# 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, a blue ceramic teapot on a wooden table, soft daylight",
  "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",
    "director_reference_images": [
      "BASE64_OF_REFERENCE_PNG"
    ],
    "director_reference_descriptions": [
      {
        "caption": {
          "base_caption": "character",
          "char_captions": []
        }
      }
    ],
    "director_reference_strength_values": [
      1
    ],
    "director_reference_secondary_strength_values": [
      0.3
    ],
    "director_reference_information_extracted": [
      1
    ]
  }
}''')
body["parameters"]["director_reference_images"] = [base64.b64encode(Path("reference.png").read_bytes()).decode("ascii")]
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)
