# Python 3; standard library only. Set NOVEA_API_KEY first.
import os, json, base64, uuid
from pathlib import Path
from urllib.request import Request, urlopen
from urllib.error import HTTPError

# Set NOVEA_REQUEST_ID to the same value when retrying this exact request.
request_id = os.environ.get("NOVEA_REQUEST_ID") or str(uuid.uuid4())
print("Request ID:", request_id)
body = json.loads(r'''{
  "input": "watercolor, two adults in a quiet garden",
  "model": "nai-diffusion-4-5-full",
  "action": "generate",
  "parameters": {
    "width": 832,
    "height": 1216,
    "steps": 23,
    "n_samples": 1,
    "scale": 5,
    "seed": 42,
    "sampler": "k_euler_ancestral",
    "negative_prompt": "lowres, blurry",
    "v4_prompt": {
      "caption": {
        "base_caption": "watercolor, two adults in a quiet garden",
        "char_captions": [
          {
            "char_caption": "adult painter, blue coat, holding a sketchbook",
            "centers": [
              {
                "x": 0.3,
                "y": 0.5
              }
            ]
          },
          {
            "char_caption": "adult gardener, straw hat, holding flowers",
            "centers": [
              {
                "x": 0.7,
                "y": 0.5
              }
            ]
          }
        ]
      },
      "use_coords": false,
      "use_order": true
    },
    "v4_negative_prompt": {
      "caption": {
        "base_caption": "lowres, blurry",
        "char_captions": [
          {
            "char_caption": "",
            "centers": [
              {
                "x": 0.3,
                "y": 0.5
              }
            ]
          },
          {
            "char_caption": "",
            "centers": [
              {
                "x": 0.7,
                "y": 0.5
              }
            ]
          }
        ]
      },
      "use_coords": false,
      "use_order": true
    }
  }
}''')

request = Request(
    "https://noveadream.com/ai/generate-image",
    data=json.dumps(body).encode("utf-8"),
    headers={
        "Authorization": "Bearer " + os.environ["NOVEA_API_KEY"],
        "Content-Type": "application/json",
        "Accept": "application/json",
        "Idempotency-Key": request_id,
    }, method="POST",
)
try:
    with urlopen(request, timeout=660) as response:
        print("Generation ID:", response.headers.get("X-Generation-ID"))
        result = json.load(response)
except HTTPError as error:
    raise SystemExit(f"HTTP {error.code}: {error.read().decode('utf-8', errors='replace')}")
for index, item in enumerate(result["images"]):
    path = Path(f"image_{index}.png")
    path.write_bytes(base64.b64decode(item["image"]))
    print("Saved:", path)
