fix(openai-image-gen): handle url and b64_json responses

Co-authored-by: Yurii Chukhlib <yuri.v.chu@gmail.com>
This commit is contained in:
Peter Steinberger
2026-01-16 23:51:08 +00:00
parent 13e2dd97a7
commit a979a62f8e

View File

@@ -1,5 +1,6 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import argparse import argparse
import base64
import datetime as dt import datetime as dt
import json import json
import os import os
@@ -211,18 +212,21 @@ def main() -> int:
args.output_format, args.output_format,
args.style, args.style,
) )
# OpenAI Images API now returns URLs by default data = res.get("data", [{}])[0]
image_url = res.get("data", [{}])[0].get("url") image_b64 = data.get("b64_json")
if not image_url: image_url = data.get("url")
if not image_b64 and not image_url:
raise RuntimeError(f"Unexpected response: {json.dumps(res)[:400]}") raise RuntimeError(f"Unexpected response: {json.dumps(res)[:400]}")
# Download image from URL
filename = f"{idx:03d}-{slugify(prompt)[:40]}.{file_ext}" filename = f"{idx:03d}-{slugify(prompt)[:40]}.{file_ext}"
filepath = out_dir / filename filepath = out_dir / filename
try: if image_b64:
urllib.request.urlretrieve(image_url, filepath) filepath.write_bytes(base64.b64decode(image_b64))
except urllib.error.URLError as e: else:
raise RuntimeError(f"Failed to download image from {image_url}: {e}") from e try:
urllib.request.urlretrieve(image_url, filepath)
except urllib.error.URLError as e:
raise RuntimeError(f"Failed to download image from {image_url}: {e}") from e
items.append({"prompt": prompt, "file": filename}) items.append({"prompt": prompt, "file": filename})