EntropyDrop commited on
Commit
627f55a
·
1 Parent(s): 1d83a33
DDJ_real2render/test_output/img16_template41_42_43.png ADDED

Git LFS Details

  • SHA256: fb95344677daea9382fc22eab47c0efb802deadf95dac3d5a09b6ae67430bbb6
  • Pointer size: 132 Bytes
  • Size of remote file: 2.71 MB
DDJ_real2render/test_output/img17_template41_42_43.png ADDED

Git LFS Details

  • SHA256: d13997b9dc7029049c77a5ca8bc5a016b652b81a22062583ee1ea048e3a1bc5f
  • Pointer size: 132 Bytes
  • Size of remote file: 2.51 MB
banana_pro_image.py CHANGED
@@ -10,69 +10,58 @@ from image_api_utils import (
10
  prepare_reference_images,
11
  )
12
 
13
- MODEL_NAME = "gemini-3-pro-image-preview"
14
 
15
 
16
- def generate_image(images=None, prompt="", aspect_ratio="1:1", image_size="2K", notify_url=None):
17
  """
18
- Triggers the image generation task using the Nano Banana Pro (gemini-3-pro-image-preview) model.
19
-
20
  :param images: Up to 14 local image paths, HTTP(S) URLs, or base64 data URLs.
21
  :param prompt: Text prompt describing the desired image content.
22
  :param aspect_ratio: Image aspect ratio. Allowed: "1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9"
23
  :param image_size: Image resolution/quality. Allowed: "1K", "2K", "4K"
24
- :param notify_url: Optional webhook URL for async callback.
25
- :return: task_id string/int
26
  """
27
- url = f"{IMAGE_API_BASE_URL}/v1/media/generate"
28
-
29
- params = {
30
- "aspectRatio": aspect_ratio,
31
- "imageSize": image_size
32
- }
33
-
34
  reference_images = prepare_reference_images(images)
35
- if reference_images:
36
- params["images"] = reference_images
37
 
38
  payload = {
39
  "model": MODEL_NAME,
40
- "params": params,
41
- "prompt": prompt
 
 
42
  }
43
-
44
- if notify_url:
45
- payload["notify_url"] = notify_url
46
 
47
  payload_body = encode_json_request(payload)
48
-
49
  headers = get_auth_headers(api_key=API_KEY)
50
- print(f"[*] Sending Banana Pro ({MODEL_NAME}) generation request to: {url}")
51
  response = requests.post(url, data=payload_body, headers=headers)
52
  response.raise_for_status()
53
  res_json = response.json()
54
-
55
- # Try parsing task_id from root or nested "data" dictionary
56
- task_id = res_json.get("task_id")
57
- if not task_id and "data" in res_json and isinstance(res_json["data"], dict):
58
- task_id = res_json["data"].get("task_id")
59
-
60
  if not task_id:
61
- raise ValueError(f"Failed to obtain task_id from response: {res_json}")
62
  print(f"[+] Task created successfully. Task ID: {task_id}")
63
  return task_id
64
 
65
 
66
- def generate_txt2img(prompt, output_path=None, aspect_ratio="1:1", image_size="2K", notify_url=None):
67
  """
68
- Text-to-image API for Nano Banana Pro (gemini-3-pro-image-preview).
69
  """
70
  task_id = generate_image(
71
  images=None,
72
  prompt=prompt,
73
  aspect_ratio=aspect_ratio,
74
  image_size=image_size,
75
- notify_url=notify_url,
76
  )
77
  return poll_and_download_result(
78
  task_id=task_id,
@@ -81,7 +70,7 @@ def generate_txt2img(prompt, output_path=None, aspect_ratio="1:1", image_size="2
81
  )
82
 
83
 
84
- def generate_img2img(local_image_paths, prompt, output_path=None, aspect_ratio="1:1", image_size="2K", notify_url=None):
85
  """
86
  Image-to-image API accepting local paths, HTTP(S) URLs, or base64 data URLs.
87
  """
@@ -90,7 +79,6 @@ def generate_img2img(local_image_paths, prompt, output_path=None, aspect_ratio="
90
  prompt=prompt,
91
  aspect_ratio=aspect_ratio,
92
  image_size=image_size,
93
- notify_url=notify_url,
94
  )
95
  return poll_and_download_result(
96
  task_id=task_id,
@@ -100,7 +88,7 @@ def generate_img2img(local_image_paths, prompt, output_path=None, aspect_ratio="
100
 
101
 
102
  if __name__ == '__main__':
103
- parser = argparse.ArgumentParser(description="Generate image using Gemini 3 Pro (Nano Banana Pro) model.")
104
  parser.add_argument("prompt", help="Text prompt for image generation.")
105
  parser.add_argument(
106
  "-i",
 
10
  prepare_reference_images,
11
  )
12
 
13
+ MODEL_NAME = "nano-banana-pro"
14
 
15
 
16
+ def generate_image(images=None, prompt="", aspect_ratio="1:1", image_size="2K"):
17
  """
18
+ Triggers an async image generation task via the Grsai nano-banana API.
19
+
20
  :param images: Up to 14 local image paths, HTTP(S) URLs, or base64 data URLs.
21
  :param prompt: Text prompt describing the desired image content.
22
  :param aspect_ratio: Image aspect ratio. Allowed: "1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9"
23
  :param image_size: Image resolution/quality. Allowed: "1K", "2K", "4K"
24
+ :return: task_id string
 
25
  """
26
+ url = f"{IMAGE_API_BASE_URL}/v1/api/generate"
27
+
 
 
 
 
 
28
  reference_images = prepare_reference_images(images)
 
 
29
 
30
  payload = {
31
  "model": MODEL_NAME,
32
+ "prompt": prompt,
33
+ "aspectRatio": aspect_ratio,
34
+ "imageSize": image_size,
35
+ "replyType": "async",
36
  }
37
+
38
+ if reference_images:
39
+ payload["images"] = reference_images
40
 
41
  payload_body = encode_json_request(payload)
42
+
43
  headers = get_auth_headers(api_key=API_KEY)
44
+ print(f"[*] Sending Banana Pro ({MODEL_NAME}) async generation request to: {url}")
45
  response = requests.post(url, data=payload_body, headers=headers)
46
  response.raise_for_status()
47
  res_json = response.json()
48
+
49
+ task_id = res_json.get("id")
 
 
 
 
50
  if not task_id:
51
+ raise ValueError(f"Failed to obtain task id from response: {res_json}")
52
  print(f"[+] Task created successfully. Task ID: {task_id}")
53
  return task_id
54
 
55
 
56
+ def generate_txt2img(prompt, output_path=None, aspect_ratio="1:1", image_size="2K"):
57
  """
58
+ Text-to-image API for Nano Banana Pro (nano-banana-pro).
59
  """
60
  task_id = generate_image(
61
  images=None,
62
  prompt=prompt,
63
  aspect_ratio=aspect_ratio,
64
  image_size=image_size,
 
65
  )
66
  return poll_and_download_result(
67
  task_id=task_id,
 
70
  )
71
 
72
 
73
+ def generate_img2img(local_image_paths, prompt, output_path=None, aspect_ratio="1:1", image_size="2K"):
74
  """
75
  Image-to-image API accepting local paths, HTTP(S) URLs, or base64 data URLs.
76
  """
 
79
  prompt=prompt,
80
  aspect_ratio=aspect_ratio,
81
  image_size=image_size,
 
82
  )
83
  return poll_and_download_result(
84
  task_id=task_id,
 
88
 
89
 
90
  if __name__ == '__main__':
91
+ parser = argparse.ArgumentParser(description="Generate image using Nano Banana Pro model via Grsai API.")
92
  parser.add_argument("prompt", help="Text prompt for image generation.")
93
  parser.add_argument(
94
  "-i",
gpt_image.py CHANGED
@@ -1,5 +1,3 @@
1
- import os
2
-
3
  import requests
4
  from image_api_utils import (
5
  IMAGE_API_BASE_URL,
@@ -10,61 +8,53 @@ from image_api_utils import (
10
  prepare_reference_images,
11
  )
12
 
13
- GPT_IMAGE_API_BASE_URL = (
14
- os.getenv("IMAGE_API_BASE_URL")
15
- or os.getenv("GPT_IMAGE_API_BASE_URL")
16
- or IMAGE_API_BASE_URL
17
- )
18
  MODEL_NAME = "gpt-image-2"
19
 
20
 
21
- def generate_image(images, prompt):
22
  """
23
- Trigger a gpt-image-2 task using local paths, URLs, or base64 data URLs.
 
 
 
 
 
 
24
  """
25
- url = f"{GPT_IMAGE_API_BASE_URL}/v1/media/generate"
26
  reference_images = prepare_reference_images(images)
 
27
  payload = {
28
  "model": MODEL_NAME,
29
- "params": {
30
- "aspect_ratio": "1:1",
31
- "images": reference_images,
32
- "n": 1,
33
- "quality": "high",
34
- "resolution": "1K",
35
- "response_format": "url",
36
- "size": "1024x1024",
37
- },
38
  "prompt": prompt,
 
 
39
  }
40
 
 
 
 
41
  payload_body = encode_json_request(payload)
42
  headers = get_auth_headers(api_key=API_KEY)
43
- print(f"[*] Sending image generation request to: {url}")
44
  response = requests.post(url, data=payload_body, headers=headers)
45
  response.raise_for_status()
46
  res_json = response.json()
47
 
48
- # Try parsing task_id from root or nested "data" dictionary
49
- task_id = res_json.get("task_id")
50
- if not task_id and "data" in res_json and isinstance(res_json["data"], dict):
51
- task_id = res_json["data"].get("task_id")
52
-
53
  if not task_id:
54
- raise ValueError(f"Failed to obtain task_id from response: {res_json}")
55
  print(f"[+] Task created successfully. Task ID: {task_id}")
56
  return task_id
57
 
58
 
59
- def generate_img2img(local_image_paths, prompt, output_path=None):
60
  """
61
  Generate an image using up to 14 local paths, URLs, or base64 data URLs.
62
  """
63
- task_id = generate_image(local_image_paths, prompt)
64
  return poll_and_download_result(
65
  task_id=task_id,
66
  output_path=output_path,
67
- default_prefix="result",
68
- api_base_url=GPT_IMAGE_API_BASE_URL,
69
- api_key=API_KEY,
70
  )
 
 
 
1
  import requests
2
  from image_api_utils import (
3
  IMAGE_API_BASE_URL,
 
8
  prepare_reference_images,
9
  )
10
 
 
 
 
 
 
11
  MODEL_NAME = "gpt-image-2"
12
 
13
 
14
+ def generate_image(images, prompt, aspect_ratio="1:1"):
15
  """
16
+ Trigger an async gpt-image-2 task via the Grsai API.
17
+
18
+ :param images: Up to 14 local image paths, HTTP(S) URLs, or base64 data URLs.
19
+ :param prompt: Text prompt describing the desired image content.
20
+ :param aspect_ratio: Image aspect ratio (e.g. "1:1", "16:9") or pixel
21
+ dimensions (e.g. "1024x1024").
22
+ :return: task_id string
23
  """
24
+ url = f"{IMAGE_API_BASE_URL}/v1/api/generate"
25
  reference_images = prepare_reference_images(images)
26
+
27
  payload = {
28
  "model": MODEL_NAME,
 
 
 
 
 
 
 
 
 
29
  "prompt": prompt,
30
+ "aspectRatio": aspect_ratio,
31
+ "replyType": "async",
32
  }
33
 
34
+ if reference_images:
35
+ payload["images"] = reference_images
36
+
37
  payload_body = encode_json_request(payload)
38
  headers = get_auth_headers(api_key=API_KEY)
39
+ print(f"[*] Sending gpt-image-2 async generation request to: {url}")
40
  response = requests.post(url, data=payload_body, headers=headers)
41
  response.raise_for_status()
42
  res_json = response.json()
43
 
44
+ task_id = res_json.get("id")
 
 
 
 
45
  if not task_id:
46
+ raise ValueError(f"Failed to obtain task id from response: {res_json}")
47
  print(f"[+] Task created successfully. Task ID: {task_id}")
48
  return task_id
49
 
50
 
51
+ def generate_img2img(local_image_paths, prompt, output_path=None, aspect_ratio="1:1"):
52
  """
53
  Generate an image using up to 14 local paths, URLs, or base64 data URLs.
54
  """
55
+ task_id = generate_image(local_image_paths, prompt, aspect_ratio=aspect_ratio)
56
  return poll_and_download_result(
57
  task_id=task_id,
58
  output_path=output_path,
59
+ default_prefix="gpt_image_result",
 
 
60
  )
image_api_utils.py CHANGED
@@ -139,50 +139,49 @@ def encode_json_request(payload):
139
 
140
  def poll_task_status(task_id, api_base_url=None, api_key=None, timeout_seconds=320, poll_interval=10):
141
  """
142
- Polls the task status with a timeout.
 
 
 
143
  """
144
  base_url = api_base_url or IMAGE_API_BASE_URL
145
- status_url = f"{base_url}/v1/media/status"
146
  start_time = time.time()
147
  print(f"[*] Polling task status (timeout={timeout_seconds}s, interval={poll_interval}s)...")
148
-
149
  headers = get_auth_headers(api_key=api_key, content_type=None)
150
-
151
  while True:
152
  elapsed = time.time() - start_time
153
  if elapsed > timeout_seconds:
154
  raise TimeoutError(f"Task {task_id} timed out after {timeout_seconds} seconds.")
155
-
156
  try:
157
- response = requests.get(status_url, params={"task_id": task_id}, headers=headers)
158
  response.raise_for_status()
159
- res_json = response.json()
160
-
161
- # Support both flat and nested responses for task status
162
- data = res_json
163
- if "data" in res_json and isinstance(res_json["data"], dict):
164
- if any(k in res_json["data"] for k in ["state", "is_final", "result_url"]):
165
- data = res_json["data"]
166
-
167
- state = data.get("state")
168
- is_final = data.get("is_final", False)
169
- progress = data.get("progress", "0%")
170
- status_text = data.get("status", "")
171
- print(f"[*] [Elapsed: {int(elapsed)}s] State: {state} ({status_text}), Progress: {progress}")
172
-
173
- if is_final:
174
- if state == "success":
175
- result_url = data.get("result_url")
176
- if not result_url:
177
- raise ValueError("Task finished with success state, but result_url is empty.")
178
- return result_url
179
- else:
180
- error_msg = data.get("error", "Unknown error")
181
- raise RuntimeError(f"Task failed with state '{state}': {error_msg}")
182
-
183
  except Exception as e:
184
  print(f"[!] Error querying task status: {e}")
185
-
186
  time.sleep(poll_interval)
187
 
188
 
 
139
 
140
  def poll_task_status(task_id, api_base_url=None, api_key=None, timeout_seconds=320, poll_interval=10):
141
  """
142
+ Polls the async task result from the Grsai nano-banana API.
143
+
144
+ Queries GET {base_url}/v1/api/result?id={task_id} until the task reaches
145
+ a terminal state (succeeded / failed / violation).
146
  """
147
  base_url = api_base_url or IMAGE_API_BASE_URL
148
+ status_url = f"{base_url}/v1/api/result"
149
  start_time = time.time()
150
  print(f"[*] Polling task status (timeout={timeout_seconds}s, interval={poll_interval}s)...")
151
+
152
  headers = get_auth_headers(api_key=api_key, content_type=None)
153
+
154
  while True:
155
  elapsed = time.time() - start_time
156
  if elapsed > timeout_seconds:
157
  raise TimeoutError(f"Task {task_id} timed out after {timeout_seconds} seconds.")
158
+
159
  try:
160
+ response = requests.get(status_url, params={"id": task_id}, headers=headers)
161
  response.raise_for_status()
162
+ data = response.json()
163
+
164
+ status = data.get("status")
165
+ progress = data.get("progress", 0)
166
+ task_id_resp = data.get("id", task_id)
167
+ print(f"[*] [Elapsed: {int(elapsed)}s] Task: {task_id_resp}, Status: {status}, Progress: {progress}%")
168
+
169
+ if status == "succeeded":
170
+ results = data.get("results", [])
171
+ if not results or not results[0].get("url"):
172
+ raise ValueError("Task succeeded but no result URL found in response.")
173
+ return results[0]["url"]
174
+
175
+ if status in ("failed", "violation"):
176
+ error_msg = data.get("error", "Unknown error")
177
+ raise RuntimeError(f"Task {status}: {error_msg}")
178
+
179
+ # status == "running" → keep polling
180
+ except (requests.RequestException, ValueError, RuntimeError, TimeoutError):
181
+ raise
 
 
 
 
182
  except Exception as e:
183
  print(f"[!] Error querying task status: {e}")
184
+
185
  time.sleep(poll_interval)
186
 
187