File size: 1,912 Bytes
2add930
72b170b
 
 
db3126e
72b170b
db3126e
 
72b170b
2add930
db3126e
2add930
 
627f55a
72b170b
627f55a
 
 
 
 
 
 
2add930
627f55a
db3126e
627f55a
2add930
db3126e
 
627f55a
 
2add930
db3126e
627f55a
 
 
db3126e
72b170b
627f55a
db3126e
2add930
 
db3126e
627f55a
2add930
627f55a
2add930
 
 
db3126e
627f55a
2add930
db3126e
2add930
627f55a
db3126e
 
72b170b
627f55a
72b170b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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",
    )