Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
gen: carry grok Imagine's quality and resolution, refuse them where they do nothing
Soohong Kimcd1313124355
diff --git a/sprite_gen/gen/__init__.py b/sprite_gen/gen/__init__.pyindex 233a511..0278a52 100644--- a/sprite_gen/gen/__init__.py+++ b/sprite_gen/gen/__init__.py@@ -28,6 +28,7 @@ CLI:[--ref REF.png ...] [--transparent [--alpha-mode auto|native|chroma][--chroma-key magenta|green]] [--white-check CHECK.png] [--model ID][--aspect-ratio 1:1] [--quality low|medium|high|xhigh|max|auto]+ [--resolution 1k|1.5k|2k][--report REPORT.json] [--keep-session]"""@@ -48,6 +49,7 @@ from sprite_gen.spec.runio import atomic_write_textfrom . import chroma as chroma_modfrom .base import (QUALITIES,+ RESOLUTIONS,TRANSPARENCY_CHROMA,TRANSPARENCY_NATIVE,TRANSPARENCY_STRATEGIES,@@ -244,6 +246,7 @@ def generate_image(model: str | None = None,aspect_ratio: str | None = None,quality: str | None = None,+ resolution: str | None = None,transparent: bool = False,alpha_mode: str = ALPHA_MODE_AUTO,chroma_key: str = "magenta",@@ -289,6 +292,7 @@ def generate_image(model=model,aspect_ratio=aspect_ratio,quality=quality,+ resolution=resolution,native_alpha=strategy == TRANSPARENCY_NATIVE,)# 타임아웃 1회 관측 가능 재시도 — 산발 provider 스톨은 같은 호출 재시도로@@ -377,6 +381,7 @@ def _run(args: argparse.Namespace) -> int:model=args.model,aspect_ratio=args.aspect_ratio,quality=args.quality,+ resolution=args.resolution,transparent=args.transparent,alpha_mode=args.alpha_mode,chroma_key=args.chroma_key,@@ -449,8 +454,20 @@ def add_arguments(parser: argparse.ArgumentParser) -> None: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"+ "(low..max, auto = the model decides) and grok takes low / medium / auto. "+ "Omitted = the provider's own default. A provider that cannot honour the "+ "level fails instead of downgrading it"+ ),+ )+ parser.add_argument(+ "--resolution",+ choices=RESOLUTIONS,+ default=None,+ help=(+ "output resolution, as the long edge of the image: grok Imagine's "+ "1k / 1.5k / 2k, priced together with --quality. Omitted = the provider's "+ "own default (grok: 1k). openai sizes from --aspect-ratio and codex from "+ "neither, so both refuse this flag instead of ignoring it"),)parser.add_argument(diff --git a/sprite_gen/gen/base.py b/sprite_gen/gen/base.pyindex 9966777..6f41043 100644--- a/sprite_gen/gen/base.py+++ b/sprite_gen/gen/base.py@@ -40,6 +40,15 @@ TRANSPARENCY_STRATEGIES = (TRANSPARENCY_NATIVE, TRANSPARENCY_CHROMA)# quietly downgraded to whatever the backend felt like (No Silent Fallback).QUALITIES = ("auto", "low", "medium", "high", "xhigh", "max")+# Output resolution — the second billed knob, over one shared vocabulary naming+# the long edge of the published image (`1k` = 1024px). grok Imagine sizes its+# output this way and prices it together with `quality`; a provider that sizes+# differently (openai derives a gpt-image `size` from `--aspect-ratio`) refuses+# the flag rather than accepting money for a resolution it will not deliver.+# Distinct from the video RESOLUTIONS (`480p`/`720p`/`1080p`), which names a+# frame height.+RESOLUTIONS = ("1k", "1.5k", "2k")+# 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@@ -129,6 +138,10 @@ class GenRequest:# 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+ # Output resolution, from RESOLUTIONS. None = the provider's own default+ # (grok: `1k`); a provider that cannot size its output this way is an error,+ # not a downgrade.+ resolution: 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.diff --git a/sprite_gen/gen/codex_provider.py b/sprite_gen/gen/codex_provider.pyindex 991fb75..a2ead18 100644--- a/sprite_gen/gen/codex_provider.py+++ b/sprite_gen/gen/codex_provider.py@@ -296,6 +296,15 @@ class CodexProvider:self.keep_session = keep_sessiondef generate(self, request: GenRequest, workdir: Path) -> ProviderRun:+ # `image_gen` exposes no effort or size dial, so neither knob is carried+ # into the prompt. Refusing beats returning a default-effort image under a+ # level the caller chose and believes they got (No Silent Fallback).+ for flag, value in (("--quality", request.quality), ("--resolution", request.resolution)):+ if value is not None:+ raise SystemExit(+ f"codex-gen: {flag} is not carried into codex image_gen; "+ "drop it or use --provider openai"+ )codex_home = _resolve_codex_home()if not codex_home.is_dir():raise SystemExit(diff --git a/sprite_gen/gen/grok_provider.py b/sprite_gen/gen/grok_provider.pyindex bba8f0f..b2292c3 100644--- a/sprite_gen/gen/grok_provider.py+++ b/sprite_gen/gen/grok_provider.py@@ -1,5 +1,11 @@# SPDX-License-Identifier: Apache-2.0-"""Direct Grok Imagine image generation/editing, with no Grok Build process."""+"""Direct Grok Imagine image generation/editing, with no Grok Build process.++`quality` and `resolution` are the two knobs Imagine prices an image on+(docs.x.ai, 2026-09-20 확인): quality for grok-imagine-image-2.0 only, resolution+naming the long edge. Both are sent only when the caller asks for one, so a+request that names neither stays exactly what it was.+"""from __future__ import annotationsimport base64@@ -13,6 +19,7 @@ from PIL import Image, UnidentifiedImageErrorfrom . import xaifrom .base import (GEN_TIMEOUT_SECONDS,+ RESOLUTIONS,TRANSPARENCY_CHROMA,GenRequest,ProviderRun,@@ -22,6 +29,23 @@ from .base import (DEFAULT_MODEL = "grok-imagine-image-2.0"MAX_REFS = 5+# The subset of the shared `--quality` vocabulary Imagine can honour. Anything+# finer belongs to another backend, so it is refused here rather than billed as+# whatever the service picked. Omitted = `auto`, which the service resolves to+# low for generations and medium for edits.+#+# Both sets were read off the server, not the prose (2026-09-20 probes on the+# subscription route). Deserialization alone is not the answer: `quality` accepts+# `high` into the shared enum and then refuses it per model —+# HTTP 400 "This model only supports the following quality value(s): low,+# medium, auto."+# — so `high` is refused here instead of costing a round-trip. `resolution` 1.5k+# is served (HTTP 200) although the capability guide's prose lists only 1k and 2k;+# the REST schema enum has all three. An unknown field is not refused at all (a+# probe carrying one rendered normally), which is exactly why these names are+# checked here rather than left to the service to notice.+SUPPORTED_QUALITIES = ("auto", "low", "medium")+SUPPORTED_RESOLUTIONS = RESOLUTIONSASPECT_RATIOS = ("auto", "1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3","2:1", "1:2", "19.5:9", "9:19.5", "20:9", "9:20", "21:9", "5:2")@@ -46,15 +70,29 @@ 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")+ # Both knobs are declared capabilities, not hints: a level outside what+ # Imagine serves fails here instead of being dropped from the body and billed+ # as whatever the service picked (No Silent Fallback).+ if request.quality is not None and request.quality not in SUPPORTED_QUALITIES:+ raise SystemExit(+ f"grok-gen: unsupported quality {request.quality!r}; grok Imagine takes "+ f"{', '.join(SUPPORTED_QUALITIES)} — a finer level belongs to --provider openai"+ )+ if request.resolution is not None and request.resolution not in SUPPORTED_RESOLUTIONS:+ raise SystemExit(+ f"grok-gen: unsupported resolution {request.resolution!r}; "+ f"expected one of {', '.join(SUPPORTED_RESOLUTIONS)}"+ )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:body["aspect_ratio"] = request.aspect_ratio+ # Sent only when asked for. An omitted knob keeps the service default and the+ # request identical to what the same call was already billed for.+ if request.quality is not None:+ body["quality"] = request.quality+ if request.resolution is not None:+ body["resolution"] = request.resolutionif request.refs:images = [_reference(Path(ref)) for ref in request.refs]if len(images) == 1:@@ -89,9 +127,14 @@ class GrokProvider:# The login is preferred (xai.resolve_credential); reaching the key means no# login exists, and that spends API credit instead of the Grok subscription.credential = xai.resolve_credential()+ # What this image is priced on, named in the same breath as the charge:+ # Imagine bills quality x resolution, so 2k medium costs twice 1k low.+ priced = ", ".join(f"{knob}={value}" for knob, value in+ (("quality", request.quality), ("resolution", request.resolution)) if value)if credential.source == xai.AUTH_SOURCE_API_KEY:announce_api_billing(self.name, xai.AUTH_ENV,- f", not your Grok subscription — `{xai.GROK_LOGIN_COMMAND}` signs that in.")+ f"{f' ({priced})' if priced else ''}, not your Grok subscription — "+ f"`{xai.GROK_LOGIN_COMMAND}` signs that in.")started = time.monotonic()status, reply = xai.http_json("POST", xai.API_BASE + endpoint, credential.token,body, timeout=GEN_TIMEOUT_SECONDS)@@ -100,8 +143,11 @@ class GrokProvider:else f"check {xai.AUTH_ENV}")raise SystemExit(f"grok-gen: credential {credential.source} rejected (HTTP {status}); {remedy}")# Error bodies can include prompts, credentials or URLs; do not echo them.+ # The one thing worth naming is the combination the docs scope to+ # grok-imagine-image-2.0, which another model is entitled to reject.if status != 200:- raise SystemExit(f"grok-gen: image request failed (HTTP {status}); no retry or provider fallback")+ scoped = f" (sent with {priced}, documented for {DEFAULT_MODEL})" if priced and body["model"] != DEFAULT_MODEL else ""+ raise SystemExit(f"grok-gen: image request failed (HTTP {status}); no retry or provider fallback{scoped}")items = reply.get("data") if isinstance(reply, dict) else Noneif not isinstance(items, list) or len(items) != 1 or not isinstance(items[0], dict):raise SystemExit("grok-gen: expected exactly one image in the response; nothing published")@@ -109,4 +155,7 @@ class GrokProvider:return ProviderRun(provider=self.name, elapsed_seconds=time.monotonic() - started,model=body["model"], extra={"auth_source": credential.source,"transport": "xai-api", "endpoint": endpoint,- "aspect_ratio_source": "reference" if len(request.refs) == 1 else "request-or-auto"})+ "aspect_ratio_source": "reference" if len(request.refs) == 1 else "request-or-auto",+ # Absent = the service default, which the report must not+ # invent a name for (`auto` differs per endpoint).+ **{knob: body[knob] for knob in ("quality", "resolution") if knob in body}})diff --git a/sprite_gen/gen/openai_provider.py b/sprite_gen/gen/openai_provider.pyindex 3426dd1..a35fbdd 100644--- a/sprite_gen/gen/openai_provider.py+++ b/sprite_gen/gen/openai_provider.py@@ -137,6 +137,14 @@ def _fields(request: GenRequest) -> dict[str, str]: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")+ # `size` here comes from --aspect-ratio (SIZES); gpt-image has no long-edge+ # preset, so an asked-for resolution is refused instead of being dropped from+ # a body the caller is about to pay for (No Silent Fallback).+ if request.resolution is not None:+ raise SystemExit(+ f"openai-gen: resolution {request.resolution!r} is grok Imagine's vocabulary; "+ "a gpt-image size comes from --aspect-ratio"+ )quality = request.quality or DEFAULT_QUALITYif quality not in SUPPORTED_QUALITIES:raise SystemExit(diff --git a/tests/gen/test_gen.py b/tests/gen/test_gen.pyindex e444659..666435d 100644--- a/tests/gen/test_gen.py+++ b/tests/gen/test_gen.py@@ -668,6 +668,21 @@ def test_real_providers_declare_their_transparency_strategy() -> None:assert grok_provider.GrokProvider.transparency == gen_base.TRANSPARENCY_CHROMA[email protected]("options, flag", [({"quality": "max"}, "--quality"),+ ({"quality": "auto"}, "--quality"),+ ({"resolution": "2k"}, "--resolution")])+def test_codex_refuses_a_level_image_gen_cannot_carry(tmp_path: Path, monkeypatch, options, flag) -> None:+ """image_gen has no effort or size dial, so the level is refused, never dropped:+ a caller who paid attention to --quality must not get a default-effort image."""+ import subprocess++ monkeypatch.setattr(subprocess, "run", lambda *a, **k: pytest.fail("codex must not be spawned"))+ with pytest.raises(SystemExit, match=flag) as error:+ codex_provider.CodexProvider().generate(GenRequest("x", tmp_path / "raw.png", **options), tmp_path)+ assert "openai" in str(error.value)+ assert not (tmp_path / "raw.png").exists()++def test_grok_refuses_a_native_alpha_request_before_upload(tmp_path: Path, monkeypatch) -> None:from sprite_gen.gen import grok_providerdiff --git a/tests/gen/test_grok_provider.py b/tests/gen/test_grok_provider.pyindex 93c6860..6e63d78 100644--- a/tests/gen/test_grok_provider.py+++ b/tests/gen/test_grok_provider.py@@ -10,6 +10,7 @@ import pytestfrom PIL import Imagefrom sprite_gen import gen+from sprite_gen.gen import base as gen_basefrom sprite_gen.gen import grok_provider as grok, xaifrom sprite_gen.gen.base import GenRequestfrom sprite_gen.workflow import access, guide@@ -208,3 +209,100 @@ def test_guide_prefers_subscription_without_api_billing_question(tmp_path, api,assert all(item["billing"] == "subscription" for item in result["access"])assert not any(question["field"] == "confirm_api_billing" for question in result["questions"])assert api["calls"] == []+++def _sent(api, index=0):+ return json.loads(api["calls"][index][0].data)++[email protected]("resolution", grok.SUPPORTED_RESOLUTIONS)[email protected]("quality", grok.SUPPORTED_QUALITIES)+def test_every_priced_level_reaches_the_request_and_the_report(tmp_path, api, quality, resolution):+ """The two knobs Imagine prices on arrive verbatim — no normalising, no default."""+ result = gen.generate_image("grok", "x", tmp_path / f"{quality}-{resolution}.png",+ quality=quality, resolution=resolution)+ body = _sent(api)+ assert body["quality"] == quality and body["resolution"] == resolution+ assert result.extra["quality"] == quality and result.extra["resolution"] == resolution+++def test_asking_for_neither_leaves_the_request_and_report_as_they_were(tmp_path, api):+ result = gen.generate_image("grok", "x", tmp_path / "out.png")+ body = _sent(api)+ assert "quality" not in body and "resolution" not in body+ # The service default (`auto` = low here, medium on edits) is the service's to+ # name; the report does not invent a level that was never requested.+ assert "quality" not in result.extra and "resolution" not in result.extra++[email protected]("options, expected", [+ ({"quality": "high"}, "openai"),+ ({"quality": "xhigh"}, "openai"),+ ({"quality": "max"}, "openai"),+ ({"quality": "bogus"}, "openai"),+ ({"resolution": "4k"}, "1.5k"),+ ({"resolution": "1024"}, "1.5k"),+ ({"resolution": "1K"}, "1.5k"),+])+def test_a_level_grok_cannot_serve_fails_before_upload(tmp_path, api, options, expected):+ with pytest.raises(SystemExit) as error:+ grok.GrokProvider().generate(GenRequest("x", tmp_path / "raw.png", **options), tmp_path)+ message = str(error.value)+ assert next(iter(options.values())) in message and expected in message+ assert api["calls"] == []+++def test_an_edit_carries_the_knobs_too(tmp_path, api):+ ref = tmp_path / "ref.png"+ Image.new("RGB", (12, 8), (0, 0, 200)).save(ref)+ gen.generate_image("grok", "x", tmp_path / "edit.png", refs=[ref], quality="medium", resolution="2k")+ request, _ = api["calls"][0]+ assert request.full_url.endswith("/images/edits")+ assert _sent(api)["quality"] == "medium" and _sent(api)["resolution"] == "2k"+++def test_the_api_key_notice_names_what_the_image_is_priced_on(tmp_path, api, capsys):+ """불변식 5: 2k medium bills twice 1k low, so the charge line says which one left."""+ gen.generate_image("grok", "x", tmp_path / "out.png", quality="medium", resolution="2k")+ notice = [line for line in capsys.readouterr().err.splitlines() if "per-call API charge" in line]+ assert len(notice) == 1+ assert "quality=medium" in notice[0] and "resolution=2k" in notice[0]+++def test_the_subscription_route_stays_silent_about_billing(tmp_path, api, monkeypatch, capsys):+ _subscription_login(tmp_path, monkeypatch)+ gen.generate_image("grok", "x", tmp_path / "out.png", quality="low", resolution="1k")+ assert "per-call API charge" not in capsys.readouterr().err+ assert _sent(api)["quality"] == "low"++[email protected]("model, scoped", [("grok-2-image", True), (None, False)])+def test_a_rejected_request_names_the_model_the_knobs_are_documented_for(tmp_path, api, model, scoped):+ """docs.x.ai scopes quality/resolution to grok-imagine-image-2.0; a 400 on another+ model should say so instead of leaving the caller with a bare status code."""+ api.update(status=400, body={"error": "synthetic-secret https://signed.invalid/private"})+ with pytest.raises(SystemExit, match="HTTP 400") as error:+ gen.generate_image("grok", "x", tmp_path / "out.png", model=model, quality="low", resolution="2k")+ message = str(error.value)+ assert ("quality=low, resolution=2k" in message and grok.DEFAULT_MODEL in message) is scoped+ assert "synthetic-secret" not in message+++def test_cli_carries_quality_and_resolution_into_the_body(tmp_path, api):+ assert gen.main(["--provider", "grok", "--prompt", "x", "--out", str(tmp_path / "cli.png"),+ "--quality", "low", "--resolution", "1.5k"]) == 0+ assert _sent(api)["quality"] == "low" and _sent(api)["resolution"] == "1.5k"+++def test_the_declared_subsets_are_the_servers_own_enums():+ """Pinned to what the live API answered on 2026-09-20, which is not what either+ doc page says on its own: `high` deserializes but the model refuses it with+ HTTP 400, and `1.5k` renders although the capability guide omits it. Widening+ or narrowing these needs a fresh probe, not a doc reading — the service ignores+ a field it does not know instead of refusing it."""+ assert grok.SUPPORTED_QUALITIES == ("auto", "low", "medium")+ assert grok.SUPPORTED_RESOLUTIONS == ("1k", "1.5k", "2k")+ # Both live inside the shared CLI vocabulary, so every level grok declares is+ # one `--quality` / `--resolution` can actually pass in.+ assert set(grok.SUPPORTED_QUALITIES) <= set(gen_base.QUALITIES)+ assert set(grok.SUPPORTED_RESOLUTIONS) <= set(gen_base.RESOLUTIONS)diff --git a/tests/gen/test_openai_provider.py b/tests/gen/test_openai_provider.pyindex 2576039..c5d37dc 100644--- a/tests/gen/test_openai_provider.py+++ b/tests/gen/test_openai_provider.py@@ -220,7 +220,7 @@ def test_invalid_request_fails_before_any_billable_call(tmp_path, api):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"}):+ {"aspect_ratio": "19.5:9"}, {"quality": "ultra"}, {"resolution": "2k"}):prompt = options.pop("prompt", "x")with pytest.raises(SystemExit):openai.OpenAIProvider().generate(GenRequest(prompt, tmp_path / "raw.png", **options), tmp_path)@@ -342,3 +342,12 @@ def test_cli_accepts_provider_and_quality(tmp_path, api):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"+++def test_a_grok_resolution_is_refused_rather_than_dropped(tmp_path, api):+ """gpt-image has no long-edge preset: --resolution would be paid for and ignored."""+ with pytest.raises(SystemExit, match="aspect-ratio") as error:+ gen.generate_image("openai", "x", tmp_path / "out.png", resolution="2k")+ assert "2k" in str(error.value)+ assert api["calls"] == []+ assert not (tmp_path / "out.png").exists()