# Product photos from one template. Python 3.9 or newer, nothing to install.
#   export ARLEE_API_KEY=sk-...
#   python3 product-photos.py products.csv photos
import base64, csv, json, os, sys, time, urllib.error, urllib.request
from concurrent.futures import ThreadPoolExecutor

URL = os.environ.get("IMAGE_API", "https://api.arleelabs.com/v1") + "/images/generations"
KEY = os.environ["ARLEE_API_KEY"]
MODEL = os.environ.get("IMAGE_MODEL", "nano-banana-2.1")
AT_ONCE = 4        # not more than the parallel jobs of your plan
TIMEOUT = 180      # seconds; shorter than the model needs means lost pictures
TRIES = 5
RUN = time.strftime("%Y%m%d")  # the same day, the same keys: a second start repeats nothing

TEMPLATE = (
    "Studio product photo of {object} on a seamless {backdrop} paper backdrop. "
    "The object is centered and fills about half of the frame. "
    "Soft diffused light from the upper left, gentle contact shadow. "
    "Clean, minimal, square composition. No text, no logos, no labels."
)

def ask(prompt, key):
    body = json.dumps({"model": MODEL, "prompt": prompt, "size": "1024x1024"}).encode()
    request = urllib.request.Request(URL, body, {
        "Authorization": "Bearer " + KEY, "Content-Type": "application/json", "Idempotency-Key": key})
    with urllib.request.urlopen(request, timeout=TIMEOUT) as answer:
        picture = json.load(answer)["data"][0]
    if picture.get("b64_json"):
        return base64.b64decode(picture["b64_json"])
    with urllib.request.urlopen(picture["url"], timeout=TIMEOUT) as file:
        return file.read()

def extension(data):
    return ".png" if data[:4] == b"\x89PNG" else ".jpg" if data[:2] == b"\xff\xd8" else ".webp"

def make(row, folder):
    if any(name.startswith(row["id"] + ".") for name in os.listdir(folder)):
        return row["id"], "already there"
    key, spare = f"{RUN}-{row['id']}", 0
    for attempt in range(1, TRIES + 1):
        try:
            data = ask(TEMPLATE.format(**row), f"{key}-{spare}" if spare else key)
            with open(os.path.join(folder, row["id"] + extension(data)), "wb") as file:
                file.write(data)
            return row["id"], f"made on try {attempt}"
        except urllib.error.HTTPError as error:
            if error.code == 429:      # a limit: wait as long as the API says
                time.sleep(int(error.headers.get("Retry-After") or 10))
            elif error.code == 409:    # it was made, but the answer was lost: ask anew
                spare += 1
            elif error.code < 500:     # the request itself is wrong: another try will not help
                return row["id"], f"refused: {error.read().decode()[:200]}"
            else:
                time.sleep(5 * attempt)
        except OSError:                # a timeout or a broken connection
            time.sleep(5 * attempt)
    return row["id"], "gave up"

def main(table, folder):
    os.makedirs(folder, exist_ok=True)
    with open(table, newline="") as file:
        rows = list(csv.DictReader(file))
    with ThreadPoolExecutor(AT_ONCE) as pool:
        for name, what in pool.map(lambda row: make(row, folder), rows):
            print(name, what, flush=True)

main(*sys.argv[1:3])
