EntropyDrop commited on
Commit
db3126e
·
1 Parent(s): 60df411
Files changed (4) hide show
  1. banana_pro_image.py +43 -39
  2. gpt_image.py +31 -39
  3. gpt_skin2real.py +9 -2
  4. image_api_utils.py +130 -97
banana_pro_image.py CHANGED
@@ -1,24 +1,23 @@
1
- import os
2
  import argparse
 
3
  import requests
4
  from image_api_utils import (
5
  IMAGE_API_BASE_URL,
6
  API_KEY,
 
7
  get_auth_headers,
8
- upload_file_to_s3,
9
- delete_file_from_s3,
10
- poll_task_status,
11
- download_image,
12
- run_media_generation_pipeline
13
  )
14
 
15
  MODEL_NAME = "gemini-3-pro-image-preview"
16
 
17
- def generate_image(s3_urls=None, prompt="", aspect_ratio="1:1", image_size="2K", notify_url=None):
 
18
  """
19
  Triggers the image generation task using the Nano Banana Pro (gemini-3-pro-image-preview) model.
20
 
21
- :param s3_urls: List of reference image URLs (up to 14) for img2img, or None for txt2img.
22
  :param prompt: Text prompt describing the desired image content.
23
  :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"
24
  :param image_size: Image resolution/quality. Allowed: "1K", "2K", "4K"
@@ -32,10 +31,9 @@ def generate_image(s3_urls=None, prompt="", aspect_ratio="1:1", image_size="2K",
32
  "imageSize": image_size
33
  }
34
 
35
- if s3_urls:
36
- if isinstance(s3_urls, str):
37
- s3_urls = [s3_urls]
38
- params["images"] = s3_urls
39
 
40
  payload = {
41
  "model": MODEL_NAME,
@@ -45,10 +43,12 @@ def generate_image(s3_urls=None, prompt="", aspect_ratio="1:1", image_size="2K",
45
 
46
  if notify_url:
47
  payload["notify_url"] = notify_url
 
 
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, json=payload, headers=headers)
52
  response.raise_for_status()
53
  res_json = response.json()
54
 
@@ -62,48 +62,52 @@ def generate_image(s3_urls=None, prompt="", aspect_ratio="1:1", image_size="2K",
62
  print(f"[+] Task created successfully. Task ID: {task_id}")
63
  return task_id
64
 
 
65
  def generate_txt2img(prompt, output_path=None, aspect_ratio="1:1", image_size="2K", notify_url=None):
66
  """
67
  Text-to-image API for Nano Banana Pro (gemini-3-pro-image-preview).
68
  """
69
- def task_fn(_):
70
- return generate_image(
71
- s3_urls=None,
72
- prompt=prompt,
73
- aspect_ratio=aspect_ratio,
74
- image_size=image_size,
75
- notify_url=notify_url
76
- )
77
- return run_media_generation_pipeline(
78
- generate_task_fn=task_fn,
79
- local_image_paths=None,
80
  output_path=output_path,
81
- default_prefix="banana_pro_result"
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 for Nano Banana Pro (gemini-3-pro-image-preview).
87
  """
88
- def task_fn(s3_urls):
89
- return generate_image(
90
- s3_urls=s3_urls,
91
- prompt=prompt,
92
- aspect_ratio=aspect_ratio,
93
- image_size=image_size,
94
- notify_url=notify_url
95
- )
96
- return run_media_generation_pipeline(
97
- generate_task_fn=task_fn,
98
- local_image_paths=local_image_paths,
99
  output_path=output_path,
100
- default_prefix="banana_pro_result"
101
  )
102
 
 
103
  if __name__ == '__main__':
104
  parser = argparse.ArgumentParser(description="Generate image using Gemini 3 Pro (Nano Banana Pro) model.")
105
  parser.add_argument("prompt", help="Text prompt for image generation.")
106
- parser.add_argument("-i", "--images", nargs="+", help="Local reference image path(s) for img2img (up to 14).")
 
 
 
 
 
107
  parser.add_argument("-o", "--output", help="Output path for the generated image.")
108
  parser.add_argument("-a", "--aspect-ratio", default="1:1",
109
  choices=["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9"],
 
 
1
  import argparse
2
+
3
  import requests
4
  from image_api_utils import (
5
  IMAGE_API_BASE_URL,
6
  API_KEY,
7
+ encode_json_request,
8
  get_auth_headers,
9
+ poll_and_download_result,
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"
 
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,
 
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
 
 
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,
 
 
79
  output_path=output_path,
80
+ default_prefix="banana_pro_result",
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
  """
88
+ task_id = generate_image(
89
+ images=local_image_paths,
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,
 
 
97
  output_path=output_path,
98
+ default_prefix="banana_pro_result",
99
  )
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",
107
+ "--images",
108
+ nargs="+",
109
+ help="Reference image path(s), HTTP(S) URL(s), or base64 data URL(s), up to 14.",
110
+ )
111
  parser.add_argument("-o", "--output", help="Output path for the generated image.")
112
  parser.add_argument("-a", "--aspect-ratio", default="1:1",
113
  choices=["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9"],
gpt_image.py CHANGED
@@ -1,78 +1,70 @@
1
  import os
 
2
  import requests
3
  from image_api_utils import (
4
  IMAGE_API_BASE_URL,
5
  API_KEY,
6
- AWS_BUCKET_NAME,
7
  get_auth_headers,
8
- upload_file_to_s3 as base_upload_file_to_s3,
9
- delete_file_from_s3 as base_delete_file_from_s3,
10
- poll_task_status,
11
- download_image,
12
- run_media_generation_pipeline
13
  )
14
 
15
- # Kept for backward compatibility
16
- GPT_IMAGE_API_BASE_URL = os.getenv("IMAGE_API_BASE_URL") or os.getenv("GPT_IMAGE_API_BASE_URL") or IMAGE_API_BASE_URL
 
 
 
 
17
 
18
- def upload_file_to_s3(local_path, bucket=None, key=None):
19
- """
20
- Upload a local file to S3 (kept for backward compatibility).
21
- """
22
- s3_url, _ = base_upload_file_to_s3(local_path, bucket=bucket, key=key)
23
- return s3_url
24
 
25
- def delete_file_from_s3(bucket=None, key=None):
26
- """
27
- Cleans up temporary file from S3 (kept for backward compatibility).
28
  """
29
- base_delete_file_from_s3(bucket=bucket, key=key)
30
-
31
- def generate_image(s3_urls, prompt):
32
  """
33
- Triggers the image-to-image task using the gpt-image-2 model.
34
- """
35
- url = f"{IMAGE_API_BASE_URL}/v1/media/generate"
36
  payload = {
37
- "model": "gpt-image-2",
38
  "params": {
39
  "aspect_ratio": "1:1",
40
- "images": s3_urls,
41
  "n": 1,
42
  "quality": "high",
43
  "resolution": "1K",
44
  "response_format": "url",
45
- "size": "1024x1024"
46
  },
47
- "prompt": prompt
48
  }
49
-
 
50
  headers = get_auth_headers(api_key=API_KEY)
51
  print(f"[*] Sending image generation request to: {url}")
52
- response = requests.post(url, json=payload, headers=headers)
53
  response.raise_for_status()
54
  res_json = response.json()
55
-
56
  # Try parsing task_id from root or nested "data" dictionary
57
  task_id = res_json.get("task_id")
58
  if not task_id and "data" in res_json and isinstance(res_json["data"], dict):
59
  task_id = res_json["data"].get("task_id")
60
-
61
  if not task_id:
62
  raise ValueError(f"Failed to obtain task_id from response: {res_json}")
63
  print(f"[+] Task created successfully. Task ID: {task_id}")
64
  return task_id
65
 
 
66
  def generate_img2img(local_image_paths, prompt, output_path=None):
67
  """
68
- High-level API that handles S3 uploads, task submission, status polling, downloading, and cleanup.
69
  """
70
- def task_fn(s3_urls):
71
- return generate_image(s3_urls, prompt)
72
-
73
- return run_media_generation_pipeline(
74
- generate_task_fn=task_fn,
75
- local_image_paths=local_image_paths,
76
  output_path=output_path,
77
- default_prefix="result"
 
 
78
  )
 
1
  import os
2
+
3
  import requests
4
  from image_api_utils import (
5
  IMAGE_API_BASE_URL,
6
  API_KEY,
7
+ encode_json_request,
8
  get_auth_headers,
9
+ poll_and_download_result,
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
  )
gpt_skin2real.py CHANGED
@@ -13,11 +13,18 @@ from alice_to_steve import alice_to_steve
13
  from mc_voxel_texture_resolver import resolve_voxel_consistency
14
 
15
  def main():
16
- parser = argparse.ArgumentParser(description="Render Minecraft skin to 3D views, upload to S3, and call img2img model.")
 
 
17
  parser.add_argument("skin", help="Path to local Minecraft skin image file.")
18
  parser.add_argument("-o", "--output", help="Output path for the generated image. Defaults to 'result_<timestamp>.png'.")
19
  parser.add_argument("-p", "--prompt", default="生成ta的全身真人照片,再生成ta的背面放在图片右边。请准确还原人物的特征细节,注意真人照片里面通常不包含像素风格的装饰。", help="Prompt for the img2img model.")
20
- parser.add_argument("-r", "--render-only", action="store_true", help="Only render the 3D front and back views locally, without calling the S3/img2img pipeline.")
 
 
 
 
 
21
  args = parser.parse_args()
22
 
23
  # 1. Validate skin path
 
13
  from mc_voxel_texture_resolver import resolve_voxel_consistency
14
 
15
  def main():
16
+ parser = argparse.ArgumentParser(
17
+ description="Render Minecraft skin to 3D views and call the img2img model with base64 references."
18
+ )
19
  parser.add_argument("skin", help="Path to local Minecraft skin image file.")
20
  parser.add_argument("-o", "--output", help="Output path for the generated image. Defaults to 'result_<timestamp>.png'.")
21
  parser.add_argument("-p", "--prompt", default="生成ta的全身真人照片,再生成ta的背面放在图片右边。请准确还原人物的特征细节,注意真人照片里面通常不包含像素风格的装饰。", help="Prompt for the img2img model.")
22
+ parser.add_argument(
23
+ "-r",
24
+ "--render-only",
25
+ action="store_true",
26
+ help="Only render the 3D front and back views locally, without calling img2img.",
27
+ )
28
  args = parser.parse_args()
29
 
30
  # 1. Validate skin path
image_api_utils.py CHANGED
@@ -1,24 +1,26 @@
 
 
 
 
1
  import os
2
- import sys
3
  import time
4
- import uuid
5
  import requests
6
- import boto3
7
- import mimetypes
8
  from dotenv import load_dotenv
9
 
10
  # Load .env file from the directory of this module
11
  env_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env')
12
  load_dotenv(env_path)
13
 
14
- AWS_ACCESS_KEY_ID = os.getenv("AWS_S3_ACCESS_KEY_ID")
15
- AWS_SECRET_ACCESS_KEY = os.getenv("AWS_S3_SECRET_ACCESS_KEY")
16
- AWS_REGION = os.getenv("AWS_REGION")
17
- AWS_BUCKET_NAME = os.getenv("AWS_BUCKET_NAME")
18
-
19
  IMAGE_API_BASE_URL = os.getenv("IMAGE_API_BASE_URL")
20
  API_KEY = os.getenv("API_KEY")
21
 
 
 
 
 
 
 
22
  def get_auth_headers(api_key=None, content_type="application/json"):
23
  """
24
  Construct HTTP headers including Bearer Authorization token.
@@ -31,61 +33,109 @@ def get_auth_headers(api_key=None, content_type="application/json"):
31
  headers["Authorization"] = f"Bearer {key}"
32
  return headers
33
 
34
- def upload_file_to_s3(local_path, bucket=None, key=None):
35
- """
36
- Upload a local file to S3 with ACL='public-read' so the external API can access it.
37
- Returns (s3_url, key).
38
- """
39
- bucket = bucket or AWS_BUCKET_NAME
40
- if not AWS_ACCESS_KEY_ID or not AWS_SECRET_ACCESS_KEY:
41
- raise ValueError("AWS_S3_ACCESS_KEY_ID or AWS_S3_SECRET_ACCESS_KEY is not configured in .env.")
42
-
43
- if not key:
44
- file_ext = os.path.splitext(local_path)[1] or ".png"
45
- key = f"temp/{uuid.uuid4()}{file_ext}"
46
-
47
- print(f"[*] Uploading '{local_path}' to S3 bucket '{bucket}' with key '{key}'...")
48
- s3_client = boto3.client(
49
- 's3',
50
- aws_access_key_id=AWS_ACCESS_KEY_ID,
51
- aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
52
- region_name=AWS_REGION
53
- )
54
-
55
- content_type, _ = mimetypes.guess_type(local_path)
56
- if not content_type:
57
- content_type = 'image/png'
58
-
59
- s3_client.upload_file(
60
- local_path,
61
- bucket,
62
- key,
63
- ExtraArgs={'ACL': 'public-read', 'ContentType': content_type}
64
- )
65
-
66
- s3_url = f"https://{bucket}.s3.{AWS_REGION}.amazonaws.com/{key}"
67
- print(f"[+] Uploaded successfully. S3 public URL: {s3_url}")
68
- return s3_url, key
69
 
70
- def delete_file_from_s3(bucket=None, key=None):
71
- """
72
- Cleans up the uploaded file from S3.
73
- """
74
- bucket = bucket or AWS_BUCKET_NAME
75
- if not key:
76
- return
77
- print(f"[*] Cleaning up temporary file from S3: {key}")
78
  try:
79
- s3_client = boto3.client(
80
- 's3',
81
- aws_access_key_id=AWS_ACCESS_KEY_ID,
82
- aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
83
- region_name=AWS_REGION
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  )
85
- s3_client.delete_object(Bucket=bucket, Key=key)
86
- print("[+] Temporary file deleted from S3 successfully.")
87
- except Exception as e:
88
- print(f"[!] Failed to delete temporary S3 object: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
  def poll_task_status(task_id, api_base_url=None, api_key=None, timeout_seconds=320, poll_interval=10):
91
  """
@@ -135,6 +185,7 @@ def poll_task_status(task_id, api_base_url=None, api_key=None, timeout_seconds=3
135
 
136
  time.sleep(poll_interval)
137
 
 
138
  def download_image(url, output_path):
139
  """
140
  Downloads the final image from the given URL and saves it locally.
@@ -147,39 +198,21 @@ def download_image(url, output_path):
147
  f.write(chunk)
148
  print(f"[+] Image saved successfully to: {output_path}")
149
 
150
- def run_media_generation_pipeline(generate_task_fn, local_image_paths=None, output_path=None, default_prefix="result"):
151
- """
152
- Generic execution pipeline for media generation tasks:
153
- 1. Upload local images to S3 (if any)
154
- 2. Invoke generation task function -> returns task_id
155
- 3. Poll task status -> returns result_url
156
- 4. Download final image to output_path
157
- 5. Clean up temporary S3 objects
158
- """
159
- s3_uploaded_keys = []
160
- s3_urls = []
161
-
162
- if local_image_paths:
163
- if isinstance(local_image_paths, str):
164
- local_image_paths = [local_image_paths]
165
-
166
- for img_path in local_image_paths:
167
- if not os.path.exists(img_path):
168
- raise FileNotFoundError(f"Local file '{img_path}' does not exist.")
169
- s3_url, s3_key = upload_file_to_s3(img_path)
170
- s3_uploaded_keys.append(s3_key)
171
- s3_urls.append(s3_url)
172
-
173
- try:
174
- task_id = generate_task_fn(s3_urls if s3_urls else None)
175
- result_url = poll_task_status(task_id)
176
-
177
- if not output_path:
178
- output_path = f"{default_prefix}_{int(time.time())}.png"
179
-
180
- download_image(result_url, output_path)
181
- return output_path
182
-
183
- finally:
184
- for key in s3_uploaded_keys:
185
- delete_file_from_s3(key=key)
 
1
+ import base64
2
+ import binascii
3
+ import json
4
+ import mimetypes
5
  import os
 
6
  import time
7
+
8
  import requests
 
 
9
  from dotenv import load_dotenv
10
 
11
  # Load .env file from the directory of this module
12
  env_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env')
13
  load_dotenv(env_path)
14
 
 
 
 
 
 
15
  IMAGE_API_BASE_URL = os.getenv("IMAGE_API_BASE_URL")
16
  API_KEY = os.getenv("API_KEY")
17
 
18
+ MAX_REFERENCE_IMAGES = 14
19
+ MAX_IMAGE_BYTES = 10 * 1024 * 1024
20
+ MAX_BASE64_TOTAL_BYTES = 30 * 1024 * 1024
21
+ MAX_REQUEST_BODY_BYTES = 50 * 1024 * 1024
22
+
23
+
24
  def get_auth_headers(api_key=None, content_type="application/json"):
25
  """
26
  Construct HTTP headers including Bearer Authorization token.
 
33
  headers["Authorization"] = f"Bearer {key}"
34
  return headers
35
 
36
+ def _validate_data_url(data_url):
37
+ header, separator, encoded_data = data_url.partition(",")
38
+ header_lower = header.lower()
39
+ if (
40
+ not separator
41
+ or not header_lower.startswith("data:image/")
42
+ or ";base64" not in header_lower
43
+ ):
44
+ raise ValueError(
45
+ "Inline reference images must use the format "
46
+ "'data:image/...;base64,<data>'."
47
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
 
 
 
 
 
 
 
 
49
  try:
50
+ decoded_size = len(base64.b64decode(encoded_data, validate=True))
51
+ except (binascii.Error, ValueError) as exc:
52
+ raise ValueError("Reference image contains invalid base64 data.") from exc
53
+
54
+ if decoded_size > MAX_IMAGE_BYTES:
55
+ raise ValueError(
56
+ f"Inline reference image is {decoded_size / 1024 / 1024:.2f}MB after decoding; "
57
+ f"the maximum is {MAX_IMAGE_BYTES / 1024 / 1024:.0f}MB."
58
+ )
59
+ return decoded_size
60
+
61
+
62
+ def _local_image_to_data_url(image_path):
63
+ image_path = os.fspath(image_path)
64
+ if not os.path.isfile(image_path):
65
+ raise FileNotFoundError(f"Local reference image '{image_path}' does not exist.")
66
+
67
+ file_size = os.path.getsize(image_path)
68
+ if file_size > MAX_IMAGE_BYTES:
69
+ raise ValueError(
70
+ f"Reference image '{image_path}' is {file_size / 1024 / 1024:.2f}MB; "
71
+ f"the maximum is {MAX_IMAGE_BYTES / 1024 / 1024:.0f}MB."
72
+ )
73
+
74
+ mime_type, _ = mimetypes.guess_type(image_path)
75
+ if not mime_type or not mime_type.startswith("image/"):
76
+ raise ValueError(
77
+ f"Could not determine an image MIME type for '{image_path}'. "
78
+ "Use a standard image extension such as .png, .jpg, .webp, or .gif."
79
  )
80
+
81
+ print(f"[*] Encoding local reference image as base64: {image_path}")
82
+ with open(image_path, "rb") as image_file:
83
+ image_data = image_file.read()
84
+ encoded_data = base64.b64encode(image_data).decode("ascii")
85
+ return f"data:{mime_type};base64,{encoded_data}", file_size
86
+
87
+
88
+ def prepare_reference_images(image_inputs):
89
+ """Convert local paths to data URLs and validate reference image limits."""
90
+ if not image_inputs:
91
+ return None
92
+ if isinstance(image_inputs, (str, os.PathLike)):
93
+ image_inputs = [image_inputs]
94
+ else:
95
+ image_inputs = list(image_inputs)
96
+
97
+ if len(image_inputs) > MAX_REFERENCE_IMAGES:
98
+ raise ValueError(
99
+ f"At most {MAX_REFERENCE_IMAGES} reference images are allowed; "
100
+ f"received {len(image_inputs)}."
101
+ )
102
+
103
+ images = []
104
+ base64_total_bytes = 0
105
+ for image_input in image_inputs:
106
+ value = os.fspath(image_input)
107
+ value_lower = value.lower()
108
+ if value_lower.startswith(("http://", "https://")):
109
+ images.append(value)
110
+ continue
111
+ if value_lower.startswith("data:"):
112
+ decoded_size = _validate_data_url(value)
113
+ images.append(value)
114
+ else:
115
+ data_url, decoded_size = _local_image_to_data_url(value)
116
+ images.append(data_url)
117
+
118
+ base64_total_bytes += decoded_size
119
+ if base64_total_bytes > MAX_BASE64_TOTAL_BYTES:
120
+ raise ValueError(
121
+ f"Base64 reference images total {base64_total_bytes / 1024 / 1024:.2f}MB "
122
+ f"after decoding; the maximum is "
123
+ f"{MAX_BASE64_TOTAL_BYTES / 1024 / 1024:.0f}MB."
124
+ )
125
+
126
+ return images
127
+
128
+
129
+ def encode_json_request(payload):
130
+ """Serialize a JSON request and enforce the API's request-body size limit."""
131
+ payload_body = json.dumps(payload, ensure_ascii=False, allow_nan=False).encode("utf-8")
132
+ if len(payload_body) > MAX_REQUEST_BODY_BYTES:
133
+ raise ValueError(
134
+ f"Request body is {len(payload_body) / 1024 / 1024:.2f}MB; "
135
+ f"the maximum is {MAX_REQUEST_BODY_BYTES / 1024 / 1024:.0f}MB."
136
+ )
137
+ return payload_body
138
+
139
 
140
  def poll_task_status(task_id, api_base_url=None, api_key=None, timeout_seconds=320, poll_interval=10):
141
  """
 
185
 
186
  time.sleep(poll_interval)
187
 
188
+
189
  def download_image(url, output_path):
190
  """
191
  Downloads the final image from the given URL and saves it locally.
 
198
  f.write(chunk)
199
  print(f"[+] Image saved successfully to: {output_path}")
200
 
201
+
202
+ def poll_and_download_result(
203
+ task_id,
204
+ output_path=None,
205
+ default_prefix="result",
206
+ api_base_url=None,
207
+ api_key=None,
208
+ ):
209
+ """Poll a media task and download its final image."""
210
+ result_url = poll_task_status(
211
+ task_id,
212
+ api_base_url=api_base_url,
213
+ api_key=api_key,
214
+ )
215
+ if not output_path:
216
+ output_path = f"{default_prefix}_{int(time.time())}.png"
217
+ download_image(result_url, output_path)
218
+ return output_path