Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
refactor: one copy of how a Claude call's tokens split by price - anthropic_api.billed_tokens, out of cost_usd unchanged (input, output, cache reads, cache writes by lifetime, a write the reply does not split a five-minute one), which cost_usd now prices; public, so a caller that prices the calls at rates of its own reads the same split; docs/pixel-draw.md and CHANGELOG Unreleased name it
Soohong Kim20da1c8de771
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a905b1e..49f5a23 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,7 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the- **Fix: a hex colour is six hex digits, the `#` optional — read and written in one place (`util.hexcolor`).** `recolor`'s map, `slice-sheet --chroma-key`, `handed-check --marker` / `--strap` and the curation view's pixel edits took a sign or an underscore as a digit (`#-1-1-1` read as (-1, -1, -1); a non-hex six-letter edit stopped the request); each now refuses it in its own words, and the curation view skips it as it skips a value of the wrong length. `prepare --chroma-key` also takes `RRGGBB` without the `#`, as the other flags did. Written colours are unchanged: upper case, and lower case in `recolor`'s report and palette draft.- **Fix: a Python call of `gen.run`, the video verbs' `run`, `pixel-draw`'s `run` or `inspect-motion`'s `run` without a required flag is a TypeError naming it**, as the other verbs' `run(**kwargs)` always said; these four read their keywords by hand and went on with `None`. One reader for all, `util.cli_kwargs.namespace_from_kwargs`, in place of twelve copies and four hand-made readings.- **Internal: `pixel-draw`'s G8 sizes a frame by the image path's opaque box, `frames.extract.solid_alpha_bbox`**, in place of its own count of opaque rows and columns — the same box, read in one place; `gates.G8` is unchanged.+- **New: `anthropic_api.billed_tokens(usage)` — a Claude call's tokens by the price each is billed at**, the split `cost_usd` priced inline, now one public function `cost_usd` asks: input, output, cache reads, and cache writes by their lifetime (`usage.cache_creation`'s five-minute and one-hour counts; a reply that does not split them wrote for five minutes), keyed as `PRICE_PER_MTOK` prices them, each count as the reply gave it. A caller that prices the calls at rates of its own reads the same split instead of keeping a copy. `cost_usd` is unchanged.- **Tests** — `tests/gen/test_retry.py` (the rule per provider and status, every direct call asking it, a broken refusal body is no answer on all three transports), `tests/gen/test_flags_over_spec.py`, `tests/test_cli_kwargs.py`, `tests/test_hexcolor.py` (each verb reads through the one function; a second copy turns them red), and the provider, video, video-set and G8 tests moved to the new answers.- **New (experimental): `sprite-gen pixel-draw` — Claude Opus draws pixel art of 8–48 px directly, as a pixel grid.** The model writes a palette and one line of keys per pixel row (a character grid, or JSON with `--format json`); code checks it and renders it. `--subject` (or `--spec`), `--size` 8–48 (32), `--kind sprite|icon|tile`, `--frames` (up to four, drawn in one call; `--walk-cycle` for contact, passing, contact, passing), `--palette free[:N]|pico8|#hex,…|file`, `--candidates` (2), `--effort medium|high|xhigh` (high), `--batch` (Message Batches, half price), `--max-tokens` (32000 for one frame, 64000 for more), `--pick vision|human`. G1 reads every answer strictly; a row one key too long or short, a key outside the palette or rows missing at the end go back to the model on their own with a column ruler and are spliced in (two rounds), and an answer still broken — or broken beyond its rows — is drawn once more; a single frame written without its `FRAME` line is recovered and recorded. A sprite or icon is drawn to the engine's safe area — `prepare`'s margin, 9.4% of the side, floored, taken from `prepare` rather than copied — as a target for the body's average size, not a wall: at 32 px the body is about the size of the central 26×26 (16 → 14, 24 → 20, 48 → 40), a pose or a detail that needs the room (a raised weapon, a long blade, an effect, a wide stance) may reach past it into the margin, up to the canvas edge, and a sprite's feet stand on the safe area's bottom row, the row `prepare`'s fit grounds a frame on, in every frame; the prompt says it in rows and columns counted from 1. G2 palette, G3 alpha and G6 frames (one ground line, heights within a pixel, no two frames the same — a sprite's or icon's measured inside the safe area, so a staff or a spark that reaches into the margin in one frame is not a taller figure) fail a candidate; G4 tile seam, G5 stray pixels and a walk whose legs barely change sides warn. G3, G4 and G5 ask judgments sprite-gen already makes rather than keep their own, each lifted out of its owner unchanged: G3 is whether a frame's background is really transparent by the verdict `gen` reads a generated raw by (`chroma.alpha_verdict`, out of `classify_raw_alpha`: at least 5 % of the pixels and half the one-pixel border alpha 0 for a sprite or icon, with something drawn and the four corners clear; no alpha-0 pixel for a tile); G4 is `background-tile`'s join measure (`inspect_tile`), asked of a tile along x and along y, and warns with its reasons where it says `needs-review`; G5 counts the lone pixels the YCbCr matte cleanup erases (`frames.extract.isolated_dots`, out of `_cleanup_alpha_ycc`: no opaque pixel among the eight neighbours), so each pixel of a one-pixel diagonal stroke, which touches the next at a corner, is no longer a stray pixel. G8 safe area never fails a candidate: it takes the judgment the pixel snap already makes — one function, `safe_area_fit` in `frames/extract.py`, lifted out of the snap with its lines unchanged — on each frame's opaque box: past the physical cap (the canvas's width, its height less the margin under the floor row, 32×29 at 32 px) warns, a reroll candidate; past the safe area but within the cap is an info line, `info` in the report, which asks for nothing; and a sprite whose feet are off the floor row warns. Of two or more candidates that pass, one vision call at effort low picks (G7). An answer that spent every token thinking is drawn once more one effort lower; a refusal is reported as it came (`refused by the provider's content policy (stop_reason=refusal category=…)`); nothing falls back to another model. The run folder holds `grid.txt` (the truth: edit it and re-render with `--grid`), `palette.json`, `frame-<name>.png` written by an encoder whose bytes depend on the pixels alone, `preview-x<s>.png`, `tiled-3x3.png` for a tile, `anim.gif` for several frames, every call under `calls/` and `report.json` with each call's model, effort, usage (thinking tokens included), price, seconds and request id, the gate results and the repair history. A batch is recorded the moment it is submitted, and `--resume` collects it — and reads every answered call back — instead of buying it twice. It runs on `ANTHROPIC_API_KEY`, billed per call and said so on stderr; the transport is urllib, so the dependency surface stays Pillow and NumPy — [docs/pixel-draw.md](docs/pixel-draw.md).- **Fix: a poll xAI answers 429 or 5xx asks the same request again — the clip is bought once.** `video`, `video-extend` and `video-edit` ended the run on any non-2xx poll, after xAI had accepted the request and may bill it, and the line read `(HTTP 429)` — what `video-set`, and any caller that backs off on a refused submission, answers by submitting the clip again: a second clip paid for, the first never published. A poll answered `429`, `500`, `502`, `503` or `504` is now asked again on the same `request_id`, after a wait that doubles from 8 s up to 60 s while the polls are refused and goes back to 4 s on an answer; a stderr note says each, the status in plain digits. The poll timeout (`SPRITE_GEN_VIDEO_TIMEOUT_SECONDS`) still bounds the whole poll, a pending poll's waits included (and, below, the downloads). A refused POST is still never sent again, and a `400` or `404` poll still ends the run with its status (a `401` or `403` poll is unfinished, below).diff --git a/docs/pixel-draw.md b/docs/pixel-draw.mdindex ad07303..868d0b5 100644--- a/docs/pixel-draw.md+++ b/docs/pixel-draw.md@@ -239,7 +239,11 @@ zlib build. The previews, the tiling and the GIF are views for the eye.| `usage`, `cost_usd`, `seconds` | totals over the calls, and the run's wall time |`cost_usd` is each call's usage at the published price (below), Message Batches at half. It is-what the calls cost by the API's own usage counts, not a console bill.+what the calls cost by the API's own usage counts, not a console bill. Which price each token is+billed at is one function, `anthropic_api.billed_tokens`: input, output, cache reads, and cache+writes by their lifetime (`usage.cache_creation`'s five-minute and one-hour counts; a reply that+does not split them wrote for five minutes), each count as the reply gave it — a caller pricing+the calls at rates of its own reads the same split.## Failuresdiff --git a/sprite_gen/gen/anthropic_api.py b/sprite_gen/gen/anthropic_api.pyindex 3fb0496..e2c2c04 100644--- a/sprite_gen/gen/anthropic_api.py+++ b/sprite_gen/gen/anthropic_api.py@@ -135,21 +135,24 @@ def thinking_tokens(usage: dict[str, Any]) -> int | None:return value if isinstance(value, int) else None-def cost_usd(usage: dict[str, Any], *, batch: bool, model: str = MODEL) -> float:- """What `usage` costs at the published prices; Message Batches bill half."""- price = PRICE_PER_MTOK[model]+def billed_tokens(usage: dict[str, Any]) -> dict[str, Any]:+ """One call's tokens by the price each is billed at, keyed as `PRICE_PER_MTOK` prices them. Thinking is inside+ `output_tokens`. Cache writes are split by their lifetime (`usage.cache_creation`); a reply that does not split+ them wrote for five minutes. Each count is as the reply gave it — None where it gave none — so a caller pricing+ the call at rates of its own reads a missing count its own way; `cost_usd` reads it as nothing."""creation = usage.get("cache_creation") if isinstance(usage.get("cache_creation"), dict) else {}write_5m = creation.get("ephemeral_5m_input_tokens")write_1h = creation.get("ephemeral_1h_input_tokens")if write_5m is None and write_1h is None:- write_5m, write_1h = usage.get("cache_creation_input_tokens") or 0, 0- total = (- (usage.get("input_tokens") or 0) * price["input"]- + (write_5m or 0) * price["cache_write_5m"]- + (write_1h or 0) * price["cache_write_1h"]- + (usage.get("cache_read_input_tokens") or 0) * price["cache_read"]- + (usage.get("output_tokens") or 0) * price["output"]- ) / 1_000_000+ write_5m, write_1h = usage.get("cache_creation_input_tokens"), 0+ return {"input": usage.get("input_tokens"), "cache_write_5m": write_5m, "cache_write_1h": write_1h,+ "cache_read": usage.get("cache_read_input_tokens"), "output": usage.get("output_tokens")}+++def cost_usd(usage: dict[str, Any], *, batch: bool, model: str = MODEL) -> float:+ """What `usage` costs at the published prices (`billed_tokens` at `PRICE_PER_MTOK`); Message Batches bill half."""+ price = PRICE_PER_MTOK[model]+ total = sum((count or 0) * price[kind] for kind, count in billed_tokens(usage).items()) / 1_000_000return round(total * (BATCH_DISCOUNT if batch else 1.0), 6)