Skip to content

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

refactor: one copy each of the report printer (gen.base.print_json for gen, the video verbs and pixel-draw), of what ends a call unanswered and its words (xai's, for the Anthropic transport too), and of the preview checker (qa.preview, for compose-gif, compose-cycle and the pixel-draw pick sheet, whose grey squares take its two greys)

Soohong Kim5a6752e0db10
diff --git a/sprite_gen/compose/compose_cycle.py b/sprite_gen/compose/compose_cycle.py
index 35f246d..24ad2f3 100644
--- a/sprite_gen/compose/compose_cycle.py
+++ b/sprite_gen/compose/compose_cycle.py
@@ -19,6 +19,7 @@ from PIL import Image, ImageDraw
from sprite_gen.curate.curation import apply_pixel_edits, apply_transform, frame_variant, load_curation, pixel_snap_scale, source_frame_index, state_pixel_ops, state_plan
from sprite_gen.spec.layout import row_frame_rel, state_frame_total
from sprite_gen.frames.extract import require_frames_manifest
+from sprite_gen.qa.preview import flatten
from sprite_gen.util.gif_utils import delay_ticks_to_duration_ms, save_clean_gif
from sprite_gen.spec.runio import read_guard, relative_posix, load_request
@@ -31,23 +32,6 @@ def sha256(path: Path) -> str:
return digest.hexdigest()
-def checker(size: tuple[int, int], square: int = 16) -> Image.Image:
- width, height = size
- image = Image.new("RGBA", size, (210, 210, 210, 255))
- pixels = image.load()
- for y in range(height):
- for x in range(width):
- if ((x // square) + (y // square)) % 2 == 0:
- pixels[x, y] = (235, 235, 235, 255)
- return image
-
-
-def flatten(frame: Image.Image) -> Image.Image:
- base = checker(frame.size)
- base.alpha_composite(frame)
- return base.convert("RGB")
-
-
def parse_frames(value: str) -> list[int]:
frames = [int(part.strip()) for part in value.split(",") if part.strip()]
if not frames:
diff --git a/sprite_gen/compose/compose_gif.py b/sprite_gen/compose/compose_gif.py
index 5233acd..f6089f2 100644
--- a/sprite_gen/compose/compose_gif.py
+++ b/sprite_gen/compose/compose_gif.py
@@ -18,6 +18,7 @@ from sprite_gen.effects.breathe import anatomy_report, bake_breathe_sequence
from sprite_gen.curate.curation import apply_pixel_edits, apply_transform, edit_index, frame_variant, load_curation, pixel_snap_scale, source_frame_index, state_breathe, state_pixel_ops, state_plan
from sprite_gen.spec.layout import row_frame_rel, state_frame_total
from sprite_gen.frames.extract import require_frames_manifest
+from sprite_gen.qa.preview import flatten
from sprite_gen.spec.runio import read_guard, load_request
from sprite_gen.util.gif_utils import delay_ticks_to_duration_ms, gif_report, save_clean_gif
@@ -31,23 +32,6 @@ def parse_frame_order(value: str) -> list[int]:
return frames
-def checker(size: tuple[int, int], square: int = 16) -> Image.Image:
- width, height = size
- image = Image.new("RGBA", size, (210, 210, 210, 255))
- pixels = image.load()
- for y in range(height):
- for x in range(width):
- if ((x // square) + (y // square)) % 2 == 0:
- pixels[x, y] = (235, 235, 235, 255)
- return image
-
-
-def flatten(frame: Image.Image) -> Image.Image:
- base = checker(frame.size)
- base.alpha_composite(frame.convert("RGBA"))
- return base.convert("RGB")
-
-
def load_frames(args: argparse.Namespace) -> list[tuple[int, Path, Image.Image]]:
if args.frame_dir:
frame_dir = args.frame_dir.expanduser().resolve()
diff --git a/sprite_gen/gen/__init__.py b/sprite_gen/gen/__init__.py
index 529499d..6bc89de 100644
--- a/sprite_gen/gen/__init__.py
+++ b/sprite_gen/gen/__init__.py
@@ -61,6 +61,7 @@ from .base import (
GenRequest,
GenResult,
GenTimeoutError,
+ print_json,
provider_binary,
provider_subprocess_env,
verify_png,
@@ -666,28 +667,10 @@ def _run(args: argparse.Namespace) -> int:
report_path = Path(args.report).expanduser().resolve()
atomic_write_text(report_path, json.dumps(payload, ensure_ascii=False, indent=2) + "\n")
payload["report"] = str(report_path)
- _print_json(payload)
+ print_json(payload)
return 0
-def _print_json(payload: dict) -> None:
- """Emit the machine-readable report as UTF-8 on every host locale.
-
- A generated prompt may contain Korean or an em dash. On a Windows cp949
- redirected stream, writing that through ``TextIOWrapper`` can fail after
- the image already exists. The binary buffer is the CLI byte contract and
- avoids mutating process-global stdout configuration. Captured/in-memory
- streams without a buffer already accept Unicode and use the text path.
- """
- text = json.dumps(payload, ensure_ascii=False, indent=2) + "\n"
- buffer = getattr(sys.stdout, "buffer", None)
- if buffer is not None:
- buffer.write(text.encode("utf-8"))
- buffer.flush()
- else:
- sys.stdout.write(text)
-
-
def _build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(prog="sprite-gen gen", description=__doc__)
add_arguments(parser)
diff --git a/sprite_gen/gen/anthropic_api.py b/sprite_gen/gen/anthropic_api.py
index 853f5b8..e1df9f3 100644
--- a/sprite_gen/gen/anthropic_api.py
+++ b/sprite_gen/gen/anthropic_api.py
@@ -4,7 +4,8 @@ Message Batches, and what a call cost.
Raw HTTP over urllib, like `openai_provider` and `xai`: the runtime dependency surface is Pillow
and NumPy (SECURITY.md), and one more SDK with its own HTTP stack would be a second transport for
-the same job. Field names and behaviour are the documented Messages API surface
+the same job. What ends an exchange unanswered (`NO_ANSWER`) and the words for it
+(`no_answer_reason`) are `xai`'s. Field names and behaviour are the documented Messages API surface
(platform.claude.com, 2026-10-12 확인):
- `POST /v1/messages` with `stream: true` answers Server-Sent Events: `message_start` (a message
@@ -41,6 +42,7 @@ from dataclasses import dataclass
from typing import Any, Callable
from . import refusal
+from .xai import NO_ANSWER, no_answer_reason
API_BASE = "https://api.anthropic.com/v1"
API_VERSION = "2023-06-01"
@@ -63,9 +65,6 @@ RETRY_AFTER_MAX = 120.0
# API sends `ping`s, so a stream that says nothing for minutes is stalled, not thinking.
READ_TIMEOUT_SECONDS = float(os.environ.get("SPRITE_GEN_CLAUDE_READ_TIMEOUT_SECONDS", "300"))
-# Everything that ends an exchange before its answer is read whole (as in `xai.NO_ANSWER`).
-NO_ANSWER = (OSError, http.client.HTTPException)
-
Sleep = Callable[[float], None]
@@ -192,13 +191,6 @@ def refused_line(status: int, body: Any, token: str | None) -> str:
return f"pixel-draw: claude request failed (HTTP {status}){suffix}; not asked again{refusal.said(body, token)}"
-def _no_answer(exc: BaseException) -> str:
- said = exc.reason if isinstance(exc, urllib.error.URLError) else exc
- if isinstance(said, http.client.HTTPException) and not isinstance(said, OSError):
- return repr(said)[:200]
- return (str(said) or type(said).__name__)[:200]
-
-
def _retry_after(headers: Any) -> float | None:
value = headers.get("retry-after") if headers is not None else None
try:
@@ -228,7 +220,7 @@ def _open(request_for: Callable[[], urllib.request.Request], token: str, *, time
raise ApiError(refused_line(exc.code, body, token), status=exc.code,
request_id=exc.headers.get("request-id") if exc.headers else None, billed=False) from exc
except NO_ANSWER as exc:
- raise ApiError(f"pixel-draw: claude request got no answer ({_no_answer(exc)}); not asked again "
+ raise ApiError(f"pixel-draw: claude request got no answer ({no_answer_reason(exc)}); not asked again "
"(the API may have accepted it)") from exc
raise AssertionError("unreachable")
@@ -318,7 +310,7 @@ def stream_message(token: str, body: dict[str, Any], *, sleep: Sleep = time.slee
state.feed(json.loads("\n".join(event_data)))
except NO_ANSWER as exc:
partial = state.reply(request_id=request_id, seconds=time.monotonic() - started)
- raise ApiError(f"pixel-draw: the answer stream broke ({_no_answer(exc)}); not asked again "
+ raise ApiError(f"pixel-draw: the answer stream broke ({no_answer_reason(exc)}); not asked again "
"(what was written may be billed)", request_id=request_id, partial=partial) from exc
except (json.JSONDecodeError, UnicodeDecodeError) as exc:
partial = state.reply(request_id=request_id, seconds=time.monotonic() - started)
@@ -346,7 +338,7 @@ def _json_call(method: str, url: str, token: str, body: dict[str, Any] | None, *
with response:
raw = response.read().decode("utf-8")
except NO_ANSWER as exc:
- raise ApiError(f"pixel-draw: claude answer broke ({_no_answer(exc)})") from exc
+ raise ApiError(f"pixel-draw: claude answer broke ({no_answer_reason(exc)})") from exc
try:
return json.loads(raw) if raw else {}
except json.JSONDecodeError as exc:
@@ -398,7 +390,7 @@ def batch_results(token: str, batch: dict[str, Any], *, sleep: Sleep = time.slee
with response:
lines = response.read().decode("utf-8").splitlines()
except NO_ANSWER as exc:
- raise ApiError(f"pixel-draw: batch results broke ({_no_answer(exc)})") from exc
+ raise ApiError(f"pixel-draw: batch results broke ({no_answer_reason(exc)})") from exc
results: dict[str, Reply | ApiError] = {}
for line in lines:
if not line.strip():
diff --git a/sprite_gen/gen/base.py b/sprite_gen/gen/base.py
index 6918316..8483893 100644
--- a/sprite_gen/gen/base.py
+++ b/sprite_gen/gen/base.py
@@ -11,6 +11,7 @@ path or a "done" string (No Silent Fallback).
from __future__ import annotations
import io
+import json
import os
import shutil
import sys
@@ -118,6 +119,25 @@ def announce_api_billing(provider: str, env_name: str, detail: str = "") -> None
)
+def print_json(payload: dict) -> None:
+ """Emit the machine-readable report as UTF-8 on every host locale.
+
+ A generated prompt may contain Korean or an em dash. On a Windows cp949
+ redirected stream, writing that through ``TextIOWrapper`` can fail after
+ the image already exists. The binary buffer is the CLI byte contract and
+ avoids mutating process-global stdout configuration. Captured/in-memory
+ streams without a buffer already accept Unicode and use the text path.
+ One writer for every report `gen`, the video verbs and `pixel-draw` print.
+ """
+ text = json.dumps(payload, ensure_ascii=False, indent=2) + "\n"
+ buffer = getattr(sys.stdout, "buffer", None)
+ if buffer is not None:
+ buffer.write(text.encode("utf-8"))
+ buffer.flush()
+ else:
+ sys.stdout.write(text)
+
+
def verify_png(path: Path) -> int:
"""Return the PNG byte count, or raise SystemExit if it is missing/not a PNG."""
if not path.is_file():
diff --git a/sprite_gen/gen/pixel_draw.py b/sprite_gen/gen/pixel_draw.py
index 2399311..eed6bd6 100644
--- a/sprite_gen/gen/pixel_draw.py
+++ b/sprite_gen/gen/pixel_draw.py
@@ -17,10 +17,10 @@ One run, `--candidates` K answers to the same request:
most twice in all.
3. G2 palette, G3 alpha and G6 frames fail a candidate; G4 tile seam, G5 stray pixels, the walk
cycle's leg alternation and G8 safe area (a frame past the physical cap, a sprite off the floor
- row) warn, and G8 notes a frame past the safe area within the cap in an info line — the image
- path's judgment (`frames.extract.safe_area_fit`). The prompt gives a sprite or icon the engine's
- safe area (`safe_area_lines`) in rows and columns, as a target for the body's size that a pose
- may go past.
+ row) warn, and G8 notes a frame past the safe area within the cap in an info line. G3, G4, G5
+ and G8 are judgments sprite-gen already makes elsewhere, called rather than copied
+ (`pixel_gates`). The prompt gives a sprite or icon the engine's safe area (`safe_area_lines`) in
+ rows and columns, as a target for the body's size that a pose may go past.
4. G7: of two or more candidates that passed, one vision call (effort low) picks, or a person
does (`--pick human`). One that passed alone is the pick.
@@ -49,12 +49,13 @@ from typing import Any, Callable, Generator
from PIL import Image, ImageDraw
+from sprite_gen.qa.preview import checker
from sprite_gen.spec.runio import atomic_write_text
from . import anthropic_api as api
from . import refusal
from .anthropic_api import ApiError, Reply
-from .base import announce_api_billing
-from .pixel_gates import evaluate, safe_area
+from .base import announce_api_billing, print_json
+from .pixel_gates import colors_used, evaluate, safe_area
from .pixel_grid import (
FORMATS, Grid, Issue, PaletteRule, check_rows, frame_name_ok, frame_pixels, palette_rule, parse_answer,
parse_row_answers, png_bytes, preview_scale, preview_strip, read_grid_text, recovered, row_issues, row_text,
@@ -797,18 +798,12 @@ def _issue_list(issues: list[Issue]) -> str:
return ", ".join(shown) + (f" and {len(failing) - 6} more" if len(failing) > 6 else "")
-def _checker(width: int, height: int, cell: int = 8) -> Image.Image:
- board = Image.new("RGBA", (width, height), (236, 236, 236, 255))
- draw = ImageDraw.Draw(board)
- for y in range(0, height, cell):
- for x in range(0, width, cell):
- if (x // cell + y // cell) % 2:
- draw.rectangle([x, y, x + cell - 1, y + cell - 1], fill=(206, 206, 206, 255))
- return board
+PICK_CHECKER_SQUARE = 8 # sheet pixels a square of the checker under a preview
def pick_sheet(run_dir: Path, by_label: dict[str, Candidate], *, tile: bool) -> bytes:
- """One sheet of the candidates' previews (and 3x3 tilings), each row labelled."""
+ """One sheet of the candidates' previews (and 3x3 tilings), each row labelled, a preview's
+ transparency on the engine's preview checker (`qa.preview.checker`)."""
rows = []
for label, candidate in by_label.items():
preview = Image.open(run_dir / candidate.files["preview"]).convert("RGBA")
@@ -823,7 +818,7 @@ def pick_sheet(run_dir: Path, by_label: dict[str, Candidate], *, tile: bool) ->
for label, preview, tiled in rows:
draw.text((pad, y + 4), label, fill=(0, 0, 0, 255), font_size=36)
x = pad + label_width
- sheet.alpha_composite(Image.alpha_composite(_checker(preview.width, preview.height), preview), (x, y))
+ sheet.alpha_composite(Image.alpha_composite(checker(preview.size, PICK_CHECKER_SQUARE), preview), (x, y))
if tiled is not None:
sheet.alpha_composite(tiled, (x + preview.width + pad, y))
y += max(preview.height, tiled.height if tiled is not None else 0) + pad
@@ -888,16 +883,6 @@ def _write_report(run_dir: Path, report: dict[str, Any]) -> Path:
return path
-def _print_json(payload: dict[str, Any]) -> None:
- text = json.dumps(payload, ensure_ascii=False, indent=2) + "\n"
- buffer = getattr(sys.stdout, "buffer", None)
- if buffer is not None:
- buffer.write(text.encode("utf-8"))
- buffer.flush()
- else:
- sys.stdout.write(text)
-
-
# ----------------------------------------------------------------------------- the verb
def add_arguments(parser: argparse.ArgumentParser) -> None:
@@ -988,20 +973,16 @@ def _run_grid(args: argparse.Namespace) -> int:
raise _refuse(f"{args.grid} does not parse whole: {_issue_list(issues)}; report {path}")
pixels = {name: frame_pixels(grid, name) for name in frames}
gates = evaluate(pixels, kind=kind, rule=rule, walk_cycle=bool(args.walk_cycle))
- files = write_files(out_dir, grid, frames, kind, rule, _colors_used(pixels))
+ files = write_files(out_dir, grid, frames, kind, rule, colors_used(pixels))
report.update(status="ok" if gates["ok"] else "failed", gates=gates, warnings=gates["warnings"], info=gates["info"],
files=files, request={**report["request"], "size": [grid.width, grid.height]})
path = _write_report(out_dir, report)
if not gates["ok"]:
raise _refuse(f"{args.grid} fails {', '.join(gates['failed'])}; files and report in {out_dir} ({path.name})")
- _print_json(report)
+ print_json(report)
return 0
-def _colors_used(pixels: dict[str, Any]) -> list[str]:
- return sorted({"#{:02X}{:02X}{:02X}".format(*p[:3]) for f in pixels.values() for row in f for p in row if p[3] >= 128})
-
-
def _run(args: argparse.Namespace, *, sleep: Callable[[float], None] = time.sleep) -> int:
if args.grid is not None:
return _run_grid(args)
@@ -1045,7 +1026,7 @@ def _run(args: argparse.Namespace, *, sleep: Callable[[float], None] = time.slee
if candidate.grid is not None:
pixels = {name: frame_pixels(candidate.grid, name) for name in request.frames}
files = write_files(out_dir / "candidates" / candidate.id, candidate.grid, request.frames, request.kind,
- request.palette, _colors_used(pixels))
+ request.palette, colors_used(pixels))
candidate.files = _prefixed(files, f"candidates/{candidate.id}")
passed = [c for c in candidates if c.status == "passed"]
report["candidates"] = [c.to_dict() for c in candidates]
@@ -1074,7 +1055,7 @@ def _run(args: argparse.Namespace, *, sleep: Callable[[float], None] = time.slee
f"{out_dir / 'candidates'}; report {path}")
report["status"] = "ok"
_finish(report, calls, started)
- _print_json(report)
+ print_json(report)
return 0
diff --git a/sprite_gen/gen/video.py b/sprite_gen/gen/video.py
index 424bf7b..23f5606 100644
--- a/sprite_gen/gen/video.py
+++ b/sprite_gen/gen/video.py
@@ -60,7 +60,7 @@ from typing import Any, Callable
from sprite_gen.spec.runio import atomic_write_text
from . import prompt_parts, refusal
-from .base import announce_api_billing
+from .base import announce_api_billing, print_json
from .facing import FACINGS, validate as validate_facing
from sprite_gen.video import facing as facing_mod
from .xai import (
@@ -970,16 +970,6 @@ def resume_video(
)
-def _print_json(payload: dict) -> None:
- text = json.dumps(payload, ensure_ascii=False, indent=2) + "\n"
- buffer = getattr(sys.stdout, "buffer", None)
- if buffer is not None:
- buffer.write(text.encode("utf-8"))
- buffer.flush()
- else:
- sys.stdout.write(text)
-
-
def _add_prompt_and_report(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--prompt")
parser.add_argument("--prompt-file", type=Path)
@@ -1051,7 +1041,7 @@ def _publish_report(args: argparse.Namespace, make: Callable[[], VideoResult]) -
if report_path is not None:
atomic_write_text(report_path, json.dumps(payload, ensure_ascii=False, indent=2) + "\n")
payload["report"] = str(report_path)
- _print_json(payload)
+ print_json(payload)
return 0
diff --git a/sprite_gen/gen/xai.py b/sprite_gen/gen/xai.py
index 3154cea..ae10174 100644
--- a/sprite_gen/gen/xai.py
+++ b/sprite_gen/gen/xai.py
@@ -155,12 +155,18 @@ NO_ANSWER = (OSError, http.client.HTTPException)
def no_answer(exc: BaseException) -> TransportError:
+ return TransportError(no_answer_reason(exc))
+
+
+def no_answer_reason(exc: BaseException) -> str:
+ """What the transport said when a request got no answer it could read: the words every direct
+ provider call (xAI here, Anthropic in `anthropic_api`) puts in its line."""
said = exc.reason if isinstance(exc, urllib.error.URLError) else exc
# An http.client exception carries what the server sent (BadStatusLine its line, CRLF included);
# its repr names the kind and keeps that on one line. RemoteDisconnected is a reset too: its words.
if isinstance(said, http.client.HTTPException) and not isinstance(said, OSError):
- return TransportError(repr(said)[:200])
- return TransportError((str(said) or type(said).__name__)[:200])
+ return repr(said)[:200]
+ return (str(said) or type(said).__name__)[:200]
ANSWER_CHUNK = 1 << 16 # what one read of an answer bounded by a deadline asks for
diff --git a/sprite_gen/qa/preview.py b/sprite_gen/qa/preview.py
index be1062b..110f121 100644
--- a/sprite_gen/qa/preview.py
+++ b/sprite_gen/qa/preview.py
@@ -24,7 +24,9 @@ from sprite_gen.util.gif_utils import delay_ticks_to_duration_ms, save_clean_gif
def checker(size: tuple[int, int], square: int = 16) -> Image.Image:
- """Neutral checker so transparent pixels and stray fringe are both visible."""
+ """Neutral checker so transparent pixels and stray fringe are both visible. The one checker of
+ sprite-gen's previews: these contact sheets, `compose-gif`'s and `compose-cycle`'s, and
+ `pixel-draw`'s pick sheet."""
w, h = size
bg = Image.new("RGBA", size, (210, 210, 210, 255))
px = bg.load()
@@ -37,7 +39,7 @@ def checker(size: tuple[int, int], square: int = 16) -> Image.Image:
def flatten(frame: Image.Image) -> Image.Image:
base = checker(frame.size)
- base.alpha_composite(frame)
+ base.alpha_composite(frame.convert("RGBA"))
return base.convert("RGB")
diff --git a/tests/gen/test_gen.py b/tests/gen/test_gen.py
index 1aa86e4..62d8ae7 100644
--- a/tests/gen/test_gen.py
+++ b/tests/gen/test_gen.py
@@ -142,7 +142,7 @@ def test_json_report_writes_utf8_bytes_without_reconfiguring_stdout(monkeypatch)
raw = io.BytesIO()
cp949_stream = io.TextIOWrapper(raw, encoding="cp949")
monkeypatch.setattr(sys, "stdout", cp949_stream)
- gen._print_json({"prompt": "도구 — 완료"})
+ gen_base.print_json({"prompt": "도구 — 완료"})
cp949_stream.detach()
assert json.loads(raw.getvalue().decode("utf-8")) == {"prompt": "도구 — 완료"}