| 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, |
| ) |
|
|
| MODEL_NAME = "gpt-image-2" |
|
|
|
|
| def generate_image(images, prompt, aspect_ratio="1:1"): |
| """ |
| Trigger an async gpt-image-2 task via the Grsai API. |
| |
| :param images: Up to 14 local image paths, HTTP(S) URLs, or base64 data URLs. |
| :param prompt: Text prompt describing the desired image content. |
| :param aspect_ratio: Image aspect ratio (e.g. "1:1", "16:9") or pixel |
| dimensions (e.g. "1024x1024"). |
| :return: task_id string |
| """ |
| url = f"{IMAGE_API_BASE_URL}/v1/api/generate" |
| reference_images = prepare_reference_images(images) |
|
|
| payload = { |
| "model": MODEL_NAME, |
| "prompt": prompt, |
| "aspectRatio": aspect_ratio, |
| "replyType": "async", |
| } |
|
|
| if reference_images: |
| payload["images"] = reference_images |
|
|
| payload_body = encode_json_request(payload) |
| headers = get_auth_headers(api_key=API_KEY) |
| print(f"[*] Sending gpt-image-2 async 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("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, aspect_ratio="1:1"): |
| """ |
| Generate an image using up to 14 local paths, URLs, or base64 data URLs. |
| """ |
| task_id = generate_image(local_image_paths, prompt, aspect_ratio=aspect_ratio) |
| return poll_and_download_result( |
| task_id=task_id, |
| output_path=output_path, |
| default_prefix="gpt_image_result", |
| ) |
|
|