EntropyDrop commited on
Commit
72b170b
·
1 Parent(s): c184c98

feat: add Nano Banana Pro image API support and extract common image API utilities

Browse files
Files changed (3) hide show
  1. banana_pro_image.py +128 -0
  2. gpt_image.py +33 -163
  3. image_api_utils.py +185 -0
banana_pro_image.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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"
25
+ :param notify_url: Optional webhook URL for async callback.
26
+ :return: task_id string/int
27
+ """
28
+ url = f"{IMAGE_API_BASE_URL}/v1/media/generate"
29
+
30
+ params = {
31
+ "aspectRatio": aspect_ratio,
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,
42
+ "params": params,
43
+ "prompt": prompt
44
+ }
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
+
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
+ 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"],
110
+ help="Aspect ratio (default: 1:1).")
111
+ parser.add_argument("-s", "--image-size", default="2K", choices=["1K", "2K", "4K"], help="Resolution size (default: 2K).")
112
+ args = parser.parse_args()
113
+
114
+ if args.images:
115
+ generate_img2img(
116
+ local_image_paths=args.images,
117
+ prompt=args.prompt,
118
+ output_path=args.output,
119
+ aspect_ratio=args.aspect_ratio,
120
+ image_size=args.image_size
121
+ )
122
+ else:
123
+ generate_txt2img(
124
+ prompt=args.prompt,
125
+ output_path=args.output,
126
+ aspect_ratio=args.aspect_ratio,
127
+ image_size=args.image_size
128
+ )
gpt_image.py CHANGED
@@ -1,57 +1,38 @@
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 current directory
11
- env_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env')
12
- load_dotenv(env_path)
13
 
14
- # Retrieve configuration details
15
- AWS_ACCESS_KEY_ID = os.getenv("AWS_S3_ACCESS_KEY_ID")
16
- AWS_SECRET_ACCESS_KEY = os.getenv("AWS_S3_SECRET_ACCESS_KEY")
17
- AWS_REGION = os.getenv("AWS_REGION")
18
- AWS_BUCKET_NAME = os.getenv("AWS_BUCKET_NAME")
19
- GPT_IMAGE_API_BASE_URL = os.getenv("GPT_IMAGE_API_BASE_URL")
20
- API_KEY = os.getenv("API_KEY")
21
-
22
- def upload_file_to_s3(local_path, bucket, key):
23
  """
24
- Upload a local file to S3 with ACL='public-read' so the external API can access it.
25
  """
26
- print(f"[*] Uploading '{local_path}' to S3 bucket '{bucket}' with key '{key}'...")
27
- s3_client = boto3.client(
28
- 's3',
29
- aws_access_key_id=AWS_ACCESS_KEY_ID,
30
- aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
31
- region_name=AWS_REGION
32
- )
33
-
34
- # Guess mime type or default to image/png
35
- content_type, _ = mimetypes.guess_type(local_path)
36
- if not content_type:
37
- content_type = 'image/png'
38
-
39
- s3_client.upload_file(
40
- local_path,
41
- bucket,
42
- key,
43
- ExtraArgs={'ACL': 'public-read', 'ContentType': content_type}
44
- )
45
-
46
- s3_url = f"https://{bucket}.s3.{AWS_REGION}.amazonaws.com/{key}"
47
- print(f"[+] Uploaded successfully. S3 public URL: {s3_url}")
48
  return s3_url
49
 
 
 
 
 
 
 
50
  def generate_image(s3_urls, prompt):
51
  """
52
  Triggers the image-to-image task using the gpt-image-2 model.
53
  """
54
- url = f"{GPT_IMAGE_API_BASE_URL}/v1/media/generate"
55
  payload = {
56
  "model": "gpt-image-2",
57
  "params": {
@@ -66,10 +47,7 @@ def generate_image(s3_urls, prompt):
66
  "prompt": prompt
67
  }
68
 
69
- headers = {"Content-Type": "application/json"}
70
- if API_KEY:
71
- headers["Authorization"] = f"Bearer {API_KEY}"
72
-
73
  print(f"[*] Sending image generation request to: {url}")
74
  response = requests.post(url, json=payload, headers=headers)
75
  response.raise_for_status()
@@ -85,124 +63,16 @@ def generate_image(s3_urls, prompt):
85
  print(f"[+] Task created successfully. Task ID: {task_id}")
86
  return task_id
87
 
88
- def poll_task_status(task_id, timeout_seconds=320, poll_interval=10):
89
- """
90
- Polls the task status with a timeout.
91
- """
92
- status_url = f"{GPT_IMAGE_API_BASE_URL}/v1/media/status"
93
- start_time = time.time()
94
- print(f"[*] Polling task status (timeout={timeout_seconds}s, interval={poll_interval}s)...")
95
-
96
- while True:
97
- elapsed = time.time() - start_time
98
- if elapsed > timeout_seconds:
99
- raise TimeoutError(f"Task {task_id} timed out after {timeout_seconds} seconds.")
100
-
101
- try:
102
- headers = {}
103
- if API_KEY:
104
- headers["Authorization"] = f"Bearer {API_KEY}"
105
- response = requests.get(status_url, params={"task_id": task_id}, headers=headers)
106
- response.raise_for_status()
107
- res_json = response.json()
108
-
109
- # Support both flat and nested responses for task status
110
- data = res_json
111
- if "data" in res_json and isinstance(res_json["data"], dict):
112
- if any(k in res_json["data"] for k in ["state", "is_final", "result_url"]):
113
- data = res_json["data"]
114
-
115
- state = data.get("state")
116
- is_final = data.get("is_final", False)
117
- progress = data.get("progress", "0%")
118
- print(f"[*] [Elapsed: {int(elapsed)}s] State: {state}, Progress: {progress}")
119
-
120
- if is_final:
121
- if state == "success":
122
- result_url = data.get("result_url")
123
- if not result_url:
124
- raise ValueError("Task finished with success state, but result_url is empty.")
125
- return result_url
126
- else:
127
- error_msg = data.get("error", "Unknown error")
128
- raise RuntimeError(f"Task failed with state '{state}': {error_msg}")
129
-
130
- except Exception as e:
131
- # Print error and retry during polling
132
- print(f"[!] Error querying task status: {e}")
133
-
134
- time.sleep(poll_interval)
135
-
136
- def download_image(url, output_path):
137
- """
138
- Downloads the final image from the given URL and saves it locally.
139
- """
140
- print(f"[*] Downloading result image from: {url}")
141
- response = requests.get(url, stream=True)
142
- response.raise_for_status()
143
- with open(output_path, "wb") as f:
144
- for chunk in response.iter_content(chunk_size=8192):
145
- f.write(chunk)
146
- print(f"[+] Image saved successfully to: {output_path}")
147
-
148
- def delete_file_from_s3(bucket, key):
149
- """
150
- Cleans up the uploaded file from S3.
151
- """
152
- print(f"[*] Cleaning up temporary file from S3: {key}")
153
- try:
154
- s3_client = boto3.client(
155
- 's3',
156
- aws_access_key_id=AWS_ACCESS_KEY_ID,
157
- aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
158
- region_name=AWS_REGION
159
- )
160
- s3_client.delete_object(Bucket=bucket, Key=key)
161
- print("[+] Temporary file deleted from S3 successfully.")
162
- except Exception as e:
163
- print(f"[!] Failed to delete temporary S3 object: {e}")
164
-
165
  def generate_img2img(local_image_paths, prompt, output_path=None):
166
  """
167
- High-level API that does:
168
- 1. S3 uploads
169
- 2. Model task trigger
170
- 3. Status polling
171
- 4. Saving result locally
172
- 5. Clean up S3 temporary files
173
  """
174
- if not AWS_ACCESS_KEY_ID or not AWS_SECRET_ACCESS_KEY:
175
- raise ValueError("AWS_S3_ACCESS_KEY_ID or AWS_S3_SECRET_ACCESS_KEY is not configured in .env.")
176
-
177
- # Validate that all input files exist
178
- for img_path in local_image_paths:
179
- if not os.path.exists(img_path):
180
- raise FileNotFoundError(f"Local file '{img_path}' does not exist.")
181
-
182
- s3_uploaded_keys = []
183
- s3_urls = []
184
- try:
185
- # 1. Upload the local images to S3
186
- for img_path in local_image_paths:
187
- file_ext = os.path.splitext(img_path)[1] or ".png"
188
- s3_temp_key = f"temp/{uuid.uuid4()}{file_ext}"
189
- s3_url = upload_file_to_s3(img_path, AWS_BUCKET_NAME, s3_temp_key)
190
- s3_uploaded_keys.append(s3_temp_key)
191
- s3_urls.append(s3_url)
192
-
193
- # 2. Invoke the image-to-image model
194
- task_id = generate_image(s3_urls, prompt)
195
 
196
- # 3. Poll for the task status with a 2-minute timeout
197
- result_url = poll_task_status(task_id)
198
-
199
- # 4. Save the result to the output path
200
- if not output_path:
201
- output_path = f"result_{int(time.time())}.png"
202
- download_image(result_url, output_path)
203
- return output_path
204
-
205
- finally:
206
- # 5. Clean up S3 temporary files
207
- for key in s3_uploaded_keys:
208
- delete_file_from_s3(AWS_BUCKET_NAME, key)
 
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": {
 
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()
 
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
+ )
 
 
 
 
 
 
 
image_api_utils.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.
25
+ """
26
+ key = api_key or API_KEY
27
+ headers = {}
28
+ if content_type:
29
+ headers["Content-Type"] = content_type
30
+ if key:
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
+ """
92
+ Polls the task status with a timeout.
93
+ """
94
+ base_url = api_base_url or IMAGE_API_BASE_URL
95
+ status_url = f"{base_url}/v1/media/status"
96
+ start_time = time.time()
97
+ print(f"[*] Polling task status (timeout={timeout_seconds}s, interval={poll_interval}s)...")
98
+
99
+ headers = get_auth_headers(api_key=api_key, content_type=None)
100
+
101
+ while True:
102
+ elapsed = time.time() - start_time
103
+ if elapsed > timeout_seconds:
104
+ raise TimeoutError(f"Task {task_id} timed out after {timeout_seconds} seconds.")
105
+
106
+ try:
107
+ response = requests.get(status_url, params={"task_id": task_id}, headers=headers)
108
+ response.raise_for_status()
109
+ res_json = response.json()
110
+
111
+ # Support both flat and nested responses for task status
112
+ data = res_json
113
+ if "data" in res_json and isinstance(res_json["data"], dict):
114
+ if any(k in res_json["data"] for k in ["state", "is_final", "result_url"]):
115
+ data = res_json["data"]
116
+
117
+ state = data.get("state")
118
+ is_final = data.get("is_final", False)
119
+ progress = data.get("progress", "0%")
120
+ status_text = data.get("status", "")
121
+ print(f"[*] [Elapsed: {int(elapsed)}s] State: {state} ({status_text}), Progress: {progress}")
122
+
123
+ if is_final:
124
+ if state == "success":
125
+ result_url = data.get("result_url")
126
+ if not result_url:
127
+ raise ValueError("Task finished with success state, but result_url is empty.")
128
+ return result_url
129
+ else:
130
+ error_msg = data.get("error", "Unknown error")
131
+ raise RuntimeError(f"Task failed with state '{state}': {error_msg}")
132
+
133
+ except Exception as e:
134
+ print(f"[!] Error querying task status: {e}")
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.
141
+ """
142
+ print(f"[*] Downloading result image from: {url}")
143
+ response = requests.get(url, stream=True)
144
+ response.raise_for_status()
145
+ with open(output_path, "wb") as f:
146
+ for chunk in response.iter_content(chunk_size=8192):
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)