| import os |
|
|
| import requests |
| from image_api_utils import ( |
| IMAGE_API_BASE_URL, |
| API_KEY, |
| encode_json_request, |
| get_auth_headers, |
| poll_and_download_result, |
| prepare_reference_images, |
| ) |
|
|
| GPT_IMAGE_API_BASE_URL = ( |
| os.getenv("IMAGE_API_BASE_URL") |
| or os.getenv("GPT_IMAGE_API_BASE_URL") |
| or IMAGE_API_BASE_URL |
| ) |
| MODEL_NAME = "gpt-image-2" |
|
|
|
|
| def generate_image(images, prompt): |
| """ |
| Trigger a gpt-image-2 task using local paths, URLs, or base64 data URLs. |
| """ |
| url = f"{GPT_IMAGE_API_BASE_URL}/v1/media/generate" |
| reference_images = prepare_reference_images(images) |
| payload = { |
| "model": MODEL_NAME, |
| "params": { |
| "aspect_ratio": "1:1", |
| "images": reference_images, |
| "n": 1, |
| "quality": "high", |
| "resolution": "1K", |
| "response_format": "url", |
| "size": "1024x1024", |
| }, |
| "prompt": prompt, |
| } |
|
|
| payload_body = encode_json_request(payload) |
| headers = get_auth_headers(api_key=API_KEY) |
| print(f"[*] Sending image generation request to: {url}") |
| response = requests.post(url, data=payload_body, headers=headers) |
| response.raise_for_status() |
| res_json = response.json() |
|
|
| |
| 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 generate_img2img(local_image_paths, prompt, output_path=None): |
| """ |
| Generate an image using up to 14 local paths, URLs, or base64 data URLs. |
| """ |
| task_id = generate_image(local_image_paths, prompt) |
| return poll_and_download_result( |
| task_id=task_id, |
| output_path=output_path, |
| default_prefix="result", |
| api_base_url=GPT_IMAGE_API_BASE_URL, |
| api_key=API_KEY, |
| ) |
|
|