# 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": "img2img",
  "parameters": {
    "width": 832,
    "height": 1216,
    "steps": 23,
    "n_samples": 1,
    "scale": 5,
    "seed": 42,
    "sampler": "k_euler_ancestral",
    "negative_prompt": "lowres, blurry",
    "image": "BASE64_OF_SOURCE_PNG",
    "strength": 0.65,
    "noise": 0
  }
}''')
body["parameters"]["image"] = base64.b64encode(Path("source.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)
