Sking / gpt_image.py
EntropyDrop
v93
343d151
Raw
History Blame
7.49 kB
import os
import sys
import time
import uuid
import requests
import boto3
import mimetypes
from dotenv import load_dotenv
# Load .env file from the current directory
env_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env')
load_dotenv(env_path)
# Retrieve configuration details
AWS_ACCESS_KEY_ID = os.getenv("AWS_S3_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = os.getenv("AWS_S3_SECRET_ACCESS_KEY")
AWS_REGION = os.getenv("AWS_REGION")
AWS_BUCKET_NAME = os.getenv("AWS_BUCKET_NAME")
GPT_IMAGE_API_BASE_URL = os.getenv("GPT_IMAGE_API_BASE_URL")
API_KEY = os.getenv("API_KEY")
def upload_file_to_s3(local_path, bucket, key):
"""
Upload a local file to S3 with ACL='public-read' so the external API can access it.
"""
print(f"[*] Uploading '{local_path}' to S3 bucket '{bucket}' with key '{key}'...")
s3_client = boto3.client(
's3',
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
region_name=AWS_REGION
)
# Guess mime type or default to image/png
content_type, _ = mimetypes.guess_type(local_path)
if not content_type:
content_type = 'image/png'
s3_client.upload_file(
local_path,
bucket,
key,
ExtraArgs={'ACL': 'public-read', 'ContentType': content_type}
)
s3_url = f"https://{bucket}.s3.{AWS_REGION}.amazonaws.com/{key}"
print(f"[+] Uploaded successfully. S3 public URL: {s3_url}")
return s3_url
def generate_image(s3_urls, prompt):
"""
Triggers the image-to-image task using the gpt-image-2 model.
"""
url = f"{GPT_IMAGE_API_BASE_URL}/v1/media/generate"
payload = {
"model": "gpt-image-2",
"params": {
"aspect_ratio": "1:1",
"images": s3_urls,
"n": 1,
"quality": "high",
"resolution": "1K",
"response_format": "url",
"size": "1024x1024"
},
"prompt": prompt
}
headers = {"Content-Type": "application/json"}
if API_KEY:
headers["Authorization"] = f"Bearer {API_KEY}"
print(f"[*] Sending image generation request to: {url}")
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()
res_json = response.json()
# Try parsing task_id from root or nested "data" dictionary
task_id = res_json.get("task_id")
if not task_id and "data" in res_json and isinstance(res_json["data"], dict):
task_id = res_json["data"].get("task_id")
if not task_id:
raise ValueError(f"Failed to obtain task_id from response: {res_json}")
print(f"[+] Task created successfully. Task ID: {task_id}")
return task_id
def poll_task_status(task_id, timeout_seconds=320, poll_interval=10):
"""
Polls the task status with a timeout.
"""
status_url = f"{GPT_IMAGE_API_BASE_URL}/v1/media/status"
start_time = time.time()
print(f"[*] Polling task status (timeout={timeout_seconds}s, interval={poll_interval}s)...")
while True:
elapsed = time.time() - start_time
if elapsed > timeout_seconds:
raise TimeoutError(f"Task {task_id} timed out after {timeout_seconds} seconds.")
try:
headers = {}
if API_KEY:
headers["Authorization"] = f"Bearer {API_KEY}"
response = requests.get(status_url, params={"task_id": task_id}, headers=headers)
response.raise_for_status()
res_json = response.json()
# Support both flat and nested responses for task status
data = res_json
if "data" in res_json and isinstance(res_json["data"], dict):
if any(k in res_json["data"] for k in ["state", "is_final", "result_url"]):
data = res_json["data"]
state = data.get("state")
is_final = data.get("is_final", False)
progress = data.get("progress", "0%")
print(f"[*] [Elapsed: {int(elapsed)}s] State: {state}, Progress: {progress}")
if is_final:
if state == "success":
result_url = data.get("result_url")
if not result_url:
raise ValueError("Task finished with success state, but result_url is empty.")
return result_url
else:
error_msg = data.get("error", "Unknown error")
raise RuntimeError(f"Task failed with state '{state}': {error_msg}")
except Exception as e:
# Print error and retry during polling
print(f"[!] Error querying task status: {e}")
time.sleep(poll_interval)
def download_image(url, output_path):
"""
Downloads the final image from the given URL and saves it locally.
"""
print(f"[*] Downloading result image from: {url}")
response = requests.get(url, stream=True)
response.raise_for_status()
with open(output_path, "wb") as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
print(f"[+] Image saved successfully to: {output_path}")
def delete_file_from_s3(bucket, key):
"""
Cleans up the uploaded file from S3.
"""
print(f"[*] Cleaning up temporary file from S3: {key}")
try:
s3_client = boto3.client(
's3',
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
region_name=AWS_REGION
)
s3_client.delete_object(Bucket=bucket, Key=key)
print("[+] Temporary file deleted from S3 successfully.")
except Exception as e:
print(f"[!] Failed to delete temporary S3 object: {e}")
def generate_img2img(local_image_paths, prompt, output_path=None):
"""
High-level API that does:
1. S3 uploads
2. Model task trigger
3. Status polling
4. Saving result locally
5. Clean up S3 temporary files
"""
if not AWS_ACCESS_KEY_ID or not AWS_SECRET_ACCESS_KEY:
raise ValueError("AWS_S3_ACCESS_KEY_ID or AWS_S3_SECRET_ACCESS_KEY is not configured in .env.")
# Validate that all input files exist
for img_path in local_image_paths:
if not os.path.exists(img_path):
raise FileNotFoundError(f"Local file '{img_path}' does not exist.")
s3_uploaded_keys = []
s3_urls = []
try:
# 1. Upload the local images to S3
for img_path in local_image_paths:
file_ext = os.path.splitext(img_path)[1] or ".png"
s3_temp_key = f"temp/{uuid.uuid4()}{file_ext}"
s3_url = upload_file_to_s3(img_path, AWS_BUCKET_NAME, s3_temp_key)
s3_uploaded_keys.append(s3_temp_key)
s3_urls.append(s3_url)
# 2. Invoke the image-to-image model
task_id = generate_image(s3_urls, prompt)
# 3. Poll for the task status with a 2-minute timeout
result_url = poll_task_status(task_id)
# 4. Save the result to the output path
if not output_path:
output_path = f"result_{int(time.time())}.png"
download_image(result_url, output_path)
return output_path
finally:
# 5. Clean up S3 temporary files
for key in s3_uploaded_keys:
delete_file_from_s3(AWS_BUCKET_NAME, key)