import os, time, requests
BASE = "https://api.genlook.app/tryon/v1"
session = requests.Session()
session.headers["x-api-key"] = os.environ["GENLOOK_API_KEY"]
def upload_customer(path: str) -> str:
with open(path, "rb") as f:
r = session.post(f"{BASE}/images/upload", files={"file": (os.path.basename(path), f)})
r.raise_for_status()
return r.json()["imageId"]
def try_on(image_id: str, product: dict) -> str:
person = {"image": {"source": {"id": image_id}}}
# Reference first: no payload, no re-analysis.
r = session.post(f"{BASE}/try-on", json={
"products": [{"externalId": product["externalId"]}], "person": person})
if r.status_code == 404 and r.json()["code"] == "PRODUCT_NOT_FOUND":
r = session.post(f"{BASE}/try-on", json={"products": [product], "person": person})
r.raise_for_status()
return r.json()["generationId"]
def wait(generation_id: str, timeout_s: int = 180) -> str:
deadline = time.time() + timeout_s
while time.time() < deadline:
data = session.get(f"{BASE}/generations/{generation_id}").json()
if data["status"] == "COMPLETED":
return data["resultImageUrl"]
if data["status"] == "FAILED":
raise RuntimeError(f"{data['errorCode']}: {data['errorMessage']}")
time.sleep(1)
raise TimeoutError(generation_id)
if __name__ == "__main__":
image_id = upload_customer("./customer.jpg")
generation_id = try_on(image_id, {
"externalId": "shirt-42",
"title": "Red cotton t-shirt",
"description": "Regular fit crew neck tee in soft cotton, short sleeves, hip length.",
"images": [{"source": {"url": "https://cdn.example.com/red-tee.jpg"}}],
})
print(wait(generation_id))