Skip to content

Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.

gen: add an openai Images provider that needs only OPENAI_API_KEY

Soohong Kim21034bf2898c
diff --git a/sprite_gen/cli.py b/sprite_gen/cli.py
index 0fff49e..1d1b6ad 100644
--- a/sprite_gen/cli.py
+++ b/sprite_gen/cli.py
@@ -293,7 +293,7 @@ COMMANDS: dict[str, tuple[str, Callable[[argparse.ArgumentParser], None], Callab
slice_sheet.run,
),
"gen": (
- "Generate one image via a provider (codex image_gen / grok Imagine) into a verified PNG.",
+ "Generate one image via a provider (codex image_gen / grok Imagine / openai Images API) into a verified PNG.",
_add_gen,
gen.run,
),
diff --git a/sprite_gen/gen/__init__.py b/sprite_gen/gen/__init__.py
index 82e760c..78469fd 100644
--- a/sprite_gen/gen/__init__.py
+++ b/sprite_gen/gen/__init__.py
@@ -2,20 +2,27 @@
"""Unified image generation layer for sprite-gen.
Single source of truth for provider-backed image generation: codex (`image_gen`,
-ChatGPT OAuth) and grok (Imagine, xAI OAuth). One call = prompt (+ optional refs)
--> one verified raw PNG, with an optional deterministic transparent chroma
-post-process. The general `image-gen` skill is a thin shuttle over `sprite-gen gen`.
+ChatGPT OAuth), grok (Imagine, xAI OAuth) and openai (Images REST, OPENAI_API_KEY).
+One call = prompt (+ optional refs) -> one verified raw PNG, with an optional
+deterministic transparent chroma post-process. The general `image-gen` skill is a
+thin shuttle over `sprite-gen gen`.
+
+codex and openai reach the same family of GPT image models by different routes:
+codex needs an interactive ChatGPT login and the `codex` CLI on PATH, openai needs
+only an API key, which is what a headless container (Modal worker, CI) can have.
Transparency is a per-provider strategy (`Provider.transparency`, declared once
-in each adapter): codex `image_gen` returns a genuinely transparent PNG when asked
-(`native`), grok Imagine cannot and is keyed out of a chroma background (`chroma`).
-`--transparent` follows the provider's strategy unless `--alpha-mode` overrides it.
+in each adapter): codex `image_gen` and openai (`background: transparent`) return a
+genuinely transparent PNG when asked (`native`), grok Imagine cannot and is keyed
+out of a chroma background (`chroma`). `--transparent` follows the provider's
+strategy unless `--alpha-mode` overrides it.
CLI:
- sprite-gen gen --provider codex|grok --prompt "..." --out DEST.png
+ sprite-gen gen --provider codex|grok|openai --prompt "..." --out DEST.png
[--ref REF.png ...] [--transparent [--alpha-mode auto|native|chroma]
[--chroma-key magenta|green]] [--white-check CHECK.png] [--model ID]
- [--aspect-ratio 1:1] [--report REPORT.json] [--keep-session]
+ [--aspect-ratio 1:1] [--quality low|medium|high|xhigh|max|auto]
+ [--report REPORT.json] [--keep-session]
"""
from __future__ import annotations
@@ -34,6 +41,7 @@ from sprite_gen.spec.runio import atomic_write_text
from . import chroma as chroma_mod
from .base import (
+ QUALITIES,
TRANSPARENCY_CHROMA,
TRANSPARENCY_NATIVE,
TRANSPARENCY_STRATEGIES,
@@ -46,8 +54,9 @@ from .base import (
)
from .codex_provider import CodexProvider
from .grok_provider import GrokProvider
+from .openai_provider import OpenAIProvider
-PROVIDERS = ("codex", "grok")
+PROVIDERS = ("codex", "grok", "openai")
# `--alpha-mode`: `auto` reads the provider's declared strategy (the SSoT);
# `native` / `chroma` force one. Forcing `native` on a chroma-only provider fails
# loud — a strategy the backend cannot execute is not a fallback candidate.
@@ -71,6 +80,8 @@ def _make_provider(name: str, *, keep_session: bool):
return CodexProvider(keep_session=keep_session)
if name == "grok":
return GrokProvider()
+ if name == "openai":
+ return OpenAIProvider()
raise SystemExit(f"gen: unknown provider {name!r}; expected one of {', '.join(PROVIDERS)}")
@@ -210,6 +221,7 @@ def generate_image(
refs: list[Path] | None = None,
model: str | None = None,
aspect_ratio: str | None = None,
+ quality: str | None = None,
transparent: bool = False,
alpha_mode: str = ALPHA_MODE_AUTO,
chroma_key: str = "magenta",
@@ -254,6 +266,7 @@ def generate_image(
refs=refs,
model=model,
aspect_ratio=aspect_ratio,
+ quality=quality,
native_alpha=strategy == TRANSPARENCY_NATIVE,
)
# 타임아웃 1회 관측 가능 재시도 — 산발 provider 스톨은 같은 호출 재시도로
@@ -341,6 +354,7 @@ def _run(args: argparse.Namespace) -> int:
refs=args.ref,
model=args.model,
aspect_ratio=args.aspect_ratio,
+ quality=args.quality,
transparent=args.transparent,
alpha_mode=args.alpha_mode,
chroma_key=args.chroma_key,
@@ -404,13 +418,24 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--out", required=True, type=Path)
parser.add_argument("--ref", action="append", type=Path, default=[], help="reference image (repeatable)")
parser.add_argument("--model")
- parser.add_argument("--aspect-ratio", help="grok only, e.g. 1:1 16:9 9:16")
+ parser.add_argument("--aspect-ratio", help="grok and openai, e.g. 1:1 16:9 9:16 (openai maps it to a gpt-image size; codex ignores it)")
+ parser.add_argument(
+ "--quality",
+ choices=QUALITIES,
+ default=None,
+ help=(
+ "rendering effort billed for this image; openai carries the whole range "
+ "(low..max, auto = the model decides). Omitted = the provider's own default. "
+ "A provider that cannot honour the level fails instead of downgrading it"
+ ),
+ )
parser.add_argument(
"--transparent",
action="store_true",
help=(
"publish a transparent RGBA PNG using the provider's transparency strategy: "
- "codex asks image_gen for real alpha (native), grok is keyed out of a chroma background"
+ "codex asks image_gen for real alpha and openai asks for background=transparent (native), "
+ "grok is keyed out of a chroma background"
),
)
parser.add_argument(
@@ -419,7 +444,7 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
default=ALPHA_MODE_AUTO,
help=(
"transparency strategy for --transparent: auto = the provider's declared strategy "
- "(native on codex, but chroma whenever --ref is attached — native alpha with refs is unstable); "
+ "(native on codex and openai, but chroma whenever --ref is attached — native alpha with refs is unstable); "
"chroma forces chroma keying (e.g. a codex prompt that already carries a key background); "
"native forces native alpha and is refused on a provider that cannot return alpha"
),
diff --git a/sprite_gen/gen/base.py b/sprite_gen/gen/base.py
index 2b9f4f5..150b430 100644
--- a/sprite_gen/gen/base.py
+++ b/sprite_gen/gen/base.py
@@ -10,12 +10,16 @@ path or a "done" string (No Silent Fallback).
from __future__ import annotations
+import io
import os
import shutil
+import tempfile
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Protocol
+from PIL import Image, UnidentifiedImageError
+
PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
# Transparency strategy — a capability each provider declares exactly once
@@ -29,6 +33,12 @@ TRANSPARENCY_NATIVE = "native"
TRANSPARENCY_CHROMA = "chroma"
TRANSPARENCY_STRATEGIES = (TRANSPARENCY_NATIVE, TRANSPARENCY_CHROMA)
+# Quality is a per-provider capability over one shared vocabulary. This tuple is
+# the `--quality` surface (the union); each provider declares the subset it can
+# honour and fails loud on a name outside it, so a paid-for level is never
+# quietly downgraded to whatever the backend felt like (No Silent Fallback).
+QUALITIES = ("auto", "low", "medium", "high", "xhigh", "max")
+
# Child provider processes are independent execution contexts. They must not
# inherit parent orchestration identity or lifecycle controls, while ordinary
# variables such as PATH remain available. Suffix matching keeps the contract
@@ -99,13 +109,47 @@ class GenRequest:
raw: Path # provider writes the generated PNG (chroma background included) here
refs: list[Path] = field(default_factory=list)
model: str | None = None
- aspect_ratio: str | None = None # grok honours this; codex ignores it
+ aspect_ratio: str | None = None # grok honours this; openai maps it to a size; codex ignores it
+ # Rendering effort/fidelity level, from QUALITIES. None = the provider's own
+ # default; a level the provider does not support is an error, not a downgrade.
+ quality: str | None = None
# Ask the model for a genuinely transparent background (alpha channel). Only
# legal for a provider whose `transparency` is `native`; the orchestrator gates
# it and the provider carries the request into its transport prompt.
native_alpha: bool = False
+def publish_png(data: bytes, path: Path, *, label: str) -> None:
+ """Publish decoded provider image bytes as a verified PNG at `path`.
+
+ One writer for every provider: decode first (a corrupt or non-image payload
+ fails before anything is published), re-encode only when the payload is not
+ already a PNG — grok Imagine answers with JPEG — then verify the bytes and
+ swap them in atomically. Nothing is resized. A failure leaves whatever was at
+ `path` untouched, so a stale raw is never reused as a result.
+ """
+ try:
+ with Image.open(io.BytesIO(data)) as source:
+ source.load()
+ if source.format == "PNG":
+ png = data
+ else:
+ buffer = io.BytesIO()
+ source.convert("RGBA" if "A" in source.getbands() else "RGB").save(buffer, format="PNG")
+ png = buffer.getvalue()
+ except (OSError, ValueError, UnidentifiedImageError) as exc:
+ raise SystemExit(f"{label}: response image is invalid; nothing published") from exc
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with tempfile.NamedTemporaryFile(dir=path.parent, suffix=".png", delete=False) as tmp:
+ temp = Path(tmp.name)
+ try:
+ temp.write_bytes(png)
+ verify_png(temp)
+ os.replace(temp, path)
+ finally:
+ temp.unlink(missing_ok=True)
+
+
@dataclass
class ProviderRun:
"""What a provider reports after writing `request.raw`."""
diff --git a/sprite_gen/gen/grok_provider.py b/sprite_gen/gen/grok_provider.py
index 4d54041..e42e961 100644
--- a/sprite_gen/gen/grok_provider.py
+++ b/sprite_gen/gen/grok_provider.py
@@ -5,15 +5,13 @@ from __future__ import annotations
import base64
import binascii
import io
-import os
-import tempfile
import time
from pathlib import Path
from PIL import Image, UnidentifiedImageError
from . import xai
-from .base import GEN_TIMEOUT_SECONDS, TRANSPARENCY_CHROMA, GenRequest, ProviderRun, verify_png
+from .base import GEN_TIMEOUT_SECONDS, TRANSPARENCY_CHROMA, GenRequest, ProviderRun, publish_png
DEFAULT_MODEL = "grok-imagine-image-2.0"
MAX_REFS = 5
@@ -41,6 +39,11 @@ def _request_body(request: GenRequest) -> tuple[str, dict]:
raise SystemExit(f"grok-gen: at most {MAX_REFS} reference images are supported")
if request.aspect_ratio is not None and request.aspect_ratio not in ASPECT_RATIOS:
raise SystemExit(f"grok-gen: unsupported aspect ratio {request.aspect_ratio!r}")
+ # --quality is a declared capability, not a hint: grok does not carry one yet,
+ # so an asked-for level fails here instead of being dropped from the body and
+ # billed as whatever Imagine picked (No Silent Fallback).
+ if request.quality is not None:
+ raise SystemExit("grok-gen: --quality is not carried into grok Imagine; drop it or use --provider openai")
body = {"model": request.model or DEFAULT_MODEL, "prompt": request.prompt,
"n": 1, "response_format": "b64_json"}
if request.aspect_ratio and len(request.refs) != 1:
@@ -56,28 +59,16 @@ def _request_body(request: GenRequest) -> tuple[str, dict]:
def _publish_image(item: dict, path: Path) -> None:
- # Inline bytes avoid signed download URLs and bearer forwarding.
+ # Inline bytes avoid signed download URLs and bearer forwarding. Imagine may
+ # answer with JPEG; `publish_png` re-encodes it without resizing.
encoded = item.get("b64_json")
if not isinstance(encoded, str) or not encoded:
raise SystemExit("grok-gen: response has no b64_json image; nothing published")
try:
data = base64.b64decode(encoded, validate=True)
- with Image.open(io.BytesIO(data)) as source:
- source.load()
- # Imagine may return JPEG. Encode a real PNG without resizing.
- png = io.BytesIO()
- source.convert("RGBA" if "A" in source.getbands() else "RGB").save(png, format="PNG")
- except (ValueError, binascii.Error, OSError, UnidentifiedImageError) as exc:
+ except (ValueError, binascii.Error) as exc:
raise SystemExit("grok-gen: response image is invalid; nothing published") from exc
- path.parent.mkdir(parents=True, exist_ok=True)
- with tempfile.NamedTemporaryFile(dir=path.parent, suffix=".png", delete=False) as tmp:
- temp = Path(tmp.name)
- try:
- temp.write_bytes(png.getvalue())
- verify_png(temp)
- os.replace(temp, path)
- finally:
- temp.unlink(missing_ok=True)
+ publish_png(data, path, label="grok-gen")
class GrokProvider:
diff --git a/sprite_gen/gen/openai_provider.py b/sprite_gen/gen/openai_provider.py
new file mode 100644
index 0000000..4c23231
--- /dev/null
+++ b/sprite_gen/gen/openai_provider.py
@@ -0,0 +1,274 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Direct OpenAI Images generation/editing with an API key and no ChatGPT login.
+
+The `codex` provider reaches the same family of models through the ChatGPT
+subscription (an interactive OAuth login and a `codex` CLI on PATH). Neither
+exists inside a headless container, so this adapter talks to the REST endpoints
+with `OPENAI_API_KEY` alone: `POST /v1/images/generations`, or
+`POST /v1/images/edits` (multipart) when reference images are attached.
+
+Field names and enums are the documented Images API surface (developers.openai.com,
+2026-09-20 확인): gpt-image models always answer with base64 (`response_format` is
+not accepted), `quality` is low|medium|high|xhigh|max|auto, `background` is
+transparent|opaque|auto and transparency needs `output_format` png or webp, and a
+custom `size` must have both sides divisible by 16, an aspect ratio within
+1:3..3:1, and a total pixel count between 655,360 and 8,294,400.
+
+This provider never falls back to codex, to another key, or to a retry: a missing
+credential, a rejected key or a failed request is the observable outcome.
+"""
+from __future__ import annotations
+
+import base64
+import binascii
+import io
+import json
+import os
+import time
+import urllib.error
+import urllib.request
+import uuid
+from pathlib import Path
+from typing import Any
+
+from PIL import Image, UnidentifiedImageError
+
+from .base import (
+ GEN_TIMEOUT_SECONDS,
+ QUALITIES,
+ TRANSPARENCY_NATIVE,
+ GenRequest,
+ ProviderRun,
+ publish_png,
+)
+
+API_BASE = "https://api.openai.com/v1"
+AUTH_ENV = "OPENAI_API_KEY"
+AUTH_SOURCE_API_KEY = AUTH_ENV
+
+DEFAULT_MODEL = "gpt-image-2.5-flare"
+# The documented default is `auto` (the model picks the effort). It is sent
+# explicitly so the billed level is always visible in the request and the report.
+DEFAULT_QUALITY = "auto"
+# gpt-image-2.5 accepts the whole shared vocabulary.
+SUPPORTED_QUALITIES = QUALITIES
+# "For GPT image models, you can provide up to 16 images." (images/edits `images`)
+MAX_REFS = 16
+PNG_OUTPUT_FORMAT = "png"
+BACKGROUND_TRANSPARENT = "transparent"
+BACKGROUND_OPAQUE = "opaque"
+
+# `--aspect-ratio` -> a concrete gpt-image `size`. Every entry satisfies the
+# documented constraints (both sides divisible by 16, ratio inside 1:3..3:1,
+# 655,360 <= pixels <= 8,294,400) and is checked by the test suite, so the ratio
+# a caller asks for is the ratio that is billed and returned. A ratio that has no
+# exact gpt-image size is refused rather than quietly rounded to a nearby one.
+SIZES = {
+ "auto": "auto",
+ "1:1": "1024x1024",
+ "3:2": "1536x1024",
+ "2:3": "1024x1536",
+ "4:3": "1024x768",
+ "3:4": "768x1024",
+ "16:9": "1536x864",
+ "9:16": "864x1536",
+ "2:1": "1440x720",
+ "1:2": "720x1440",
+ "3:1": "1536x512",
+ "1:3": "512x1536",
+}
+DEFAULT_SIZE = SIZES["1:1"]
+
+_REFERENCE_MIMES = {"image/png": "png", "image/jpeg": "jpg", "image/webp": "webp"}
+
+
+def resolve_credential(env: dict[str, str] | None = None) -> str:
+ """Return the OpenAI API key, or fail loud naming the variable that is missing."""
+ env = os.environ if env is None else env
+ key = (env.get(AUTH_ENV) or "").strip()
+ if key:
+ return key
+ if AUTH_ENV in env:
+ raise SystemExit(
+ f"openai-gen: {AUTH_ENV} is set but empty; give it a value. "
+ "This provider never falls back to the codex ChatGPT login."
+ )
+ raise SystemExit(
+ f"openai-gen: no OpenAI credential — {AUTH_ENV} is not set.\n"
+ f" export {AUTH_ENV}=<your OpenAI API key> (platform.openai.com/api-keys). "
+ "This provider never falls back to the codex ChatGPT login, which needs an "
+ "interactive browser sign-in that a container does not have."
+ )
+
+
+def _reference(path: Path, index: int) -> tuple[str, str, bytes]:
+ """Read one reference image as a (filename, mime, bytes) multipart part.
+
+ The part is named by position, not by the local file: a user's filename is
+ their data, and a name carrying a quote or a newline would forge the part
+ header it is written into.
+ """
+ try:
+ data = path.read_bytes()
+ with Image.open(io.BytesIO(data)) as source:
+ source.load()
+ mime = Image.MIME.get(source.format)
+ if mime not in _REFERENCE_MIMES:
+ raise ValueError("reference must be PNG, JPEG or WebP")
+ except (OSError, ValueError, UnidentifiedImageError) as exc:
+ raise SystemExit(f"openai-gen: invalid reference image {path}") from exc
+ return f"image-{index}.{_REFERENCE_MIMES[mime]}", mime, data
+
+
+def _fields(request: GenRequest) -> dict[str, str]:
+ """The request fields shared by generations and edits, validated offline.
+
+ Everything that can be refused without spending money is refused here, before
+ a credential is read or a socket is opened.
+ """
+ if not request.prompt.strip():
+ raise SystemExit("openai-gen: empty prompt")
+ if len(request.refs) > MAX_REFS:
+ raise SystemExit(f"openai-gen: at most {MAX_REFS} reference images are supported")
+ quality = request.quality or DEFAULT_QUALITY
+ if quality not in SUPPORTED_QUALITIES:
+ raise SystemExit(
+ f"openai-gen: unsupported quality {quality!r}; expected one of {', '.join(SUPPORTED_QUALITIES)}"
+ )
+ if request.aspect_ratio is None:
+ size = DEFAULT_SIZE
+ elif request.aspect_ratio in SIZES:
+ size = SIZES[request.aspect_ratio]
+ else:
+ raise SystemExit(
+ f"openai-gen: aspect ratio {request.aspect_ratio!r} has no gpt-image size; "
+ f"expected one of {', '.join(SIZES)}"
+ )
+ return {
+ "model": request.model or DEFAULT_MODEL,
+ "prompt": request.prompt,
+ "n": "1",
+ "size": size,
+ "quality": quality,
+ # png keeps the alpha channel that `background: transparent` produces.
+ "output_format": PNG_OUTPUT_FORMAT,
+ "background": BACKGROUND_TRANSPARENT if request.native_alpha else BACKGROUND_OPAQUE,
+ }
+
+
+def _json_request(fields: dict[str, str]) -> tuple[bytes, str]:
+ body = {**fields, "n": int(fields["n"])}
+ return json.dumps(body).encode("utf-8"), "application/json"
+
+
+def _multipart_request(fields: dict[str, str], refs: list[Path]) -> tuple[bytes, str]:
+ """Encode the edits request; `/v1/images/edits` takes multipart, not JSON.
+
+ Reference images go in as repeated `image[]` parts, in the order they were
+ given, because the model reads them positionally.
+ """
+ boundary = "----sprite-gen-" + uuid.uuid4().hex
+ marker = f"--{boundary}\r\n".encode("utf-8")
+ chunks: list[bytes] = []
+ for name, value in fields.items():
+ chunks.append(marker)
+ chunks.append(f'Content-Disposition: form-data; name="{name}"\r\n\r\n'.encode("utf-8"))
+ chunks.append(value.encode("utf-8") + b"\r\n")
+ for index, ref in enumerate(refs):
+ filename, mime, data = _reference(ref, index)
+ chunks.append(marker)
+ chunks.append(
+ f'Content-Disposition: form-data; name="image[]"; filename="{filename}"\r\n'
+ f"Content-Type: {mime}\r\n\r\n".encode("utf-8")
+ )
+ chunks.append(data + b"\r\n")
+ chunks.append(f"--{boundary}--\r\n".encode("utf-8"))
+ return b"".join(chunks), f"multipart/form-data; boundary={boundary}"
+
+
+def http_image(url: str, token: str, data: bytes, content_type: str, *, timeout: float) -> tuple[int, Any]:
+ """POST an images request and return (status, parsed JSON).
+
+ A transport error is terminal: the server may already have accepted and billed
+ the request, so it is never retried here.
+ """
+ request = urllib.request.Request(url, data=data, method="POST")
+ request.add_header("Authorization", f"Bearer {token}")
+ request.add_header("Accept", "application/json")
+ request.add_header("Content-Type", content_type)
+ try:
+ with urllib.request.urlopen(request, timeout=timeout) as response:
+ raw = response.read().decode("utf-8")
+ return response.status, (json.loads(raw) if raw else {})
+ except (json.JSONDecodeError, UnicodeDecodeError) as exc:
+ raise SystemExit("openai-gen: response was not valid JSON") from exc
+ except urllib.error.HTTPError as exc:
+ raw = exc.read().decode("utf-8", "replace")
+ try:
+ return exc.code, json.loads(raw)
+ except json.JSONDecodeError:
+ return exc.code, {"raw": raw[:400]}
+ except (urllib.error.URLError, TimeoutError, OSError) as exc:
+ raise SystemExit(
+ "openai-gen: request failed or timed out; no automatic retry (the server may have accepted it)"
+ ) from exc
+
+
+def _publish_image(item: dict, path: Path) -> None:
+ # gpt-image models always answer with inline base64 — no signed URL to follow
+ # and no bearer token to forward.
+ encoded = item.get("b64_json")
+ if not isinstance(encoded, str) or not encoded:
+ raise SystemExit("openai-gen: response has no b64_json image; nothing published")
+ try:
+ data = base64.b64decode(encoded, validate=True)
+ except (ValueError, binascii.Error) as exc:
+ raise SystemExit("openai-gen: response image is invalid; nothing published") from exc
+ publish_png(data, path, label="openai-gen")
+
+
+class OpenAIProvider:
+ name = "openai"
+ # `background: transparent` returns a real alpha channel on gpt-image-2.5.
+ transparency = TRANSPARENCY_NATIVE
+
+ def generate(self, request: GenRequest, workdir: Path) -> ProviderRun:
+ fields = _fields(request)
+ refs = [Path(ref) for ref in request.refs]
+ if refs:
+ endpoint = "/images/edits"
+ data, content_type = _multipart_request(fields, refs)
+ else:
+ endpoint = "/images/generations"
+ data, content_type = _json_request(fields)
+ token = resolve_credential()
+ started = time.monotonic()
+ status, reply = http_image(API_BASE + endpoint, token, data, content_type, timeout=GEN_TIMEOUT_SECONDS)
+ if status in (401, 403):
+ raise SystemExit(
+ f"openai-gen: credential {AUTH_SOURCE_API_KEY} rejected (HTTP {status}); "
+ f"check the key's value and that its project may call {fields['model']}"
+ )
+ # Error bodies can echo the prompt, a key or a signed URL; do not print them.
+ if status != 200:
+ raise SystemExit(f"openai-gen: image request failed (HTTP {status}); no retry or provider fallback")
+ items = reply.get("data") if isinstance(reply, dict) else None
+ if not isinstance(items, list) or len(items) != 1 or not isinstance(items[0], dict):
+ raise SystemExit("openai-gen: expected exactly one image in the response; nothing published")
+ _publish_image(items[0], request.raw)
+ usage = reply.get("usage") if isinstance(reply, dict) else None
+ return ProviderRun(
+ provider=self.name,
+ elapsed_seconds=time.monotonic() - started,
+ model=fields["model"],
+ extra={
+ "auth_source": AUTH_SOURCE_API_KEY,
+ "transport": "openai-api",
+ "endpoint": endpoint,
+ "quality": fields["quality"],
+ "size": fields["size"],
+ "background": fields["background"],
+ # Token counts only — what the call cost, never what it contained.
+ **({"usage": usage} if isinstance(usage, dict) else {}),
+ },
+ )
diff --git a/sprite_gen/workflow/access.py b/sprite_gen/workflow/access.py
index 84e5700..adec1e6 100644
--- a/sprite_gen/workflow/access.py
+++ b/sprite_gen/workflow/access.py
@@ -6,6 +6,8 @@ import shutil
import subprocess
from sprite_gen.gen.base import provider_binary, provider_subprocess_env
+from sprite_gen.gen.openai_provider import AUTH_ENV as OPENAI_AUTH_ENV
+from sprite_gen.gen.openai_provider import resolve_credential as resolve_openai_credential
from sprite_gen.gen.xai import AUTH_SOURCE_API_KEY, resolve_credential
@@ -27,6 +29,17 @@ def probe_access(provider: str, *, video: bool = False) -> dict:
if "chatgpt" not in output:
return {**result, "reason": "login succeeded but ChatGPT subscription authentication was not identified"}
return {**result, "login": "ready"}
+ if provider == "openai":
+ # An API key is the whole credential: there is no login to inspect and no
+ # subscription route to prefer, so readiness is the key's presence and the
+ # billing route is always metered API credit.
+ try:
+ resolve_openai_credential()
+ except (SystemExit, OSError, ValueError):
+ return {**result, "login": "unavailable",
+ "reason": f"{OPENAI_AUTH_ENV} is not set; export the key or choose another provider"}
+ return {**result, "login": "ready", "billing": "api-credit",
+ "reason": f"OpenAI images will use {OPENAI_AUTH_ENV} and separate API credit; confirm this billing choice."}
if provider != "grok":
raise ValueError(f"unknown provider: {provider}")
try:
diff --git a/sprite_gen/workflow/catalog.py b/sprite_gen/workflow/catalog.py
index c54ea11..64425bd 100644
--- a/sprite_gen/workflow/catalog.py
+++ b/sprite_gen/workflow/catalog.py
@@ -8,9 +8,21 @@ MOTION_METHODS = {
"grok-video": {"label": "그록 영상", "provider": "grok", "doc": "docs/video-pipeline.md",
"steps": ["video-set"]},
}
+# One label per registered provider. A provider with no label here is a bug, not
+# a row to drop quietly: the mapping is checked rather than zipped positionally,
+# so registering a backend in `gen.PROVIDERS` without naming it fails at import.
+PROVIDER_LABELS = {
+ "codex": "지피티 (ChatGPT 로그인)",
+ "grok": "그록",
+ "openai": "지피티 (API 키)",
+}
+_unlabelled = [provider for provider in PROVIDERS if provider not in PROVIDER_LABELS]
+if _unlabelled:
+ raise RuntimeError(f"workflow catalog: no label for provider(s) {', '.join(_unlabelled)}")
+
FIELDS = {
- "image_provider": {"options": dict(zip(PROVIDERS, ("지피티", "그록"))),
- "question": "이미지를 지피티로 만들까요, 그록으로 만들까요?"},
+ "image_provider": {"options": {provider: PROVIDER_LABELS[provider] for provider in PROVIDERS},
+ "question": "이미지를 무엇으로 만들까요?"},
"motion_method": {"options": {k: v["label"] for k, v in MOTION_METHODS.items()},
"question": "동작을 그록 영상으로 만들까요, 지피티 이미지 스프라이트로 만들까요?"},
"curation": {"options": {"open": "열기", "skip": "열지 않기"},
diff --git a/sprite_gen/workflow/guide.py b/sprite_gen/workflow/guide.py
index 205a2da..d04dbb6 100644
--- a/sprite_gen/workflow/guide.py
+++ b/sprite_gen/workflow/guide.py
@@ -50,7 +50,12 @@ def guide(kind: str, *, stage: str = "start", base_image: Path | None = None, re
blocked.append({"provider": provider, "reason": state["reason"]})
elif state["billing"] == "api-credit":
if not confirm_api_billing:
- questions.append({"field": "confirm_api_billing", "question": "그록 영상에 별도 API 크레딧을 사용할까요?", "options": {"yes": "사용", "no": "구독 로그인으로 변경"}})
+ # Metered API credit is a billing decision, so the question
+ # names the provider that would be charged rather than assuming
+ # one (grok video and the openai key both land here).
+ questions.append({"field": "confirm_api_billing",
+ "question": f"{FIELDS['image_provider']['options'][provider]}에 별도 API 크레딧을 사용할까요?",
+ "options": {"yes": "사용", "no": "다른 경로로 변경"}})
elif provider not in confirmed_access and not any(q["field"] == f"access_{provider}" for q in questions):
questions.append({"field": f"access_{provider}", "question": f"{FIELDS['image_provider']['options'][provider]} 계정의 구독과 이미지/영상 이용 가능 여부를 확인해 주세요.",
"options": {"yes": "사용 가능", "no": "사용 불가"}})
diff --git a/tests/gen/test_openai_provider.py b/tests/gen/test_openai_provider.py
new file mode 100644
index 0000000..0f157e0
--- /dev/null
+++ b/tests/gen/test_openai_provider.py
@@ -0,0 +1,250 @@
+# SPDX-License-Identifier: Apache-2.0
+"""OpenAI Images API contract, offline: no key, no network, no codex subprocess.
+
+The paid seam is the request body, so that is what is pinned here: which endpoint
+is called, every field that decides what is billed (model / quality / size /
+background / output_format), how the base64 answer becomes a verified PNG, and
+which failures must never publish, retry or leak the key.
+"""
+import base64
+import io
+import json
+import subprocess
+import urllib.error
+
+import pytest
+from PIL import Image
+
+from sprite_gen import gen
+from sprite_gen.gen import openai_provider as openai
+from sprite_gen.gen.base import GenRequest
+from sprite_gen.workflow import access
+from sprite_gen.workflow.catalog import FIELDS, PROVIDER_LABELS
+
+KEY = "synthetic-secret"
+
+
+def encoded_image(fmt="PNG", *, alpha=False, key=False):
+ """A 12x8 fixture: a 4x4 subject block on a plain, transparent or magenta field."""
+ if alpha:
+ image, subject = Image.new("RGBA", (12, 8), (0, 0, 0, 0)), (20, 90, 200, 255)
+ else:
+ image, subject = Image.new("RGB", (12, 8), (255, 0, 255) if key else (20, 90, 200)), (20, 90, 200)
+ for x in range(4, 8):
+ for y in range(2, 6):
+ image.putpixel((x, y), subject)
+ buf = io.BytesIO()
+ image.save(buf, format=fmt)
+ return base64.b64encode(buf.getvalue()).decode()
+
+
+def api(monkeypatch):
+ monkeypatch.setenv("OPENAI_API_KEY", KEY)
+ monkeypatch.setattr(subprocess, "run", lambda *a, **k: pytest.fail("no provider subprocess may be spawned"))
+ state = {"status": 200, "body": {"data": [{"b64_json": encoded_image()}],
+ "usage": {"input_tokens": 12, "output_tokens": 340}}, "calls": []}
+
+ class Response:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ pass
+
+ @property
+ def status(self):
+ return state["status"]
+
+ def read(self):
+ return json.dumps(state["body"]).encode()
+
+ def open_request(request, *, timeout):
+ state["calls"].append((request, timeout))
+ if state["status"] == 200:
+ return Response()
+ raise urllib.error.HTTPError(request.full_url, state["status"], "error", {},
+ io.BytesIO(json.dumps(state["body"]).encode()))
+
+ monkeypatch.setattr(openai.urllib.request, "urlopen", open_request)
+ return state
+
+
+def _body(request):
+ return json.loads(request.data)
+
+
+def test_generation_sends_the_billed_fields_and_publishes_a_png(tmp_path, api):
+ result = gen.generate_image("openai", "a blue square", tmp_path / "out.png")
+ request, timeout = api["calls"][0]
+ assert request.full_url == "https://api.openai.com/v1/images/generations"
+ assert request.get_header("Authorization") == f"Bearer {KEY}"
+ assert request.get_header("Content-type") == "application/json"
+ assert _body(request) == {"model": openai.DEFAULT_MODEL, "prompt": "a blue square", "n": 1,
+ "size": "1024x1024", "quality": "auto",
+ "output_format": "png", "background": "opaque"}
+ assert timeout == openai.GEN_TIMEOUT_SECONDS
+ # `response_format` is rejected for gpt-image models; the answer is always b64.
+ assert "response_format" not in _body(request)
+ with Image.open(result.out) as image:
+ assert image.format == "PNG" and image.size == (12, 8)
+ report = result.to_dict()
+ assert report["provider"] == "openai" and report["model"] == openai.DEFAULT_MODEL
+ assert report["extra"]["transport"] == "openai-api"
+ assert report["extra"]["auth_source"] == "OPENAI_API_KEY"
+ assert report["extra"]["usage"] == {"input_tokens": 12, "output_tokens": 340}
+ assert KEY not in json.dumps(report)
+
+
[email protected]("quality", openai.SUPPORTED_QUALITIES)
+def test_every_quality_level_reaches_the_request_verbatim(tmp_path, api, quality):
+ gen.generate_image("openai", "x", tmp_path / f"{quality}.png", quality=quality)
+ assert _body(api["calls"][0][0])["quality"] == quality
+
+
[email protected]("ratio,size", sorted(openai.SIZES.items()))
+def test_aspect_ratio_maps_to_a_legal_gpt_image_size(tmp_path, api, ratio, size):
+ gen.generate_image("openai", "x", tmp_path / "out.png", aspect_ratio=ratio)
+ assert _body(api["calls"][0][0])["size"] == size
+ if size == "auto":
+ return
+ width, height = (int(side) for side in size.split("x"))
+ # The documented custom-size constraints, checked on the table itself.
+ assert width % 16 == 0 and height % 16 == 0
+ assert max(width, height) <= 3840
+ assert 1 / 3 <= width / height <= 3
+ assert 655_360 <= width * height <= 8_294_400
+
+
+def test_model_and_quality_overrides_are_not_second_guessed(tmp_path, api):
+ gen.generate_image("openai", "x", tmp_path / "out.png", model="gpt-image-2.5-sunburst", quality="max")
+ body = _body(api["calls"][0][0])
+ assert body["model"] == "gpt-image-2.5-sunburst" and body["quality"] == "max"
+
+
+def test_transparent_asks_for_a_transparent_background_and_keeps_the_alpha(tmp_path, api):
+ api["body"] = {"data": [{"b64_json": encoded_image(alpha=True)}]}
+ result = gen.generate_image("openai", "a blue square", tmp_path / "alpha.png", transparent=True)
+ body = _body(api["calls"][0][0])
+ assert body["background"] == "transparent" and body["output_format"] == "png"
+ assert result.alpha["strategy"] == "native" and result.alpha["alpha_zero_pct"] > 0
+ with Image.open(result.out) as image:
+ assert image.getpixel((0, 0)) == (0, 0, 0, 0)
+ assert image.getpixel((6, 4))[3] == 255
+
+
+def test_reference_edit_posts_multipart_images_in_order(tmp_path, api):
+ refs = []
+ for index in range(3):
+ path = tmp_path / f"ref-{index}.png"
+ Image.new("RGB", (12, 8), (index * 40, 0, 0)).save(path)
+ refs.append(path)
+ gen.generate_image("openai", "combine these", tmp_path / "edit.png", refs=refs, quality="high")
+ request, _ = api["calls"][0]
+ assert request.full_url == "https://api.openai.com/v1/images/edits"
+ content_type = request.get_header("Content-type")
+ assert content_type.startswith("multipart/form-data; boundary=")
+ payload = request.data
+ assert payload.count(b'name="image[]"') == len(refs)
+ assert b'name="quality"\r\n\r\nhigh\r\n' in payload
+ assert b'name="model"\r\n\r\n' + openai.DEFAULT_MODEL.encode() in payload
+ positions = [payload.index(ref.read_bytes()) for ref in refs]
+ assert positions == sorted(positions), "reference images are read positionally; order must survive"
+
+
[email protected]("status", [400, 401, 403, 429, 500])
+def test_api_failure_keeps_existing_output_and_does_not_retry(tmp_path, api, status):
+ api.update(status=status, body={"error": {"message": f"{KEY} https://signed.invalid/private"}})
+ out = tmp_path / "existing.png"
+ out.write_bytes(b"existing")
+ with pytest.raises(SystemExit, match=f"HTTP {status}") as error:
+ gen.generate_image("openai", "x", out)
+ assert KEY not in str(error.value)
+ assert "signed.invalid" not in str(error.value)
+ assert out.read_bytes() == b"existing"
+ assert len(api["calls"]) == 1
+
+
[email protected]("body", [{}, {"data": []}, {"data": [None]}, {"data": [{}, {}]},
+ {"data": [{"b64_json": "???"}]},
+ {"data": [{"b64_json": base64.b64encode(b"invalid image").decode()}]},
+ {"data": [{"url": "https://signed.invalid/private"}]}])
+def test_invalid_response_never_reuses_stale_raw(tmp_path, api, body):
+ api["body"] = body
+ raw = tmp_path / "raw.png"
+ raw.write_bytes(b"previous raw")
+ with pytest.raises(SystemExit):
+ openai.OpenAIProvider().generate(GenRequest("x", raw), tmp_path)
+ assert raw.read_bytes() == b"previous raw"
+ assert len(api["calls"]) == 1
+ assert list(tmp_path.iterdir()) == [raw]
+
+
[email protected]("value", [None, ""])
+def test_missing_key_names_the_variable_and_never_falls_back(tmp_path, api, monkeypatch, value):
+ if value is None:
+ monkeypatch.delenv("OPENAI_API_KEY")
+ else:
+ monkeypatch.setenv("OPENAI_API_KEY", value)
+ with pytest.raises(SystemExit, match="OPENAI_API_KEY") as error:
+ gen.generate_image("openai", "x", tmp_path / "out.png")
+ assert "codex" in str(error.value) # names the login it will NOT silently use
+ assert api["calls"] == []
+ assert not (tmp_path / "out.png").exists()
+
+
+def test_invalid_request_fails_before_any_billable_call(tmp_path, api):
+ bad_ref = tmp_path / "ref.png"
+ bad_ref.write_bytes(b"invalid")
+ good_ref = tmp_path / "good.png"
+ Image.new("RGB", (4, 4), (1, 2, 3)).save(good_ref)
+ for options in ({"prompt": " "}, {"refs": [bad_ref]}, {"refs": [good_ref] * (openai.MAX_REFS + 1)},
+ {"aspect_ratio": "19.5:9"}, {"quality": "ultra"}):
+ prompt = options.pop("prompt", "x")
+ with pytest.raises(SystemExit):
+ openai.OpenAIProvider().generate(GenRequest(prompt, tmp_path / "raw.png", **options), tmp_path)
+ assert api["calls"] == []
+
+
+def test_timeout_does_not_repeat_billable_request(tmp_path, api, monkeypatch):
+ calls = []
+
+ def timeout(*args, **kwargs):
+ calls.append(args)
+ raise TimeoutError()
+
+ monkeypatch.setattr(openai.urllib.request, "urlopen", timeout)
+ with pytest.raises(SystemExit, match="no automatic retry"):
+ gen.generate_image("openai", "x", tmp_path / "out.png")
+ assert len(calls) == 1
+
+
+def test_native_alpha_is_a_declared_capability(tmp_path, api):
+ assert openai.OpenAIProvider().transparency == "native"
+ # Forcing chroma stays legal (a prompt may already carry a key background).
+ api["body"] = {"data": [{"b64_json": encoded_image(key=True)}]}
+ result = gen.generate_image("openai", "blue on magenta", tmp_path / "keyed.png",
+ transparent=True, alpha_mode="chroma")
+ assert result.alpha["strategy"] == "chroma"
+ assert _body(api["calls"][0][0])["background"] == "opaque"
+
+
+def test_provider_is_registered_everywhere_a_provider_must_be(api):
+ assert "openai" in gen.PROVIDERS
+ assert isinstance(gen._make_provider("openai", keep_session=False), openai.OpenAIProvider)
+ # The workflow surface must name every registered backend, not the first two.
+ assert set(FIELDS["image_provider"]["options"]) == set(gen.PROVIDERS) == set(PROVIDER_LABELS)
+ assert access.probe_access("openai") == {"provider": "openai", "login": "ready", "subscription": "unknown",
+ "quota": "unknown", "billing": "api-credit",
+ "reason": "OpenAI images will use OPENAI_API_KEY and separate "
+ "API credit; confirm this billing choice."}
+
+
+def test_cli_accepts_provider_and_quality(tmp_path, api):
+ report = tmp_path / "report.json"
+ assert gen.main(["--provider", "openai", "--prompt", "x", "--out", str(tmp_path / "cli.png"),
+ "--quality", "low", "--aspect-ratio", "16:9", "--report", str(report)]) == 0
+ body = _body(api["calls"][0][0])
+ assert body["quality"] == "low" and body["size"] == "1536x864"
+ payload = json.loads(report.read_text(encoding="utf-8"))
+ assert payload["provider"] == "openai" and payload["provider_resolved_from"] == "explicit"