Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
retire(game-making): sound, game-pack, ui-kit, gen --layout-guide ui-kit and background-tile --axis xy leave the engine; the CHANGELOG's Unreleased (v4.0.0)
Soohong Kim9fbe5b639890
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 15c5566..f0aec79 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,28 @@All notable public changes to `sprite-gen` are recorded here. Versions track the `version:` field in `SKILL.md` and `pyproject.toml`.+## Unreleased (v4.0.0)++**Upgrading from 3.15.0: `sprite-gen sound`, `sprite-gen game-pack` and `sprite-gen ui-kit` are removed, with `gen --layout-guide ui-kit` and `background-tile --axis xy`.** These game-making features were added for building games. Making games is outside the scope of this engine, which makes sprites; features that belong to sprites stay. Files an earlier version wrote (sound folders, game packs, UI kit folders) stay on disk; nothing reads them.++### Removed++| Removed | Use |+|---|---|+| `sprite-gen sound` (ElevenLabs sound effects and instrumental music with Opus and AAC exports, a SQLite request cache and a browser loop helper), the package `sprite_gen.audio` (`sound`, `provider`, `cache`, `processing`, `manifest`, `playback` and the browser helper `sprite-gen-audio-v2.mjs`, which the wheel no longer carries), `docs/sound.md` | No replacement. |+| The ElevenLabs provider: `sprite_gen.gen.address.ELEVENLABS` and its entry in `address.PROVIDERS`, `SPRITE_GEN_ELEVENLABS_BASE_URL`, `sprite_gen.gen.retry.ELEVENLABS_BUSY` and the ElevenLabs rows of `retry.UNTAKEN` and `retry.ACT_FIRST`; `ELEVENLABS_API_KEY` is no longer read | No replacement. `sprite-gen capabilities` no longer lists the `sound` verb or the `elevenlabs` provider; its `providers` are `openai`, `xai` and `anthropic`. |+| `sprite-gen game-pack` (game atlases with playback policies, sounds, version 2 images, tiles and UI nine-slice entries), `sprite_gen.compose.game_pack`, `docs/game-pack.md` | `compose-atlas` and `export-aseprite` (Phaser and Flame) for engine exports. |+| `sprite_gen.spec.assets.load_asset_states`, which only `game-pack` called | `load_asset` and `PLAYBACK_FIELDS` stay. |+| `sprite-gen ui-kit` (splitting a game UI kit sheet into nine-slice elements), `sprite_gen.frames.ui_kit`, `docs/ui-kit.md` | No replacement. Its "Alpha cleanup" section moved to `docs/sheet-slicing.md` ("Alpha cleanup" under "Transparent sheets"); `slice-sheet --alpha-floor` and `--alpha-edge` are unchanged. |+| `gen --layout-guide ui-kit`, `gen.ui_kit_guide_size` and the `ui_kit_guide` argument of `gen.still_prompt` | No replacement. The bare `--layout-guide` and `--layout-guide figure` are unchanged. |+| `background-tile --axis xy` (one tile that repeats both ways, made for game ground tiles), `sprite_gen.background.tile.inspect_tile_xy` and the cyclic seam it used | No replacement. `--axis x` and `--axis y` are unchanged, and so are their reports. |++- **Stays the same**: non-looping playback (the `video-loop` once cut, the `loop`, `hold_last` and `end_frame` metadata, the play modes), effects (`pixel-draw --kind effect`, brightness alpha, lifetime cuts), `video-stop`, `slice-sheet --scale sheet` and `--fit contain`, the alpha haze cleanup, the refusal of a painted transparency checkerboard, `logo`, `compose-atlas` and `export-aseprite`.+- **Command line**: `sprite-gen sound`, `sprite-gen game-pack` and `sprite-gen ui-kit` end as an unknown command with argparse exit code 2; `gen --layout-guide ui-kit` and `background-tile --axis xy` end as an invalid choice with argparse exit code 2.+- **Dependencies**: the removed features declared no Python dependency. `ffmpeg`, `ffprobe` and the AAC encoder stay required by the video features that use them (`face-bake`, the video source reading, `sprite-gen video`); only the sound checks for them were removed.+- **Old changelog links**: the links in the v2.45.0 section that pointed at `docs/game-pack.md` and `docs/ui-kit.md` now point at those files in the `v2.45.0` tag on GitHub; their wording is unchanged.+- **Tests**: Removed `tests/audio/` (`test_sound.py`, `render_playback.mjs`, `prepare_playback_fixture.py`), `tests/compose/test_game_pack.py`, `tests/compose/test_game_pack_audio.py`, `tests/compose/test_game_pack_v2.py`, `tests/frames/test_ui_kit.py` and `tests/background/test_tile_xy.py`; the game pack test of `tests/video/test_stop.py` and of `tests/frames/test_slice_sheet_scale.py`, the `load_asset_states` test of `tests/spec/test_assets.py`, the three UI kit guide tests of `tests/gen/test_layout_guide.py`, and the ElevenLabs cases of `tests/gen/test_provider_address.py` and `tests/workflow/test_capabilities.py`. Changed: `tests/gen/test_painted_checkerboard.py` refuses the checkerboard through `gen` with the figure layout guide; `tests/workflow/test_capabilities.py` reads a flag's `--no-` alias off `prepare` and a required exclusive group off `video-sway`; `tests/packaging/test_curation_asset_packaging.py` checks that the wheel carries the face player `sprite_gen/video/sprite-gen-face-v1.mjs`.+## v3.15.0 - RIFE is `rife-v4.25` from TNTwise's 20250112 release by default, padded to 128 with no augmentation, the old `rife-v4.6` kept by name (`SPRITE_GEN_RIFE_MODEL_NAME`), and `sprite-gen rife install` run again**Upgrading from 3.14.0: RIFE is rife-v4.25 by default, so every frame RIFE makes changes, `sprite-gen rife install` must run again, and the old model is one variable away.** The engine runs TNTwise's rife-ncnn-vulkan 20250112 and its `rife-v4.25` with no augmentation, each image padded to 128; 3.14.0 ran nihui's 20221029 and `rife-v4.6` with `-x -z`. A cut with no held cell and no repair runs no RIFE and keeps its bytes (`tests/video/test_held_fill.py::test_a_cut_with_no_held_cell_runs_no_rife_and_is_the_same_bytes_whichever_model`); a cut whose held cells are filled, a repaired walk and a set's alignment get rife-v4.25's frames, and can take more or fewer poses. Run `sprite-gen rife install` once (an 830 MB zip, 45 MB kept, into a new directory beside the old install). A 20221029 binary on `PATH` holds no `rife-v4.25/` and now reads as RIFE not installed: install, or set `SPRITE_GEN_RIFE`. `SPRITE_GEN_RIFE_MODEL_NAME=rife-v4.6` runs the old model as it ran, its frames 3.14.0's to the byte. A `--between-cache` keys frames by model, so frames kept by 3.14.0 are not taken. With the torch backend, `sprite-gen rife install --backend torch` again; an executor and its host must name the same model.@@ -1164,12 +1186,12 @@ Restoration schemas remain `source-restoration-v5`, repair report `schema_versio- **Behavior change: a refused provider request is sent again only within the time limit of its call, and the waits count in that limit.** Previously a request its provider documents as not taken (a 429, an overload) was sent again after 8 s and 16 s, or after the answer's `retry-after` (at most 120 s), twice, whatever time the call had left, and the time limits did not count those waits: `SPRITE_GEN_GEN_TIMEOUT_SECONDS` bounded each send of an OpenAI or Grok image and of the OpenAI facing check on its own, the Grok facing check's 120 s each read, the clip's poll timeout counted from the send xAI accepted, and a Message Batch's status and results reads waited outside `--batch-wait`. A caller that stops the run at its own ceiling, set above those limits, could kill a request taken after two refusals and hear nothing from the engine. Now each limit counts from the first send and holds the waits: the image calls and the OpenAI facing check count `SPRITE_GEN_GEN_TIMEOUT_SECONDS`, the Grok facing check its 120 s, each of their sends reading only what is left of it; the clip its poll timeout (`SPRITE_GEN_VIDEO_TIMEOUT_SECONDS`; the POST itself is still not cut, its answer being the one way to the request id); a batch's reads `--batch-wait`. A wait that would reach the limit is not waited: the refusal ends the call as any refusal does, after one stderr line, `[gen] openai refused the request (429 rate_limit_exceeded); nothing was made — not asking again: the 16s wait would reach the time limit (12s left)`. The limit is read again after the wait, right before the send, as a sleep may wake later than it was asked to: one that woke at the limit or past it sends nothing either, and the refusal ends the call the same way (`… — not asking again: the time limit came during the 8s wait`). A clip's polls and downloads read their poll timeout the same way: a poll or download whose wait woke at it or past it is not sent, and the run ends unfinished on the last one as it came, where the one the transport found no time left to send was counted as a poll or download that got no answer (`timed out`). A realtime `pixel-draw` call has no time limit of its own and is unchanged.- **Tests** — `tests/gen/test_retry.py` (a request sent again only while its wait ends before the time limit; the answer's `retry-after` counted the same; a wait that ends at the limit not waited; a wait that woke at the limit or past it sends nothing, the limit read by one judgment, `too_late`, before the wait and right before the send; every direct provider call hands `retry` its limit; the Grok facing check and a Message Batch read whose wait woke past their limit send nothing), `tests/gen/test_openai_provider.py` and `tests/gen/test_grok_provider.py` (with 20 s, the second send waits only the 12 s left and the second 429 ends the call `sent 2 times`; with 8.01 s, an 8 s wait that woke 20 ms late sends nothing and the 429 ends the image call, or the OpenAI facing check, as it came), `tests/gen/test_video.py` (the poll timeout counts from the first send; a 429 whose next wait would reach it ends the run with its status, and so does one whose 8 s wait woke 20 ms past an 8.01 s timeout, with no second POST; a poll or a download whose wait woke past the timeout is not sent, and the run ends on the last one as it came), `tests/gen/test_pixel_draw.py` (each batch read is handed the end of `--batch-wait`). `tests/http_answer.py` is one offline HTTP answer the provider tests share, read whole or a chunk at a time under a deadline.-- **Behavior change: requests can pack sound without images.** Previously, a version 1 request required a nonempty `assets` list (refused with "assets must be a nonempty list"), and version 2 required at least one asset, image, tile, UI kit or icon (refused with "game pack request declares nothing to pack"), preventing games drawn in code from packing audio alone. In both versions, `assets` may now be empty or absent when sound is declared (see [docs/game-pack.md#sound-only-packs](docs/game-pack.md#sound-only-packs)). A sound-only request writes exactly `game-pack.json`, `audio-<id>.ogg`, `audio-<id>.m4a` and `sprite-gen-audio-v2.mjs` without atlas pages; its manifest sets `textures` to `[]` and `animations` to `{}` (version 2 also keeps empty `images`, `tiles` and `ui`), while audio entries, sound files and helper module bytes remain identical to packs with images. Requests declaring no assets, scene entries or sounds are refused in both versions with "game pack request declares nothing to pack: give it an asset, a scene entry or a sound" and write nothing. Packs with images (with or without sound) and packs without sound remain byte-for-byte unchanged, and repacking a sound-only request returns the same output. Tests: `tests/compose/test_game_pack_audio.py` (sound-only requests in versions 1 and 2 with `assets` empty or absent write only the manifest, sound files and helper; manifest matches image packs except for empty `textures` and `animations`; sound files and helper match bytes; repacking returns identical results; requests with neither images nor sound are refused without creating an output directory for version 1 and version 2). Synthetic fixtures only.+- **Behavior change: requests can pack sound without images.** Previously, a version 1 request required a nonempty `assets` list (refused with "assets must be a nonempty list"), and version 2 required at least one asset, image, tile, UI kit or icon (refused with "game pack request declares nothing to pack"), preventing games drawn in code from packing audio alone. In both versions, `assets` may now be empty or absent when sound is declared (see [docs/game-pack.md#sound-only-packs](https://github.com/aldegad/sprite-gen/blob/v2.45.0/docs/game-pack.md#sound-only-packs)). A sound-only request writes exactly `game-pack.json`, `audio-<id>.ogg`, `audio-<id>.m4a` and `sprite-gen-audio-v2.mjs` without atlas pages; its manifest sets `textures` to `[]` and `animations` to `{}` (version 2 also keeps empty `images`, `tiles` and `ui`), while audio entries, sound files and helper module bytes remain identical to packs with images. Requests declaring no assets, scene entries or sounds are refused in both versions with "game pack request declares nothing to pack: give it an asset, a scene entry or a sound" and write nothing. Packs with images (with or without sound) and packs without sound remain byte-for-byte unchanged, and repacking a sound-only request returns the same output. Tests: `tests/compose/test_game_pack_audio.py` (sound-only requests in versions 1 and 2 with `assets` empty or absent write only the manifest, sound files and helper; manifest matches image packs except for empty `textures` and `animations`; sound files and helper match bytes; repacking returns identical results; requests with neither images nor sound are refused without creating an output directory for version 1 and version 2). Synthetic fixtures only.- **New verb: `video-stop` cuts a walk or run that stops from the clip's own start played backwards.** Given the clip's keyed frames and a walk or run loop (`--frames-dir`, `--loop`), it writes a one-shot strip (`<name>.strip.png`), sidecar (`loop: false`, `hold_last: true`), GIF, WebP, and report (`<name>.stop.report.json`). The stop leaves the loop from the cell nearest the entry (`from_cell`), the first frame after the opening rest within `SAME_POSE` (0.35 steps) of a loop cell, and ends on the clip's first frame, the still as filmed. A seam past the jump line (1.4 steps, `--seam-max`) is refused by `video-stop` with exit code 1 and `status: "failed"` in the report, and so is another motion in the run-up between the rest and the entry, however short: a run-up frame back within `SAME_POSE` (0.35 steps) of a pose the clip had left by `TURN_BACK_AWAY` (one step) or more (the still, or the run-up's own), refused with "the run-up turns back — another motion, that the stop would play backwards", naming the three frames (`turn_back`, the nearest such comeback, is reported either way). A run-up longer than `RUN_UP_MAX_CYCLES` (1.5 cycles) — `source_cut.length` frames, overridden by `--run-up-max` — which plays strides unlike the loop's, is refused with "strides unlike the loop's, that the stop would play backwards"; `--run-up-max` bounds only that length and never lets another motion through. The seam refusal, the another-motion refusal and the run-up refusal can all be named in one message. Drift is taken out by laying the entry on its cell and the first frame on the loop's ground and mean coverage, moving frames between by a straight share of the difference per step; a run leaning away moves the still a few pixels, and drift not straight leaves a little of itself. Strips wider than 32,000 px are refused, `--speed 2` plays every other frame (still kept last), `--max-frames N` spaces frames evenly, and frames shown pass the ghost screen (`interpolation_quality`) as filmed. The pose thumbnails (`gait_fallback.poses`, 48 px cut about the feet) are now public, as the verb reads poses with them ([video-pipeline](docs/video-pipeline.md#8-a-walk-or-run-that-stops--video-stop)).- **Fix: the poses of one image row keep one size and stay on their anchor.** Each pose of a row was shrunk into its cell on its own, so a raised or extended weapon shrank that pose's body (PR #107 gave the row one shrink ratio). That ratio fitted the widest pose by its own width, and `fit_to_cell` then placed it with its `align_x` anchor (the legs, by default) on the cell's centre line: a weapon held far out crossed the cell and the pose was pushed back in, body and all, so the body jumped back in that frame alone (a greatsword thrust: 39 px in a 256 cell). The ratio is now one function, `fit_scale`, which keeps every pose inside the safe area where its anchor puts it; `fit_to_cell` takes it for a frame alone, the row takes it over every pose, and `qa/inspect` fits a row the same way instead of pose by pose. With `bbox-center` nothing changes. A weapon held far to one side now costs size in a square cell: give such a row a wider cell ([pixel-unfake](docs/pixel-unfake.md)). Test: `tests/frames/test_row_scale.py`.- **New: a motion plays as its request says — `--play loop|once-return|once-hold|lifetime` — and `video-set --motion` gives each state or item its own motion text.** A state's name used to fix its sentence, its end-frame pin, its cut and whether its strip loops, so every new motion (a punch, typing at a desk, a block, a tool swing) was a change to the engine. `video-set --play STATE=MODE` or `ITEM=MODE` and `video-prompt --play MODE` take the mode as a value of the request, and `video-set --motion STATE=TEXT` or `ITEM=TEXT` the caller's words in place of the state's sentence (an item's own value wins over its state's; a key that names neither, a key given twice or a mode the state cannot play is refused before any clip). A word the engine does not name is filmed under that name in that mode: a once-return is pinned to end on its first frame, asked for as one action that returns to the first pose, and cut whole by the new `video-loop --cycle once-return` (every frame, the last too, gated by the pin), its `strip.json` saying `loop: false`, `hold_last: false`, `returns: true` with the first pose in its first and last cells; a once-hold is cut at its held pose (`once`), the first settled pose whose drawing is not its first — a shield raised inside a body outline that keeps its size and floor is one, the first drawing come back, in place or slid sideways, is not — while the six terminal states keep their body-geometry screen (any other state cut `--cycle once` is screened by its drawing too); a lifetime is framed and filmed as an effect whatever its name; a loop asked for is searched as a loop (`periodic`) and never failed over to a single play. Named states are presets: without `--play` every state is filmed, prompted and cut as before, and an attack played once-return is the same prompt and the same pinned clip, cut whole and played once. `effect`, the six terminal states and the cyclic states refuse any other mode. `set.report.json` records each item's `play` (and `motion`); `video-prompt --json` records `play`. Not measured on a clip model: the sentences for a motion of your own ([video-pipeline](docs/video-pipeline.md#play-modes)).- **Tests** — `tests/video/test_play.py` (every named state given no mode is pinned, prompted and cut as before, and the same when its preset is named, save that a loop asked for is never failed over; a mode a state cannot play is refused; a once-return asked for pinned with its return sentence and cut whole, or searched where the source cannot pin; the attack played once-return is the attack's prompt; a named state played another way takes the mode's sentence; a once-hold with its end frame; a once-hold of your own ending on a new drawing inside the same body box cut at its held pose, the same clip as `cast` still refused by its body geometry, and one that comes back to its first drawing, in place or slid sideways, refused; a lifetime filmed as an effect whatever its name; a loop of your own; `video-set` modes and texts per state and per item, refused before any clip when a key or mode is wrong; a once-return that does not come back refused; a once-return cut subsampled with both ends kept and played once; the CLIs) and the once-return item filmed end to end in `tests/video/test_clip_prompt.py`, its strip's first and last cells the first pose. Synthetic fixtures only.-- **Behavior change: the UI kit cut reads the drawing with one exact judgment instead of a centring heuristic.** Previously, each part went to the box that holds its centroid, with every box widened by half the gap. When that left a box empty, the layout was fitted to the drawing (least squares of box centres to the centres of what the boxes held, then assign again, at most 8 rounds) and kept when it left fewer required boxes empty, or as many and fewer boxes in all, reported as `layout_fit`. The only refusal of the cut was an empty frame. With several band elements missing on a drifted sheet, a drawn element could be cut under a neighbour's name, a drawn part named missing, or an undrawn element present; a drawing that fit the layout in two ways was cut silently under one of them; and a fit dragged by a small element placed off its box's centre gave wrong readings. The cut is the one reading within 1 px of the least cost, found by one exact search over the drifts the cut considers (a scale from 0.875 to 1.125 and an offset of at most 120 px at 1024), and every refusal comes from that one result ([ui-kit](docs/ui-kit.md#reading-the-drawing)). Every drawn element is cut under its own name, or the sheet is refused. A drawing that fits the layout in two ways is refused, naming both readings. New refusals: drifted further, ambiguous, off-centre, and off the layout. A sheet drawn on its guide is cut exactly as before, report bytes included. A sheet whose every part lies at least 1 px inside its box under some drift within the accepted range (along each axis a scale from 0.9 to 1.1 and an offset of at most 96 px at 1024), with all seven frames drawn, is cut exactly as drawn or refused as fitting the layout in two ways, never refused for another reason. A sheet with stray marks (parts in no box under the drift it was drawn with) is outside it.+- **Behavior change: the UI kit cut reads the drawing with one exact judgment instead of a centring heuristic.** Previously, each part went to the box that holds its centroid, with every box widened by half the gap. When that left a box empty, the layout was fitted to the drawing (least squares of box centres to the centres of what the boxes held, then assign again, at most 8 rounds) and kept when it left fewer required boxes empty, or as many and fewer boxes in all, reported as `layout_fit`. The only refusal of the cut was an empty frame. With several band elements missing on a drifted sheet, a drawn element could be cut under a neighbour's name, a drawn part named missing, or an undrawn element present; a drawing that fit the layout in two ways was cut silently under one of them; and a fit dragged by a small element placed off its box's centre gave wrong readings. The cut is the one reading within 1 px of the least cost, found by one exact search over the drifts the cut considers (a scale from 0.875 to 1.125 and an offset of at most 120 px at 1024), and every refusal comes from that one result ([ui-kit](https://github.com/aldegad/sprite-gen/blob/v2.45.0/docs/ui-kit.md#reading-the-drawing)). Every drawn element is cut under its own name, or the sheet is refused. A drawing that fits the layout in two ways is refused, naming both readings. New refusals: drifted further, ambiguous, off-centre, and off the layout. A sheet drawn on its guide is cut exactly as before, report bytes included. A sheet whose every part lies at least 1 px inside its box under some drift within the accepted range (along each axis a scale from 0.9 to 1.1 and an offset of at most 96 px at 1024), with all seven frames drawn, is cut exactly as drawn or refused as fitting the layout in two ways, never refused for another reason. A sheet with stray marks (parts in no box under the drift it was drawn with) is outside it.- **Tests** — synthetic sheets cover the change: the two-way ambiguous sheet (512 × 768 px, seven 20 × 8 px frames, one dot on `pip_on` and squeezed `pip_off`) with an 18 px and a 60 px dot, refused by `split_ui_kit` and the CLI; the control sheet cut as `pip_off`; 512 sheets of small drawings and 256 sheets of full-size frames with small band drawings cut as drawn or refused as ambiguous, with three sheets previously refused as drifted now cut as drawn; each of the 256 sets of missing band elements under random accepted drifts; squeezes from the top by 0.90 to 0.99; a 17-sheet counterexample search; sheets refused as drifted further (20 % shorter), off-centre (dot in the gap), and required (each frame left out); a 2:3 sheet drawn on its guide with a mark 4 px wide and 20 px tall centred in the gap between the boxes of the two dots (`pip_on` above, `pip_off` below), refused as ambiguous (`pip_on, pip_off`); and 4 px scattered squares proved off the layout within 10 seconds. A square sheet and a 2:3 sheet drawn on their guide are cut byte for byte as before, with no `layout_fit`.- **Fix: the test suite runs on Windows.** `pyproject.toml` named pytest-timeout's `signal` method, and Windows has no SIGALRM, so pytest stopped with an internal error before its first test unless `-o timeout_method=thread` was given. The method is now left to pytest-timeout, which takes `signal` where SIGALRM exists (Linux, macOS: unchanged) and `thread` on Windows. Test: `tests/packaging/test_project_metadata.py`. `tests/video/test_one_step_cut.py` skips where img2webp is missing, as the other loop tests do, instead of failing all twelve of its tests.- **Fix: `sprite-gen prepare --request` keeps the request's `style`.** The subcommand declared its own copy of prepare's options, with `--style` defaulting to the default style sentence and `--cell-size` to 256, so a flag nobody gave counted as given: the request's `style` was replaced by the default sentence under a note that `--style, --cell-size` were given both ways (`scripts/prepare_sprite_run.py` and `prepare.run` were right). The subcommand now takes prepare's own declaration (`prepare.add_arguments`), which also gives it `--directions` and `--mirror`, missing until now. A request with no style and no cell still gets the default sentence and 256. Test: `tests/gen/test_flags_over_spec.py` (through `sprite-gen prepare`: a request alone keeps its style and cell with no note, a given `--style` wins and says so, the subcommand takes every option prepare declares).@@ -1192,14 +1214,14 @@ Restoration schemas remain `source-restoration-v5`, repair report `schema_versio- **Fix: a `pixel-draw` answer that writes its block more than once is read from the last block that reads whole.** An answer sometimes writes a first try — the palette and `END` with no frame — then "Corrected:" and the whole block (seen 2026-10-15 on a 16 px icon); G1 read the first block, found the frame missing and drew the candidate again. Now every block is read and the last one that reads whole is the answer (when none does, the last whose rows the row repair can fix), recorded in G1's `recovered` as `block_many` with which block was read. An answer of one block is read as before.- **Tests** — `tests/gen/test_pixel_grid.py` (several blocks read from the last whole one, or the last with rows to repair; one block as before) and an answer of two blocks drawn once in `tests/gen/test_pixel_draw.py`.- **New: alpha haze cleanup for transparent sheets (`frames.alpha_floor.clear_haze`).** Pixels at or above a floor, and faint pixels within a few pixels of them (an object's anti-aliased edge), are kept byte for byte; every other faint pixel becomes fully transparent. The report measures the haze share before and after and counts the solid and edge pixels that changed (`0`). Used by `ui-kit` (on by default) and `slice-sheet --alpha-floor N` (off by default; writes `<prefix>alpha-cleanup.json`). `slice-sheet --chroma-key none` cuts a sheet that is already transparent on its own alpha ([sheet-slicing](docs/sheet-slicing.md#transparent-sheets)).-- **New verb: `ui-kit` splits a game UI kit sheet into nine-slice elements.** `gen --layout-guide ui-kit` attaches a fixed square layout (panel, button, pressed button, card frame, HP and XP bar frames, timer badge) and asks for each element in its box. `ui-kit --sheet uikit.png --out-dir ui/` clears the haze, assigns parts to boxes by centroid, and writes each element's PNG and `ui-kit.json` (or `--report PATH`, which must end in `.json`; each element's `file` is its PNG's path from the report's directory, so a report written outside `--out-dir` still finds its elements): its rectangle, its stretch (`xy`, `x` for the bars, `none` for the badge), nine-slice insets measured so that every corner ornament and end cap lies in a fixed slice, and the content padding (a bar frame's track, a panel's text area). An ornament in the middle of an edge, an empty box or a stray part is reported or refused ([ui-kit](docs/ui-kit.md)). `--layout-guide` alone is still the one-slot figure guide.-- **New: `game-pack` request and manifest version 2 with `images`, `tiles` and `ui`.** Single images (props) are atlas frames with an anchor and an optional footprint (`"base"` measures where the image meets the ground); tiles are their own PNG and WebP files with their stored and on-screen sizes; `ui.kit` reads a `ui-kit` report into nine-slice entries (frame, size, stretch, insets, padding) and `ui.icons` adds fixed icons. Every number is in pixels of the stored image. A version 1 request is packed byte for byte as before, and a version 1 request naming the new sections is refused ([game-pack](docs/game-pack.md#version-2-images-tiles-and-ui)).+- **New verb: `ui-kit` splits a game UI kit sheet into nine-slice elements.** `gen --layout-guide ui-kit` attaches a fixed square layout (panel, button, pressed button, card frame, HP and XP bar frames, timer badge) and asks for each element in its box. `ui-kit --sheet uikit.png --out-dir ui/` clears the haze, assigns parts to boxes by centroid, and writes each element's PNG and `ui-kit.json` (or `--report PATH`, which must end in `.json`; each element's `file` is its PNG's path from the report's directory, so a report written outside `--out-dir` still finds its elements): its rectangle, its stretch (`xy`, `x` for the bars, `none` for the badge), nine-slice insets measured so that every corner ornament and end cap lies in a fixed slice, and the content padding (a bar frame's track, a panel's text area). An ornament in the middle of an edge, an empty box or a stray part is reported or refused ([ui-kit](https://github.com/aldegad/sprite-gen/blob/v2.45.0/docs/ui-kit.md)). `--layout-guide` alone is still the one-slot figure guide.+- **New: `game-pack` request and manifest version 2 with `images`, `tiles` and `ui`.** Single images (props) are atlas frames with an anchor and an optional footprint (`"base"` measures where the image meets the ground); tiles are their own PNG and WebP files with their stored and on-screen sizes; `ui.kit` reads a `ui-kit` report into nine-slice entries (frame, size, stretch, insets, padding) and `ui.icons` adds fixed icons. Every number is in pixels of the stored image. A version 1 request is packed byte for byte as before, and a version 1 request naming the new sections is refused ([game-pack](https://github.com/aldegad/sprite-gen/blob/v2.45.0/docs/game-pack.md#version-2-images-tiles-and-ui)).- **New: `slice-sheet --scale sheet` keeps the sizes a sheet was drawn at, and `--fit contain` keeps every cut whole.** The default gives each cell's main subject the target height on its own, so the props of one sheet came out the same height, and lets the canvas cut whatever that scale puts past its edge, so a subject wider than the canvas lost its sides. `--scale sheet` takes one factor for the whole sheet (the tallest main subject reaches `--target-height`), so a prop drawn twice as tall stays twice as tall. `--fit contain` lowers the factor until the whole cut fits the canvas, with the main subject still centred on its base; with `--scale sheet` the sheet takes the smallest factor any cell fits at. Every cell of a sheet keeps one canvas size, so a game pack that gives the cells one `display` height keeps their sizes too ([sheet-slicing](docs/sheet-slicing.md#props-and-icons-sheet-scale-and-contain-fit)).- **New: `slice-sheet` writes `<prefix>slice-sheet.json`.** It names the scale and fit, the sheet's factor and where it came from, and per cell the factor, the main subject's size on the sheet and on the canvas, the cut's box on the canvas, the `anchor` (the centre of the main subject's base, ready for a game pack's `images[].anchor`) and `clipped_px`, the pixels the canvas cut ([report](docs/sheet-slicing.md#report)). A run also prints a line for each cell the canvas cut. The PNGs of a default run are unchanged byte for byte; a sheet with an empty cell now fails before any cell is written, where it used to write the cells before it.-- **New: a 2:3 UI kit sheet holds the whole kit: bar fills, an item slot, a counter plate, on and off dots and a joystick.** `gen --layout-guide ui-kit --aspect-ratio 2:3` draws the square layout's seven frames at the same places and, in a band below them, `hp_bar_fill` and `xp_bar_fill` (`x`), `slot` and `badge` (`xy`), `pip_on`, `pip_off`, `joystick_base` and `joystick_knob` (`none`, so round parts keep their proportions; the guide draws them as circles, and a cut with filled corners, a round part drawn on a square plate, makes the report `needs-review`). `ui-kit` picks the layout from the sheet's shape, so a square sheet is cut, measured and packed exactly as before. Padding is measured only for elements that hold content; fills, dots and joystick parts get `0`. Each fill's report entry has `inside`: its bar frame, that frame's content rectangle and the factor that makes the fill as tall as it, and the report is `needs-review` when the fill's ends would overflow it. `game-pack` (still version 2) stores each fill at exactly its frame's content rectangle, ends kept and middle columns repeated or dropped, with `inside` in its entry, and refuses a fill whose frame is missing or whose ends do not fit ([ui-kit](docs/ui-kit.md#fills), [game-pack](docs/game-pack.md#version-2-manifest)).-- **Behavior change: a 2:3 UI kit sheet that leaves a band element out still makes a kit, without it.** The seven frames (`panel`, `button`, `button_pressed`, `card`, `hp_bar_frame`, `xp_bar_frame`, `timer_badge`) are required: an empty frame box still fails `ui-kit` with `<element>: its box holds no element; generate the sheet again`, now naming every empty frame box at once (`panel, card: their boxes hold no element; …`). The eight band elements (the fills, the slot, the badge, the dots and the joystick parts) are optional: an empty band box leaves that element out. It gets no PNG and no `elements` entry, the report names it under `missing` (every 2:3 report has `missing`, `[]` when nothing is missing), and the command's line ends with `; missing, left out of the kit: …`. `status` stays about the elements that are there. `game-pack` is unchanged: it packs the elements a report has, so a missing element has no `ui.nine_slice` entry and a game falls back for exactly that part. A square sheet's report, elements and packs are unchanged byte for byte, and its report has no `missing` ([ui-kit](docs/ui-kit.md#missing-elements)).-- **Behavior change: `ui-kit` writes a kit whole into a new directory and refuses one that holds anything.** `--out-dir` must not exist yet or be an empty directory. One that holds an earlier kit or any other file is refused with its name and what it holds, and left as it was, where a rerun used to rewrite the kit in place one file at a time and a failure partway left two kits mixed under one report. The kit is written into a hidden directory beside `--out-dir` and renamed into place in one step, so a run that fails or is killed at any step leaves either nothing or the whole kit, and of two runs into one new `--out-dir` the second is refused. A `--report` outside `--out-dir` must be a new path: it takes its name after the rename, in a step that fails when another run took the name first. One step publishes the kit, the rename or, with the report outside, the report's own step: a run that fails or is stopped with Ctrl-C before it takes everything it made back out, and one stopped after it leaves the whole kit and its report, so a report never names a PNG that is not there. A killed run can leave its hidden directory (`.<out-dir>.ui-kit-*`) or report temp beside them, and, with the report outside, the whole kit without its report. A run that is interrupted again while it is removing what it made (for example, a second Ctrl-C during that clean-up) cannot finish the clean-up either: it can leave the same things a killed run leaves, and never leaves part of a kit under `--out-dir`'s own name: `--out-dir` holds nothing or the whole kit ([ui-kit](docs/ui-kit.md#split-the-sheet)).-- **Fix: a UI kit sheet drawn a few percent shorter than its guide is cut instead of refused.** An image model may draw the layout a few percent shorter than the guide; the lower an element, the farther it sits above its box, until its centroid lies in the widened box above its own. That box held two elements and the element's own box none, so `ui-kit` refused the sheet with `<element>: its box holds no element` although every element was drawn. When a box is left empty, `ui-kit` now fits the layout to the drawing (a scale and an offset along x and y, least squares from the box centres to what the boxes hold, repeated until the assignment comes out the same) and assigns the parts again. The fit is kept when it leaves fewer required boxes empty, or as many and fewer boxes in all. A kept fit is in the report as `layout_fit`, and each `box` is then the fitted box. A sheet whose every box holds its element is cut exactly as before ([ui-kit](docs/ui-kit.md#a-drawing-that-drifted-from-the-layout)).+- **New: a 2:3 UI kit sheet holds the whole kit: bar fills, an item slot, a counter plate, on and off dots and a joystick.** `gen --layout-guide ui-kit --aspect-ratio 2:3` draws the square layout's seven frames at the same places and, in a band below them, `hp_bar_fill` and `xp_bar_fill` (`x`), `slot` and `badge` (`xy`), `pip_on`, `pip_off`, `joystick_base` and `joystick_knob` (`none`, so round parts keep their proportions; the guide draws them as circles, and a cut with filled corners, a round part drawn on a square plate, makes the report `needs-review`). `ui-kit` picks the layout from the sheet's shape, so a square sheet is cut, measured and packed exactly as before. Padding is measured only for elements that hold content; fills, dots and joystick parts get `0`. Each fill's report entry has `inside`: its bar frame, that frame's content rectangle and the factor that makes the fill as tall as it, and the report is `needs-review` when the fill's ends would overflow it. `game-pack` (still version 2) stores each fill at exactly its frame's content rectangle, ends kept and middle columns repeated or dropped, with `inside` in its entry, and refuses a fill whose frame is missing or whose ends do not fit ([ui-kit](https://github.com/aldegad/sprite-gen/blob/v2.45.0/docs/ui-kit.md#fills), [game-pack](https://github.com/aldegad/sprite-gen/blob/v2.45.0/docs/game-pack.md#version-2-manifest)).+- **Behavior change: a 2:3 UI kit sheet that leaves a band element out still makes a kit, without it.** The seven frames (`panel`, `button`, `button_pressed`, `card`, `hp_bar_frame`, `xp_bar_frame`, `timer_badge`) are required: an empty frame box still fails `ui-kit` with `<element>: its box holds no element; generate the sheet again`, now naming every empty frame box at once (`panel, card: their boxes hold no element; …`). The eight band elements (the fills, the slot, the badge, the dots and the joystick parts) are optional: an empty band box leaves that element out. It gets no PNG and no `elements` entry, the report names it under `missing` (every 2:3 report has `missing`, `[]` when nothing is missing), and the command's line ends with `; missing, left out of the kit: …`. `status` stays about the elements that are there. `game-pack` is unchanged: it packs the elements a report has, so a missing element has no `ui.nine_slice` entry and a game falls back for exactly that part. A square sheet's report, elements and packs are unchanged byte for byte, and its report has no `missing` ([ui-kit](https://github.com/aldegad/sprite-gen/blob/v2.45.0/docs/ui-kit.md#missing-elements)).+- **Behavior change: `ui-kit` writes a kit whole into a new directory and refuses one that holds anything.** `--out-dir` must not exist yet or be an empty directory. One that holds an earlier kit or any other file is refused with its name and what it holds, and left as it was, where a rerun used to rewrite the kit in place one file at a time and a failure partway left two kits mixed under one report. The kit is written into a hidden directory beside `--out-dir` and renamed into place in one step, so a run that fails or is killed at any step leaves either nothing or the whole kit, and of two runs into one new `--out-dir` the second is refused. A `--report` outside `--out-dir` must be a new path: it takes its name after the rename, in a step that fails when another run took the name first. One step publishes the kit, the rename or, with the report outside, the report's own step: a run that fails or is stopped with Ctrl-C before it takes everything it made back out, and one stopped after it leaves the whole kit and its report, so a report never names a PNG that is not there. A killed run can leave its hidden directory (`.<out-dir>.ui-kit-*`) or report temp beside them, and, with the report outside, the whole kit without its report. A run that is interrupted again while it is removing what it made (for example, a second Ctrl-C during that clean-up) cannot finish the clean-up either: it can leave the same things a killed run leaves, and never leaves part of a kit under `--out-dir`'s own name: `--out-dir` holds nothing or the whole kit ([ui-kit](https://github.com/aldegad/sprite-gen/blob/v2.45.0/docs/ui-kit.md#split-the-sheet)).+- **Fix: a UI kit sheet drawn a few percent shorter than its guide is cut instead of refused.** An image model may draw the layout a few percent shorter than the guide; the lower an element, the farther it sits above its box, until its centroid lies in the widened box above its own. That box held two elements and the element's own box none, so `ui-kit` refused the sheet with `<element>: its box holds no element` although every element was drawn. When a box is left empty, `ui-kit` now fits the layout to the drawing (a scale and an offset along x and y, least squares from the box centres to what the boxes hold, repeated until the assignment comes out the same) and assigns the parts again. The fit is kept when it leaves fewer required boxes empty, or as many and fewer boxes in all. A kept fit is in the report as `layout_fit`, and each `box` is then the fitted box. A sheet whose every box holds its element is cut exactly as before ([ui-kit](https://github.com/aldegad/sprite-gen/blob/v2.45.0/docs/ui-kit.md#a-drawing-that-drifted-from-the-layout)).- **Behavior change: a key background painted as a transparency checkerboard is refused before keying.** Asked for a magenta or green key, a model sometimes paints the grey and white checkerboard editors show behind transparent pixels. The matte read the checkerboard as the key and keyed nearly the whole image away, so a UI kit sheet had nothing left to cut. Every chroma key in `gen` now checks the raw first (`chroma.painted_checkerboard`: two greys alternating in squares of one size along a horizontal edge and a vertical edge), and fails with its own reason, `chroma: the background is a painted transparency checkerboard (… px squares along the … edges), not the magenta key the image was asked for; keying it would erase the image — generate it again`, publishing nothing. A ref run whose raw is a drawn checkerboard was keyed before; it is refused now. Key backgrounds, plain or striped grey backgrounds, and a checkered subject inside a key background are not refused ([gen](docs/gen.md#transparent-output--strategy-per-provider)).- **Tests** — `tests/frames/test_ui_kit.py` (the frames required and the band optional; an empty band box, several, or the whole band leaves those elements out of the report, the PNGs and the pack; an empty frame box, alone, several at once, or on a squeezed sheet (each frame in turn), refuses the sheet by that frame's name; a kit is written into a new or empty directory, and one that holds a kit, any other file or a hidden one, or a file at its path, is refused and left byte for byte as it was; one failure, interrupt or kill injected just before or just after each filesystem step of the publish, with the report in and outside `--out-dir` and `--out-dir` absent or empty (and removed first, as on Windows), leaves nothing before the step that publishes the kit and the whole kit from it on; an interrupt of any kind (SIGINT, SIGTERM through a handler that exits, any other exception) at each step from the rename on, with no function replaced, the same; a sweep in which an interrupt of each kind (SIGINT, SIGTERM through a handler that exits, any other exception) is raised once per run at each line, and at each instruction, of the publish, with the report in and outside `--out-dir` and `--out-dir` absent, empty, or empty and removed first, and every run ends with that interrupt and leaves either the start, with nothing hidden, or the whole kit; a run whose `--out-dir` or outside report another run reaches first is refused and removes what it made; a 2:3 sheet drawn 7 % shorter than its guide, which the layout's own boxes refuse, is fitted and every element is cut whole inside its fitted box; a square report has no `missing`), `tests/gen/test_painted_checkerboard.py` (checkerboards of 8, 12 and 32 px squares at any phase and greys, with elements across two edges, are found; key, plain grey, gradient and striped backgrounds and a chessboard inside a key background are not; `key_transparent` and a `--layout-guide ui-kit` run refuse a checkerboard before the matte runs and publish nothing), and the drawn-checkerboard ref run in `tests/gen/test_gen.py`, which now refuses.- **Tests** — `tests/background/test_tile_xy.py` (an exact doubly periodic crop, a join that stays visible on one axis names that axis, the cyclic seam), `tests/frames/test_alpha_floor.py` (a haze ring cleared, thin strokes and their anti-aliased edges kept), `tests/frames/test_ui_kit.py` (a synthetic sheet on the layout: insets to the pixel over corner ornaments, a long flourish, a bar's end gem and cap; badge padding inside its ring; a packed kit at four scales keeps ornament fringes out of the stretched middle; a report in, beside, below or above `--out-dir` names the PNGs from its own directory and packs the same bytes), `tests/frames/test_slice_sheet_transparent.py`, `tests/compose/test_game_pack_v2.py` (the manifest field by field, refusals, and a version 1 manifest and page pixels frozen from 2.44.0), `tests/compose/test_game_pack_audio.py` (a version 1 pack with sound keeps its file list, manifest bytes and page pixels from 2.44.0; a version 2 pack with sound adds only its tile files) the `--layout-guide ui-kit` cases in `tests/gen/test_layout_guide.py` (square and 2:3, any other ratio refused), the 2:3 sheet in `tests/frames/test_ui_kit.py` (every element cut from a synthetic sheet; fills fit their frame's content area in the report and, packed at three scales, to the pixel with their ends unchanged; dots and joystick parts never stretch and one drawn on a square plate is flagged; slot and plate insets to the pixel; a square sheet's report, element pixels and packs frozen from before the 2:3 sheet) and the fill cases in `tests/compose/test_game_pack_v2.py`, and `tests/frames/test_slice_sheet_scale.py` (synthetic sheets: drawn heights kept within a pixel with `--scale sheet`, after the alpha cleanup too; a 2:1 subject whole on a square canvas with `--fit contain` while the default still cuts it and says so; one factor every cut fits; sliced cells packed as game-pack `images` keep one size and stand on the reported anchor; refusals).diff --git a/README.es.md b/README.es.mdindex 7587e02..82a40ef 100644--- a/README.es.md+++ b/README.es.md@@ -50,7 +50,7 @@ flowchart LRendsubgraph C["C · utilidades"]direction LR- c1[cutout] ~~~ c2[slice-sheet] ~~~ c4[ui-kit] ~~~ c3[unpack-atlas]+ c1[cutout] ~~~ c2[slice-sheet] ~~~ c3[unpack-atlas]endsubgraph D["D · posprocesado"]direction LRdiff --git a/README.fr.md b/README.fr.mdindex c1754c5..9eb9ef0 100644--- a/README.fr.md+++ b/README.fr.md@@ -50,7 +50,7 @@ flowchart LRendsubgraph C["C · utilitaires"]direction LR- c1[cutout] ~~~ c2[slice-sheet] ~~~ c4[ui-kit] ~~~ c3[unpack-atlas]+ c1[cutout] ~~~ c2[slice-sheet] ~~~ c3[unpack-atlas]endsubgraph D["D · post-traitement"]direction LRdiff --git a/README.ja.md b/README.ja.mdindex c99dac0..46b17c1 100644--- a/README.ja.md+++ b/README.ja.md@@ -50,7 +50,7 @@ flowchart LRendsubgraph C["C · ユーティリティ"]direction LR- c1[cutout] ~~~ c2[slice-sheet] ~~~ c4[ui-kit] ~~~ c3[unpack-atlas]+ c1[cutout] ~~~ c2[slice-sheet] ~~~ c3[unpack-atlas]endsubgraph D["D · ポストプロセス"]direction LRdiff --git a/README.ko.md b/README.ko.mdindex accd57f..a2e3cff 100644--- a/README.ko.md+++ b/README.ko.md@@ -56,7 +56,7 @@ flowchart LRendsubgraph C["C · 유틸리티"]direction LR- c1[cutout] ~~~ c2[slice-sheet] ~~~ c4[ui-kit] ~~~ c3[unpack-atlas]+ c1[cutout] ~~~ c2[slice-sheet] ~~~ c3[unpack-atlas]endsubgraph D["D · 후처리"]direction LRdiff --git a/README.md b/README.mdindex 7024d7e..1372cbb 100644--- a/README.md+++ b/README.md@@ -63,7 +63,7 @@ flowchart LRendsubgraph C["C · utilities"]direction LR- c1[cutout] ~~~ c2[slice-sheet] ~~~ c4[ui-kit] ~~~ c3[unpack-atlas]+ c1[cutout] ~~~ c2[slice-sheet] ~~~ c3[unpack-atlas]endsubgraph D["D · post-processing"]direction LR@@ -138,7 +138,6 @@ A title logo whose letters the model draws freely? `sprite-gen logo --provider c```bashsprite-gen cutout icon.png --white-check # white/ivory → matte, magenta/green → chroma enginesprite-gen slice-sheet --sheet sheet.png --chroma-key magenta --grid 3x2 # multi-figure sheet → per-cell cuts-sprite-gen ui-kit --sheet uikit.png --out-dir ui/ # UI kit sheet (gen --layout-guide ui-kit) → nine-slice elementssprite-gen unpack-atlas --atlas sheet.png # finished atlas → curator-ready run (or --pngs-dir folder/)```@@ -154,7 +153,6 @@ sprite-gen export-aseprite --run-dir <run> # Aseprite JSON```bashsprite-gen background-tile --source background.png --period 512 --overlap 32 --out tile.png-sprite-gen background-tile --source ground.png --axis xy --period 960 --overlap 64 --out ground-tile.png # both wayssprite-gen shadow --source walk.strip.json --out-dir shadows/sprite-gen inspect-motion --source walk.strip.json --out motion.json# Only with known same-foot contact and an isolated foot ROI:@@ -185,7 +183,6 @@ Image generation is part of this engine (`sprite_gen.gen`, providers `codex` and| `gen --provider grok`, `video*` | the `grok` CLI login | `XAI_API_KEY` | [gen](docs/gen.md#direct-grok-calls-and-authentication), [video](docs/video.md) || `pixel-draw` | the `claude` (Claude Code) subscription login | `ANTHROPIC_API_KEY` | [pixel-draw](docs/pixel-draw.md#which-credential-a-call-runs-on) || `gen --provider openai` | — | `OPENAI_API_KEY`, only when you chose it | [gen](docs/gen.md#subscription-first--openai-runs-only-when-you-chose-it) |-| `sound` | — | `ELEVENLABS_API_KEY` | [sound](docs/sound.md) |A call on an API key is billed per call and says so on stderr before the request leaves, also inside `gen-set` and `video-set`. A call that names no provider runs on codex; when codex cannot run (not signed in, or its usage used up) it stops and asks (exit 75) — or runs what you chose for that with `sprite-gen defaults save --codex-unavailable grok|openai` ([gen](docs/gen.md#when-codex-cannot-run--ask-or-what-you-chose)). `logo` makes its images and its text checks through `gen`'s providers, on the same credentials.diff --git a/README.zh-Hans.md b/README.zh-Hans.mdindex 9d2c2ab..63085a0 100644--- a/README.zh-Hans.md+++ b/README.zh-Hans.md@@ -50,7 +50,7 @@ flowchart LRendsubgraph C["C · 实用工具"]direction LR- c1[cutout] ~~~ c2[slice-sheet] ~~~ c4[ui-kit] ~~~ c3[unpack-atlas]+ c1[cutout] ~~~ c2[slice-sheet] ~~~ c3[unpack-atlas]endsubgraph D["D · 后期处理"]direction LRdiff --git a/SKILL.md b/SKILL.mdindex e7123bc..5bec389 100644--- a/SKILL.md+++ b/SKILL.md@@ -115,14 +115,11 @@ front-facing observations also remain unchanged. Mirroring does not preserve lef| Idle breathing as a post-processing layer (the Breathe layer): pixel (default, pixel art) or smooth (large illustrations, video frames: head fixed, chest breathes, shoulders follow; facing values for a turned body); smooth can choose a beat that misses the hands with `--avoid-region`, and a way in or out of a loop carries on its breath with `--loop-cells`, `--start-cell` and `--reference`; pixel can breathe round from the chest with the arms moving sideways (`--chest-round`, `--arms-x`), cells held still (`--hold-mask`), what the arms hold moving whole with them (`--props-mask`), what the arms hold behind the body (a shield hung at the back) moves the same way with the body staying in front (`--props-behind-mask`), and pieces painted one colour move together (`--props-groups colour`, so a sword's reflection follows the sword) | curation sidecar, baked by compose; or `sprite-gen breathe <frames> <out>` on a folder of loop frames | [breathing](docs/breathing.md) || Engine exports | `export-aseprite`, `export-pngs` | [engine-export](docs/engine-export.md) || Background recipe or repeating tile | existing `gen` / `cutout`, then optional `background-tile` | [asset-tools](docs/asset-tools.md#background-recipe) |-| Ground tile that repeats both ways | `gen` (opaque), then `background-tile --axis xy` | [asset-tools](docs/asset-tools.md#both-axes-a-ground-tile) |-| Game UI kit: panel, buttons, card, HP/XP bar frames and fills, timer badge, item slot, counter plate, on/off dots, joystick base and knob as sliced elements | `gen --transparent --aspect-ratio 2:3 --layout-guide ui-kit` (`1:1`: the seven frames alone), then `ui-kit`; the seven frames are required, and a band element whose box is empty is left out and named under `missing` | [ui-kit](docs/ui-kit.md#missing-elements) || Props or icons on a transparent sheet | `slice-sheet --chroma-key none --alpha-floor 64`, props with `--scale sheet --fit contain`, icons with `--fit contain` | [sheet-slicing](docs/sheet-slicing.md#props-and-icons-sheet-scale-and-contain-fit) |-| Painted props, a ground tile and a UI kit in a game pack | `game-pack` request version 2 (`images`, `tiles`, `ui`) | [game-pack](docs/game-pack.md#version-2-images-tiles-and-ui) || Standalone projected shadow | `shadow` | [asset-tools](docs/asset-tools.md#projected-shadows) || Duplicate poses, foot contact and stride measurement | `inspect-motion` | [asset-tools](docs/asset-tools.md#motion-and-contact-evidence) || Optional scene placement, lighting, camera and render | `scene-render`, `scene-inspect` | [scene](docs/scene.md) |-| What the engine can do, for an agent or a tool to read once: every verb and argument, the providers each may call and be billed by (one JSON line, a quarter of every `--help`); a sandbox that reaches the providers through a relay: `SPRITE_GEN_<PROVIDER>_BASE_URL` (`OPENAI`, `XAI`, `ANTHROPIC`, `ELEVENLABS`) moves a provider's calls and the files it hands back, `SPRITE_GEN_LOGINS=off` runs every call on its API key | `capabilities` | [capabilities](docs/capabilities.md), [provider addresses](docs/gen.md#provider-addresses) |+| What the engine can do, for an agent or a tool to read once: every verb and argument, the providers each may call and be billed by (one JSON line, a quarter of every `--help`); a sandbox that reaches the providers through a relay: `SPRITE_GEN_<PROVIDER>_BASE_URL` (`OPENAI`, `XAI`, `ANTHROPIC`) moves a provider's calls and the files it hands back, `SPRITE_GEN_LOGINS=off` runs every call on its API key | `capabilities` | [capabilities](docs/capabilities.md), [provider addresses](docs/gen.md#provider-addresses) || Defaults | `defaults show`, `defaults save` (`--codex-unavailable ask\|grok\|openai`: what to do when codex cannot run), `defaults clear` | [user-workflow](docs/user-workflow.md#one-settings-owner) |Say a thing once: what an option says, leave out of the prompt. `--direction`, `--facing`, `--handed`, the key background and `video --direction side` each add their own sentence after your text, in one place. Your prompt carries the subject, its design and its pose. Text that says the opposite of an option ("facing left" with `--facing right`, the item on the other wrist) is sent as written with a warning (`extra.prompt_notes`, `video-prompt`'s `warnings`): fix the prompt, do not send it — [prompt-assembly](docs/prompt-assembly.md).diff --git a/docs/README.md b/docs/README.mdindex b122b74..7e2f1b5 100644--- a/docs/README.md+++ b/docs/README.md@@ -22,7 +22,7 @@ flowchart LRendsubgraph C["C · utilities"]direction LR- c1[cutout] ~~~ c2[slice-sheet] ~~~ c4[ui-kit] ~~~ c3[unpack-atlas]+ c1[cutout] ~~~ c2[slice-sheet] ~~~ c3[unpack-atlas]endsubgraph D["D · post-processing"]direction LR@@ -41,7 +41,7 @@ flowchart LR|---|---|---|| **A · atlas rows** — one still becomes a runtime sprite sheet | [run-contract.md](run-contract.md) | `prepare` → `gen` / `gen-set` → `extract` → `compose-atlas`; optional `curation` and recompose || **B · video → loop** — one still becomes transparent motion loops | [video-pipeline.md](video-pipeline.md) | `video-canvas` → `video` (or `video-prompt` and a video MCP on your agent) → `video-frames` → `video-loop`, `video-set`, `video-cycle-align`, `video-sway`, the Sway layer (`video-sway-inspect` shows every cell of it and moves nothing; old names `video-follow`, `video-follow-inspect`), `video-set-sheet` (a set's directions on one sheet, on one ground line), `video-stop` (a walk or run that stops, from the clip's own start played backwards); `handed-check` for an item on one side; obstacle plate painted and erased (`--prop-plate`) |-| **C · utilities** — imported images in, clean cuts out | [sheet-slicing.md](sheet-slicing.md) | `cutout`, `slice-sheet`, `ui-kit`, `unpack-atlas` |+| **C · utilities** — imported images in, clean cuts out | [sheet-slicing.md](sheet-slicing.md) | `cutout`, `slice-sheet`, `unpack-atlas` || **D · post-processing** — finished sheets, refined | [recolor.md](recolor.md) | `recolor`, `recolor-palette`, breathing (compose, or `breathe` on a folder of frames), `export-pngs`, `export-aseprite` || **E · asset tools** — independent background, shadow and motion tools | [asset-tools.md](asset-tools.md) | `background-tile`, `shadow`, `inspect-motion` || **S · scene** — optional composition of existing assets | [scene.md](scene.md) | `scene-render`, `scene-inspect` |@@ -79,7 +79,6 @@ grouping is derived from `sprite_gen/_modules.py`, the one taxonomy table.| Doc | Owns ||---|---|| [gen.md](gen.md) | `sprite-gen gen` / `gen-set`: providers, default resolution and what a default codex that cannot run turns into, transparency strategy per provider, where every direct provider call goes (`SPRITE_GEN_<PROVIDER>_BASE_URL`) and subscription logins off (`SPRITE_GEN_LOGINS`), when a refused provider request is sent again, row usage |-| [`sprite-gen sound`](sound.md) | Generate normalized SFX and BGM audio assets with Opus and AAC encoding, SQLite raw request caching, and Web Audio loop metadata. || [pixel-draw.md](pixel-draw.md) | `sprite-gen pixel-draw` (experimental): Claude Opus draws 8–48 px pixel art as a pixel grid — the inputs, the safe area, the style (`--style`), a set of up to 64 frames drawn four at a time and one motion (`--motion`), the run folder and its report, gates G1–G8, the row repair and the one redraw, the pick between candidates, Message Batches and `--resume`, re-rendering an edited `grid.txt` || [logo.md](logo.md) | `sprite-gen logo`: a title logo or wordmark lettered by the model into a title screen or poster, only its lettering redrawn on a chroma key, cut out with its glow kept — the steps, files, report, text check and refusals, the key choice, the logo matte and its known limit || [prompt-assembly.md](prompt-assembly.md) | What the engine adds to a still or clip prompt and when: the pieces, the 2.22.0 freeze without `--handed`, what counts as already said, and the notes on the caller's own words |@@ -105,7 +104,6 @@ grouping is derived from `sprite_gen/_modules.py`, the one taxonomy table.|---|---|| [recolor.md](recolor.md) | Deterministic palette-swap bake, colourway pick, `variants/` and its report || [engine-export.md](engine-export.md) | Aseprite-compatible export for Phaser and Flame |-| [`game-pack`](game-pack.md) | Compile sprite assets into deterministic multi-page texture atlases and manifests. |## Asset tools and optional scenes@@ -119,8 +117,7 @@ grouping is derived from `sprite_gen/_modules.py`, the one taxonomy table.| Doc | Owns ||---|---|| [directional-anchor-workflow.md](directional-anchor-workflow.md) | Directional / 45° rows: base → direction anchors → rows, the left-right gate |-| [sheet-slicing.md](sheet-slicing.md) | Multi-figure grid sheets to per-cell standing cuts; the `cutout` routes |-| [ui-kit.md](ui-kit.md) | The UI kit layout guide (square for the frames, 2:3 for the whole kit), splitting a transparent UI kit sheet into nine-slice elements with measured insets and padding, fills fitted to their bar frames, and the shared alpha haze cleanup |+| [sheet-slicing.md](sheet-slicing.md) | Multi-figure grid sheets to per-cell standing cuts, the alpha haze cleanup of a transparent sheet; the `cutout` routes |## QAdiff --git a/docs/asset-tools.md b/docs/asset-tools.mdindex 60d34c7..6251458 100644--- a/docs/asset-tools.md+++ b/docs/asset-tools.md@@ -25,21 +25,11 @@ Generate and remove the key with the existing tools, then run the tile command osprite-gen background-tile --source frontage.png --axis x --period 512 --overlap 32 --out tile.png```-`--axis x|y|xy` chooses the repeat direction. `--period` is the output length in source pixels; `--overlap` is the input overlap used to find a low-error quilting seam. Input must contain enough pixels for the requested period and overlap. The tool preserves RGBA, writes a new PNG and `<out-stem>.report.json`, and never overwrites its source. `--report` changes the JSON destination.+`--axis x|y` chooses the repeat direction. `--period` is the output length in source pixels; `--overlap` is the input overlap used to find a low-error quilting seam. Input must contain enough pixels for the requested period and overlap. The tool preserves RGBA, writes a new PNG and `<out-stem>.report.json`, and never overwrites its source. `--report` changes the JSON destination.The report measures the join against ordinary interior differences, including alpha and colour over light/dark backgrounds. It records the selected seam and source crop. A numerical join score does not prove that architecture or silhouettes repeat convincingly: inspect at least two adjacent copies. The tool does not invent missing roofs, perspective or scenery.-### Both axes: a ground tile--```bash-sprite-gen background-tile --source ground.png --axis xy --period 960 --overlap 64 --out ground-tile.png-```--`--axis xy` makes one square tile, `--period` on each side, that repeats in both directions; the source needs `period + overlap` pixels on both axes. It quilts along x, then along y. The second quilt cannot break the first one's join: its seam's two ends meet across the x wrap, so they may differ by one step at most, like any two neighbouring rows of a seam. Two separate `--axis x` and `--axis y` runs have no such rule, and the second run's report measures only its own axis.--The report measures the finished tile on both axes. `axes.x` and `axes.y` each hold that axis's join measurement (`edge_color_difference`, `seam_alpha_mismatch`, their interior baselines and thresholds), its quilt seam and search, and its own `status` and `review_reasons`. The top-level `status` is `needs-review` when either axis is, and every top-level reason is prefixed with its axis (`y: Internal quilt color difference exceeds source interior variation.`). `size` is the tile's `[width, height]` and each axis report keeps its own `period`; `source_crop` and `core_crop` are `[x0, y0, x1, y1]` boxes in the source. Look at a 2 × 2 repeat of the tile before using it.--Python APIs: `make_tile(image, period, *, axis="x", overlap=32)`, `inspect_tile(image, axis="x")` and `inspect_tile_xy(image)` in `sprite_gen.background.tile`. The first returns the image and report (`axis="xy"` included); the others only measure, `inspect_tile_xy` both joins of a tile in the report shape above without the quilt fields. `inspect_tile` is the one measure of a tile's join: [`pixel-draw`](pixel-draw.md#gates)'s G4 tile seam asks it of a drawn tile along x and along y and warns where it says `needs-review`.+Python APIs: `make_tile(image, period, *, axis="x", overlap=32)` and `inspect_tile(image, axis="x")` in `sprite_gen.background.tile`. The former returns the image and report; the latter only measures. `inspect_tile` is the one measure of a tile's join: [`pixel-draw`](pixel-draw.md#gates)'s G4 tile seam asks it of a drawn tile along x and along y and warns where it says `needs-review`.## Shared asset inputdiff --git a/docs/capabilities.md b/docs/capabilities.mdindex fcc2830..790e510 100644--- a/docs/capabilities.md+++ b/docs/capabilities.md@@ -25,7 +25,7 @@ against every verb's printed options.|---|---|| `kind` | `sprite-gen-capabilities` || `version` | the installed package's version (`unknown` from a bare checkout) |-| `providers` | per provider (`openai`, `xai`, `anthropic`, `elevenlabs`): `base_url_env` (the variable that moves its calls), `base_url` (the documented address used when it is unset), `key_env` (its API key); docs/gen.md, [provider addresses](gen.md#provider-addresses) |+| `providers` | per provider (`openai`, `xai`, `anthropic`): `base_url_env` (the variable that moves its calls), `base_url` (the documented address used when it is unset), `key_env` (its API key); docs/gen.md, [provider addresses](gen.md#provider-addresses) || `logins_env` | `SPRITE_GEN_LOGINS`, where `off` turns subscription logins off ([subscription logins off](gen.md#subscription-logins-off)) || `verbs` | every verb, in the order of `sprite-gen --help`'s table |@@ -68,7 +68,6 @@ its `--help` and its doc ([docs/README.md](README.md)).|---|---|---|| `gen`, `gen-set`, `logo` | `openai` (`--provider openai`), `xai` (`--provider grok`); codex runs on its own login | yes || `pixel-draw` | `anthropic` | yes |-| `sound` | `elevenlabs` | yes || `curation` | `xai` (the reroll and in-between buttons on grok; codex on its own login) | yes || `video`, `video-extend`, `video-edit`, `video-set` | `xai` | yes || `video-resume` | `xai` | no |diff --git a/docs/face-parts.md b/docs/face-parts.mdindex 3d9915f..58c2862 100644--- a/docs/face-parts.md+++ b/docs/face-parts.md@@ -242,7 +242,7 @@ If the planner finds no suitable frame within the body clip and one round of the| Frame steps | `video.loop._small_features` | Loop analysis features. || Jump line | `video.stop.SEAM_MAX` | Stop and loop jump line, 1.4. || Mask growth and pieces | `video.parts._dilate`, `_erode`, and `_pieces` | Tail mask morphology. |-| Packaged JS player and digests | Sound pack's `sprite-gen-audio-v2.mjs` and `audio/manifest.py` | One rule in JS, copied into the pack. |+| Packaged JS player and digests | New code here | One rule in JS, copied into the pack. || JS run from Python | node, as in the breathe JS mirror test | Runs the pack's player for a bake. || Similarity anchor with size and tilt | New code here | The engine has no size and tilt reading. || Mouth reading and expression sets | New code here | The engine has no mouth reading. |diff --git a/docs/game-pack.md b/docs/game-pack.mddeleted file mode 100644index 5c0340e..0000000--- a/docs/game-pack.md+++ /dev/null@@ -1,367 +0,0 @@-# `game-pack` reference--`sprite-gen game-pack` is a CPU-only command that compiles images, animation sequences, multi-state descriptors, and directional sprite sheets into deterministic multi-page texture atlases and a manifest. Source files remain unchanged on disk, and exported frames are resampled to target display dimensions.--## Command-line interface--```bash-sprite-gen game-pack --request game.json --out-dir game-assets-```--### Options--* `--request <path>`: Path to the request JSON file. Paths within the request resolve relative to the request file directory.-* `--out-dir <path>`: Target output directory. Must be a new directory path.-* `--page-size <int>`: Maximum page dimension in pixels. Defaults to `4096`. Lower bound is `1`; cannot exceed `4096`.-* `--max-bytes <int>`: Total encoded byte budget for all output files (PNG, WebP, JSON, JS modules, OGG, and M4A combined). Defaults to `50000000` (50 MB). Lower bound is `1`; configurable downward only.--Invalid arguments, missing files, frame dimension overflows, or budget violations exit with a non-zero status.--## Filesystem safety and determinism--* The output directory must not exist prior to packing.-* If the target directory already exists with the exact same pack generated from identical inputs, the existing pack is returned. Differing content causes execution to refuse.-* The command refuses to publish over input files: execution is rejected if the resolved output path equals any input file path or is an ancestor directory of any input file. Output may reside next to inputs or in a subdirectory.-* The full pack is encoded and size-verified in memory before staging. Output files are written to a temporary staging area, persisted with `fsync`, and published atomically via directory rename. Competing writers cannot interleave pages.-* Given identical inputs and encoder versions, output bytes are identical. Outputs contain no timestamps, absolute file system paths, or unstable sorting orders.--## Request format--```json-{- "version": 1,- "assets": [- {- "id": "hero-walk",- "source": "walk.strip.json",- "source_body_height": 400,- "display": { "body_height": 96 }- },- {- "id": "coin",- "source": "coin.png",- "display": { "height": 16 },- "resample": "nearest"- }- ]-}-```--A request must declare at least one asset or sound; `assets` may be empty or absent when `audio` names a sound (a [sound-only pack](#sound-only-packs)). A request with neither is refused ("game pack request declares nothing to pack").--### Asset identification and naming--* Asset `id` and optional `state` names must use only letters, digits, underscores, dots, and hyphens (`[a-zA-Z0-9_.-]`).-* `state` selects a single named state from a multi-state source.-* Animation keys are named `<id>` for unlabelled sources, or `<id>/<state>` when selecting or expanding states and directions.-* Frame keys inside the manifest follow `<animation-key>/000000`.--### Supported sources--The `source` property resolves:-* A static PNG image.-* A video-loop strip JSON with a same-stem PNG.-* A row-major grid sidecar descriptor with a same-stem PNG.-* A video-set sheet JSON (expands directions).-* A compose-atlas manifest (expands all states).-* A `sprite-gen-asset` version 1 external descriptor with ordered frames `[{"file": "...", "duration": <seconds>}]`.--Playback order is preserved directly from the source description into output animation `frames`. Frames are never sorted by filename.--### Display sizing and resampling--The `display` object requires exactly one positive integer dimension:-* `width`: Canvas width in pixels; height preserves aspect ratio to the nearest whole pixel.-* `height`: Canvas height in pixels; width preserves aspect ratio to the nearest whole pixel.-* `body_height`: Character body height in pixels. Scales using source metadata `body_h`. When `body_h` is absent, provide `source_body_height` on the asset entry root.--Frame alpha is not auto-trimmed. Accepted request `resample` values remain `nearest` and `lanczos`, defaulting to `nearest` when source metadata contains `frame_variant=pixel`, and `lanczos` otherwise. `nearest` uses Pillow nearest-neighbour directly, preserving pixel-art samples. The `lanczos` request mode now delegates to the engine's shared `sprite_gen.util.resample.resize_cell`, the same cutout scaler used by video-loop, extract, slice-sheet, and scene. It scales coverage separately from colour (LANCZOS coverage and Hamming colour), avoiding the colour ringing of plain RGBA LANCZOS (refer to the Cells item in [video-pipeline.md](video-pipeline.md)). For plain pixel-art PNGs lacking metadata, set `"resample": "nearest"`.--### Playback overrides and defaults--Source policies and row anchors are preserved by the asset adapter. Optional entry overrides include:-* `anchor`: `[x, y]` in source pixel space. When undeclared in both source metadata and entry overrides, defaults to canvas bottom-center. Provide explicit coordinates for padded sources.-* `fps`: Playback frame rate.-* `loop`: Loop flag (defaults to `true`).-* `hold_last`: Hold final frame on completion (defaults to `false`).-* `end_frame`: Zero-based output playback termination index (defaults to final frame; validated within frame count).-* `blend`: `"normal"` (default) or `"add"`.-* `direction`: Direction override code or `null` (defaults to `null`). Allowed only if the entry resolves to one animation; the user can select one source `state` to override one animation. An entry expanding multiple states or directions must reject any `direction` field, including `null`, before publishing output.-* `events`: Array of `{"frame": <int>, "name": "<string>"}` triggers where `frame` is a zero-based playback position validated within frame count (defaults to `[]`).--A `video-stop` strip sidecar is packed like a loop strip and carries `loop: false`, `hold_last: true` and an `anchor` that puts the loop's pivot where the stop's cells hold it, so the two animations drawn at their anchors stand in one place.--## Packing and layout--* Every frame receives 1-pixel edge extrusion on each side (+2 pixels to width and height). Maximum frame dimension plus 2 pixels must fit within `--page-size`.-* Trimming and rotation are disabled (`trimmed: false`, `rotated: false`).-* Each page has PNG and lossless WebP copies (preserving exact RGB and alpha).-* Total byte size across all PNG, WebP, JSON, JS modules, OGG, and M4A outputs must not exceed `--max-bytes`.-* Layout packing bins assets and frames using stable keys.--## Output manifest--The output `game-pack.json` structure:--```json-{- "kind": "sprite-gen-game-pack",- "version": 1,- "textures": [- {- "image": "atlas-000.png",- "webp": "atlas-000.webp",- "frames": {- "hero-walk/000000": {- "frame": { "x": 1, "y": 1, "w": 32, "h": 64 },- "sourceSize": { "w": 32, "h": 64 },- "spriteSourceSize": { "x": 0, "y": 0, "w": 32, "h": 64 },- "trimmed": false,- "rotated": false,- "pivot": { "x": 0.5, "y": 1.0 }- }- },- "meta": {- "image": "atlas-000.png",- "format": "RGBA8888",- "size": { "w": 2048, "h": 2048 },- "scale": "1"- }- }- ],- "animations": {- "hero-walk": {- "frames": ["hero-walk/000000"],- "durations_ms": [100],- "loop": true,- "hold_last": false,- "end_frame": 0,- "blend": "normal",- "events": [{ "frame": 0, "name": "impact" }],- "direction": null,- "anchor": [16, 64],- "size": { "w": 32, "h": 64 }- }- }-}-```--Manifest fields:-* `textures[].frames`: TexturePacker JSON Hash format containing `frame`, `sourceSize`, `spriteSourceSize`, and normalized `pivot`.-* `animations[].anchor`: Output anchor coordinates `[x, y]` in resized canvas pixels.-* `animations[].durations_ms`: Frame durations in milliseconds for every frame position, including repeated positions.--## Phaser 4.2.1 integration--Phaser's [`JSONHash`](https://github.com/phaserjs/phaser/blob/v4.2.1/src/textures/parsers/JSONHash.js) parser reads `frame`, `sourceSize`, `spriteSourceSize`, and `pivot`.--Phaser's `load.multiatlas` expects frame arrays and cannot parse `game-pack.json` directly. With images already loaded as HTML image elements, bind the multi-page atlas to a single texture key using [`TextureManager.addAtlasJSONHash`](https://github.com/phaserjs/phaser/blob/v4.2.1/src/textures/TextureManager.js):--```javascript-function registerGamePack(scene, imagesInPageOrder, pack) {- return scene.textures.addAtlasJSONHash('game', imagesInPageOrder, pack.textures);-}-```--`addAtlasJSONHash` assigns `sourceIndex` offsets to frames across pages. The game runtime is responsible for reading `durations_ms` and applying animation playback policies (`repeat = anim.loop ? -1 : 0`, `hold_last`, `blend`, and `events`).--## Version 2: images, tiles and UI--Version 2 adds three sections for painted scene art: single images such as props (`images`), repeating ground tiles (`tiles`) and a UI kit with nine-slice frames and icons (`ui`). A request opts in with `"version": 2`; the manifest it produces says `"version": 2`. A version 1 request is packed exactly as before: the same files with the same bytes, and a version 1 manifest that has none of the new keys. A version 1 request that names `images`, `tiles` or `ui` is refused instead of being packed without them.--### Version 2 request--```json-{- "version": 2,- "assets": [- { "id": "hero", "source": "hero.strip.json", "display": { "height": 96 } }- ],- "images": [- { "id": "fountain", "source": "props/fountain.png", "display": { "height": 120 },- "anchor": [256, 725], "footprint": "base" },- { "id": "lantern", "source": "props/lantern.png", "display": { "height": 96 },- "footprint": { "x": 180, "y": 640, "w": 150, "h": 80 } }- ],- "tiles": [- { "id": "ground", "source": "ground-tile.png", "display": { "width": 480 } }- ],- "ui": {- "kit": "ui/ui-kit.json",- "scale": 0.5,- "icons": [- { "id": "sword", "source": "icons/sword.png", "display": { "height": 48 } }- ]- }-}-```--* `assets` and `audio` keep their version 1 meaning. As in version 1, `assets` may be empty or absent; the request must still declare at least one asset, image, tile, UI kit, icon or sound.-* Every `id` uses the asset name characters (`[A-Za-z0-9_.-]`) and is unique within its section.-* `images[]`: one PNG each (a static image or a one-frame descriptor; more frames are refused). `display` takes exactly one of `width` or `height` (no `body_height`), and `resample` works as for assets. `anchor` is `[x, y]` in source pixels and defaults to the bottom centre of the image. `footprint` is optional: an explicit `{x, y, w, h}` rectangle in source pixels, or `"base"` for the measured base described below.-* Props cut from one sheet by [`slice-sheet`](sheet-slicing.md#props-and-icons-sheet-scale-and-contain-fit) share one canvas size, so giving every cell of the sheet the same `display` height keeps the sizes the sheet gave them (`--scale sheet`). The [slice-sheet report](sheet-slicing.md#report) states each cell's `anchor`, the centre of its main subject's base, in the PNG's own pixels: pass it as the entry's `anchor` as it is.-* `tiles[]`: one PNG each, ideally a seamless tile from [`background-tile --axis xy`](asset-tools.md#repeating-tiles). `display` takes exactly one of `width` or `height`: the size of one tile on screen. The tile's pixels are never resampled: the pack stores the source pixels and states both sizes.-* `ui.kit`: the JSON report a [`ui-kit`](ui-kit.md) run wrote. Every element it lists becomes a nine-slice entry, with the element PNGs it names (paths relative to the report). `ui.scale` (default `1`, positive) resizes every kit element by the same factor, so the kit stays one consistent set; a [fill](ui-kit.md#fills) instead takes its size from its frame's content area, below.-* `ui.icons[]`: fixed images such as upgrade or weapon icons, with `id`, `source` and `display` as for `images` (no anchor or footprint).-* The `"base"` footprint is measured on the source image: take the bounding box of pixels with alpha at least 128, keep its lowest fifth (rounded up, at least one row), and the footprint is the bounding box of the pixels with alpha at least 128 inside that band. It is where a prop meets the ground in a top-down or three-quarter view. It is a measurement, not a collision shape the art guarantees.--### Version 2 manifest--```json-{- "kind": "sprite-gen-game-pack",- "version": 2,- "textures": [ "...as in version 1; image, ui and icon frames are atlas frames here..." ],- "animations": { "...as in version 1..." },- "images": {- "fountain": {- "frame": "image/fountain",- "size": { "w": 104, "h": 120 },- "anchor": [52, 120],- "footprint": { "x": 10, "y": 96, "w": 84, "h": 24 }- }- },- "tiles": {- "ground": {- "image": "tile-ground.png",- "webp": "tile-ground.webp",- "size": { "w": 960, "h": 960 },- "display_size": { "w": 480, "h": 480 }- }- },- "ui": {- "nine_slice": {- "panel": {- "frame": "ui/panel",- "size": { "w": 288, "h": 200 },- "stretch": "xy",- "insets": { "left": 56, "right": 56, "top": 46, "bottom": 46 },- "padding": { "left": 24, "right": 24, "top": 22, "bottom": 22 }- },- "hp_bar_frame": {- "frame": "ui/hp_bar_frame",- "size": { "w": 304, "h": 56 },- "stretch": "x",- "insets": { "left": 66, "right": 30, "top": 0, "bottom": 0 },- "padding": { "left": 70, "right": 34, "top": 18, "bottom": 18 }- },- "hp_bar_fill": {- "frame": "ui/hp_bar_fill",- "size": { "w": 200, "h": 20 },- "stretch": "x",- "insets": { "left": 6, "right": 6, "top": 0, "bottom": 0 },- "padding": { "left": 0, "right": 0, "top": 0, "bottom": 0 },- "inside": { "element": "hp_bar_frame", "rect": { "x": 70, "y": 18, "w": 200, "h": 20 } }- }- },- "icons": {- "sword": { "frame": "icon/sword", "size": { "w": 48, "h": 48 } }- }- }-}-```--A version 2 manifest always has `images`, `tiles` and `ui`, and `ui` always has `nine_slice` and `icons`; each may be empty (`{}`). Keys are the request ids and are sorted.--What each field means, with no reading left to the consumer:--* **Where the pixels are.** `images[*].frame`, `ui.nine_slice[*].frame` and `ui.icons[*].frame` are atlas frame names in `textures[].frames`, so they load with the atlas like animation frames. Their names are `image/<id>`, `ui/<id>` and `icon/<id>`. A tile is not in the atlas: `tiles[*].image` is its own PNG file in the pack (with a lossless WebP copy in `webp`), because a repeating texture needs its own image to wrap.-* **Units.** Every size, anchor, footprint, inset and padding is in pixels of the image as stored in the pack, after the display resize: the frame's own pixels for atlas frames, the PNG's pixels for tiles. Nothing is in source pixels.-* `images[*].size` is the stored frame size. `anchor` is `[x, y]` from the frame's top-left corner (a fraction where the scaled point falls between pixels, as for animation anchors), and the atlas frame's `pivot` is the same point normalised. `footprint` is `{x, y, w, h}` from the frame's top-left corner, or `null` when the request declared none. A source footprint is scaled outward to whole pixels (left and top rounded down, right and bottom rounded up) and kept inside the frame.-* `tiles[*].size` is the stored PNG size. `display_size` is the on-screen size of one tile: draw the repeating texture with a tile scale of `display_size.w / size.w` horizontally and `display_size.h / size.h` vertically.-* `ui.nine_slice[*].size` is the stored frame size. `stretch` says how the element may be resized: `"xy"` both ways (a nine-slice), `"x"` in width only (a three-slice whose height stays `size.h`; `top` and `bottom` are `0`), `"none"` not at all (draw it at `size`; every inset is `0`). `insets` are the widths of the fixed border slices: in Phaser, `scene.add.nineslice(x, y, texture, frame, width, height, insets.left, insets.right, insets.top, insets.bottom)`. The stretched middle lies between the insets, and every corner ornament the [`ui-kit`](ui-kit.md) run found lies inside them. When the pack resizes the kit by `ui.scale`, each inset is the report's inset scaled and rounded up, or, where it is larger, the inset the same [measurement](ui-kit.md#insets) finds on the resized pixels: resampling spreads an ornament's edge a little, and that fringe stays in the fixed slice too. A scale so small that the insets leave no stretchable middle, or the padding no content area, is refused.-* `padding` places the element's content: the inner area where a panel's text, a card's contents, a badge's digits or a bar's fill goes. For an element drawn at width `W` and height `H` (its stored size or any size its `stretch` allows), the content rectangle is `x = padding.left`, `y = padding.top`, `w = W - padding.left - padding.right`, `h = H - padding.top - padding.bottom`, from the element's top-left corner. For `hp_bar_frame` and `xp_bar_frame` this is the track: fill it from its left edge to show a fraction, with the kit's `hp_bar_fill` and `xp_bar_fill` when it has them (`inside`, below). Paddings are scaled with `ui.scale` and rounded up, so the content area only shrinks.-* `inside` is on a fill alone (`hp_bar_fill`, `xp_bar_fill`): `element` is the frame it goes in, and `rect` that frame's content rectangle, from the frame's top-left corner in the frame's stored pixels (its `padding` applied to its `size`). The fill is stored at exactly that rectangle's size: resized by the one factor that makes it as tall as the rectangle (its ends keep their shape; each inset is the report's inset times that factor, rounded up, or the [measured](ui-kit.md#insets) inset of the resized pixels where that is larger), then drawn as wide as the rectangle with its end slices kept and its middle columns repeated or dropped. So a full bar is the fill drawn at its `size` at `rect.x`, `rect.y` in the frame, and it covers the content rectangle to the pixel; a fraction `f` is the fill drawn as a three-slice `f × size.w` wide from there (narrower than its two ends, `insets.left + insets.right`, a three-slice cannot shrink: show the fill's left part instead). When the frame is drawn wider than its stored size, the content rectangle grows with it: draw the fill as wide as the new rectangle allows. `ui.scale` reaches a fill only through its frame. A fill whose frame is not in the report (or is itself a fill), a fill that does not stretch `"x"`, and a fill whose two ends, so resized, are as wide as the rectangle are refused. The pack reads only `inside.element` from the report and works the rectangle out again from the frame it packed.-* `ui.icons[*].size` is the stored frame size; icons are drawn as they are.-* The atlas frames of images, UI elements and icons have `trimmed: false`, `rotated: false` and the same one-pixel extrusion as animation frames. UI element and icon frames have the pivot `{x: 0.5, y: 0.5}`.--The UI kit element names are fixed by the [`ui-kit` layout](ui-kit.md#layout): `panel`, `button`, `button_pressed`, `card`, `hp_bar_frame`, `xp_bar_frame` and `timer_badge` from a square sheet, and from a 2:3 sheet those seven and `hp_bar_fill`, `xp_bar_fill`, `slot`, `badge`, `pip_on`, `pip_off`, `joystick_base` and `joystick_knob`. Their `stretch` is part of the layout: the frames, buttons, slot and badge are `"xy"`; the two bar frames and the two fills `"x"`; the timer badge, the pips and the joystick base and knob `"none"`. The fills, the pips and the joystick parts hold no content, so their padding is `0`. These names are additive: the manifest stays version 2, and a kit from a square sheet packs to the same manifest and the same atlas pixels as before. A 2:3 sheet may leave an optional element out ([missing elements](ui-kit.md#missing-elements)): the report then names it under `missing` and has no entry for it, and the pack has no `ui.nine_slice` entry and no atlas frame for it. A game falls back for exactly the parts `nine_slice` lacks.--## Audio Assets and Playback--Game packs support optional bundled audio declared in pack recipes via `request.audio`:--```json-{- "audio": [- { "id": "music", "source": "../music/sound.json" }- ]-}-```--### Integration Rules-- **Packaging and Manifest**: Pack assembly copies format files flat into the output directory as `audio-<id>.ogg` (Opus, 160 kbps) and `audio-<id>.m4a` (AAC, 192 kbps). Output `manifest.audio[id]` contains:- - `event`: Safe string event identifier matching animation event names.- - `audio_kind`: `"sfx"` or `"bgm"`.- - `loop`: Boolean looping flag.- - `duration_seconds`: Final prepared playback duration `(end_frame - start_frame - overlap_frames) / sample_rate`.- - `target_lufs`: Target integrated loudness.- - `playback`: Integer coordinate object (`version`, `sample_rate`, `start_frame`, `end_frame`, `overlap_frames`) preserved exactly from source `sound.json`.- - `files`: Format dictionary for `ogg` and `m4a` containing relative paths (`audio-<id>.ogg`, `audio-<id>.m4a`), `sha256`, decoded `duration_seconds`, `lufs`, and `true_peak_dbfs` (`encode_passes` and `pcm_peak_limit_dbtp` exist only in `sound.json` and are stripped on load). Source `sound.json` manifests must specify `recipe.processing_version` 3 or 4 (version 4 manifests require the `normalization` record, while version 3 manifests are decoded and re-measured under the version 3 [loudness rule](sound.md#loudness-rule)). For a peak-limited sound in version 4, `lufs` sits below `target_lufs` (version 3 has no peak-limited goal).- - `player`: Runtime helper descriptor:- ```json- {- "path": "sprite-gen-audio-v2.mjs",- "sha256": "<actual file hash>",- "export": "createAudioSource"- }- ```- The `player.sha256` value is the SHA-256 digest computed from the exact shipped bytes of the bundled module.-- **Runtime Helper**: Pack generation emits a single copy of `sprite-gen-audio-v2.mjs` into the pack root. The helper is self-contained with no external imports or dependencies. The canonical buffer preparation logic resides strictly in this helper; consumers must not duplicate blending logic.-- **Event Linkage**: String matching between audio `event` identifiers and animation `events[].name` provides runtime linkage for consumer engines. The pack does not require an animation for every audio asset (such as background music or UI sound effects) and emits no runtime game glue code.-- **Pack Limits**: All output files (PNG, WebP, JSON, JS modules, OGG, and M4A) count toward `--max-bytes` (default 50,000,000 bytes). Packs containing no audio remain byte-for-byte unchanged.-- **Web Audio Playback Contract**: Conforms to [W3C Web Audio decodeAudioData](https://www.w3.org/TR/webaudio-1.0/#dom-baseaudiocontext-decodeaudiodata) and [W3C Web Audio looping](https://www.w3.org/TR/webaudio-1.0/#looping).- - Never play raw exported loop files with only `source.loop = true`; raw files are encoded audio containing complete pre-overlap sources and codec padding. HTML `<audio loop>` cannot guarantee gapless playback.- - `prepareAudioBuffer(decoded, playback)` returns an immutable, cached source buffer with fixed rounded loop length or one-shot trimmed actual interval; see [rounding and decoder tolerance](sound.md#export-signatures).- - Consumers must use `createAudioSource` to configure loop playback using an internally cached L+1 guard buffer, setting `loopEnd = L / sampleRate` which must not be overwritten with `source.buffer.duration`.--### Sound-only packs--A game whose graphics are drawn in code needs its sounds and no atlas. A sound-only request produces exactly `game-pack.json`, `audio-<id>.ogg`, `audio-<id>.m4a` and `sprite-gen-audio-v2.mjs`; no atlas page (`atlas-*.png` / `atlas-*.webp`) is written. Its manifest has the same keys as a pack with images: `textures` is `[]` and `animations` is `{}` (a version 2 manifest also keeps its empty `images` (`{}`), `tiles` (`{}`) and `ui` (`{"nine_slice": {}, "icons": {}}`)). Each `audio` entry is identical to the entry the same sound gets in a pack with images, `player` included, and the sound files and the helper are byte-for-byte the same as in that pack.--```json-{- "version": 1,- "assets": [],- "audio": [- { "id": "music", "source": "../music/sound.json" }- ]-}-```--### Web Audio Playback Example--```javascript-// Playback must be initiated by a user gesture-button.addEventListener('click', async () => {- const audioContext = new AudioContext();- await audioContext.resume();-- // Load pack manifest- const packURL = new URL('game-pack.json', import.meta.url);- const packResponse = await fetch(packURL);- const pack = await packResponse.json();-- // Inspect audio asset and import bundled runtime helper- const audio = pack.audio.music;- const helperURL = new URL(audio.player.path, packURL).href;- const { createAudioSource } = await import(helperURL);-- // Caller selects supported format (e.g. m4a or ogg)- const formatKey = 'm4a';- const audioFile = audio.files[formatKey];- const audioFileURL = new URL(audioFile.path, packURL);-- // Fetch and decode full source encoded audio file- const fileResponse = await fetch(audioFileURL);- const arrayBuffer = await fileResponse.arrayBuffer();- const decoded = await audioContext.decodeAudioData(arrayBuffer);-- // Create configured, unstarted AudioBufferSourceNode- const sourceNode = createAudioSource(audioContext, decoded, audio);- sourceNode.connect(audioContext.destination);-- // Start playback- sourceNode.start();-});-```diff --git a/docs/gen.md b/docs/gen.mdindex ed997a5..76ce829 100644--- a/docs/gen.md+++ b/docs/gen.md@@ -145,7 +145,7 @@ API contract: [OpenAI Images](https://developers.openai.com/api/images/).## Provider addresses-sprite-gen calls four providers over HTTP itself, with no SDK. Each provider's calls go+sprite-gen calls three providers over HTTP itself, with no SDK. Each provider's calls goto one base address, and one environment variable replaces it. The variable is readwhen each request is made, not at import, so a process that sets or changes it afterimporting the engine is followed. Unset, empty or blank is the documented address, as@@ -157,7 +157,6 @@ fragment, or the call stops naming the variable.| OpenAI | `SPRITE_GEN_OPENAI_BASE_URL` | `https://api.openai.com/v1` | `gen --provider openai` images and edits, its vision checks (facing, the logo's text) || xAI | `SPRITE_GEN_XAI_BASE_URL` | `https://api.x.ai/v1` | `gen --provider grok` images and edits, its vision checks, the video facing check, `video` / `video-extend` / `video-edit` requests and polls, `video-resume` polls, the clip's download || Anthropic | `SPRITE_GEN_ANTHROPIC_BASE_URL` | `https://api.anthropic.com/v1` | `pixel-draw` messages, Message Batches, a batch's results file |-| ElevenLabs | `SPRITE_GEN_ELEVENLABS_BASE_URL` | `https://api.elevenlabs.io/v1` | `sound` effects and music |The value is the API root with its version path, as the default is: a request for`/images/generations` goes to `<value>/images/generations` with the same method,@@ -194,7 +193,7 @@ the order as before; any other value stops the call naming the variable.| xAI (`gen --provider grok`, the video verbs, Grok vision) | the grok login file first (`~/.grok/auth.json`, `GROK_HOME`); `XAI_API_KEY` only without one | `XAI_API_KEY`; the login file and `GROK_HOME` are not looked at || Anthropic (`pixel-draw`) | `claude auth status` first; `ANTHROPIC_API_KEY` only without a subscription login, and for `--batch` | `ANTHROPIC_API_KEY`; `claude` is not run || codex (`gen --provider codex`, its vision checks) | `codex login status`, then `codex exec` | not usable: `codex login status` is not run; a default codex [asks, or runs what you chose](#when-codex-cannot-run--ask-or-what-you-chose), naming `SPRITE_GEN_LOGINS=off`; `--provider codex` stops |-| OpenAI (`gen --provider openai`), ElevenLabs (`sound`) | the key; neither has a login | the same |+| OpenAI (`gen --provider openai`) | the key; it has no login | the same |Each key keeps its own rule either way: set but empty is refused naming it, and amissing key stops the call naming the key (and, with `off`, the variable). A login@@ -223,7 +222,7 @@ sprite-gen gen \[--quality low|medium|high|xhigh|max|auto] # billed effort; openai takes the range, grok takes auto/low/medium[--resolution 1k|1.5k|2k] # grok output-size tier, priced with --quality[--model ID] \- [--layout-guide [figure|ui-kit]] # attach a layout guide: the one-slot figure guide (bare flag) or the UI kit layout+ [--layout-guide [figure]] # attach the one-slot figure layout guide (bare flag)[--direction side|front|back|front_diagonal|back_diagonal [--facing right|left]] # add the engine's view sentence[--handed "the black smartwatch=left wrist" ...] # with --direction: where an item on one side is in that view[--body-plan quadruped | --body-plan "the horse=quadruped" ...] # with --direction: the view for that body@@ -322,7 +321,7 @@ strategy it can execute, and `--alpha-mode auto` (the default) follows it:- **A painted transparency checkerboard is refused before keying.** Asked for a keybackground, a model sometimes paints the grey and white checkerboard that editors showbehind transparent pixels instead. The matte reads the key off the borders, so it reads- the checkerboard and keys nearly the whole image away: a UI kit sheet keyed that way has+ the checkerboard and keys nearly the whole image away: a sheet keyed that way hasnothing left to cut. A caller generates again.- `--alpha-mode chroma` on codex is for prompts that already carry a key background: the native request is **not** added to the promptand the raw is keyed like a grok run.diff --git a/docs/prompt-assembly.md b/docs/prompt-assembly.mdindex ed976c3..0d099e3 100644--- a/docs/prompt-assembly.md+++ b/docs/prompt-assembly.md@@ -37,7 +37,7 @@ sentences put in (`tests/gen/test_prompt_assembly.py`).| handed | `--direction --handed` | `handedness.text` || facing | `--ref` with `--facing` | `facing.prompt_suffix` || key background | `--transparent --ref` when `auto` plans a key | `chroma.KEY_BACKGROUND_TEXT` |-| layout guide | `--layout-guide` (`ui-kit`: the UI kit layout) | `gen.layout_guide_text`; `frames.ui_kit.guide_text` |+| layout guide | `--layout-guide` | `gen.layout_guide_text` |A facing correction (`--facing-fix regen`) regenerates with the correction ("CORRECTION REQUIRED: …")said after the first prompt (`facing.prepare_correction`).diff --git a/docs/run-contract.md b/docs/run-contract.mdindex 10c9a30..5ea12b2 100644--- a/docs/run-contract.md+++ b/docs/run-contract.md@@ -302,8 +302,7 @@ removed.The verbs that check a single output against their inputs call the same two functions,`runio.same_folder` and `runio.inside_folder`, and have no comparison of their own:-`background-tile`, `inspect-motion`, `scene-inspect`, `scene-render`, `game-pack`, `ui-kit` and-`video-sway-inspect`. `video-sway-inspect` now refuses an `--out-dir` that is the loop directory+`background-tile`, `inspect-motion`, `scene-inspect`, `scene-render` and `video-sway-inspect`. `video-sway-inspect` now refuses an `--out-dir` that is the loop directoryspelt in capitals on a volume that ignores case; before, it wrote its boards into the loopdirectory. `video-loop-compare`, `video-loop-repair`, `video-source-manifest` and `shadow`compared their report or outputs with their inputs by resolved spelling; they now calldiff --git a/docs/sheet-slicing.md b/docs/sheet-slicing.mdindex 85c0466..d39089b 100644--- a/docs/sheet-slicing.md+++ b/docs/sheet-slicing.md@@ -63,7 +63,7 @@ has no key to remove: pass `--chroma-key none` and the sheet keeps its own alphaTransparent sheets often carry a faint alpha haze around and between the drawn objects. Itjoins neighbouring parts and enlarges a figure's measured height. `--alpha-floor N` (1..255;`64` suits most generated sheets) clears it before parts are measured, with the shared-[alpha cleanup](ui-kit.md#alpha-cleanup): pixels at or above the floor and the faint pixels+[alpha cleanup](#alpha-cleanup): pixels at or above the floor and the faint pixelswithin `--alpha-edge` pixels (default 2) of them are kept as they are, every other faint pixelbecomes fully transparent. The run writes the cleanup's report to`<out-dir>/<prefix>alpha-cleanup.json` (haze share before and after, pixels cleared, and the@@ -75,6 +75,25 @@ sprite-gen slice-sheet --sheet props.png --out-dir props/ --chroma-key none --al--grid 3x2 --names pillar,statue,shrub,lantern,gravestone,fountain --prefix prop_```+### Alpha cleanup++Transparent sheets from image models often carry a faint alpha haze: barely visible pixels around and between the drawn objects. `--alpha-floor` clears it with `sprite_gen.frames.alpha_floor.clear_haze`.++* A pixel at or above the floor (`--alpha-floor`) is solid. A pixel above zero and below the floor is faint.+* A faint pixel within `--alpha-edge` pixels (8-connected, so diagonals count) of a solid pixel is part of an object's anti-aliased edge and is kept unchanged.+* Every other faint pixel is haze and becomes fully transparent (`0, 0, 0, 0`). A pixel that was already fully transparent is left as it was.++Solid pixels and edge pixels are never changed, so a stroke stays whole as long as some of its pixels reach the floor. A stroke drawn entirely below the floor is indistinguishable from haze and is removed: lower the floor for very faint art. The report measures instead of asserting: it counts what actually changed.++| Field | Meaning |+|---|---|+| `floor`, `edge_px` | the settings |+| `pixels` | pixels in the image |+| `faint_fraction_before`, `faint_fraction_after` | share of all pixels with alpha from 1 to `floor - 1`, before and after |+| `haze_fraction_before`, `haze_fraction_after` | share of all pixels that are faint and farther than `edge_px` from a solid pixel |+| `cleared_pixels` | pixels made transparent |+| `changed_solid_pixels`, `changed_edge_pixels` | solid and kept-edge pixels whose value changed; `0` unless the cleanup is wrong |+## Props and icons: sheet scale and contain fitThe default suits a character's variants: each cell's main subject is scaled to `--target-height` on its own,@@ -101,8 +120,8 @@ sprite-gen slice-sheet --sheet icons.png --out-dir icons/ --chroma-key none --al--grid 4x3 --cell-width 256 --cell-height 256 --baseline-y 236 --target-height 216 --fit contain```-Every cell of a sheet is cut on the same canvas, so a [game pack](game-pack.md#version-2-request) that gives each-cell the same `display` height scales them all by the same amount and the sizes stay relative there too. The alpha+Every cell of a sheet is cut on the same canvas, so a consumer that draws each cell at the same height scales them+all by the same amount and the sizes stay relative there too. The alphacleanup (`--alpha-floor`) runs before anything is measured, so the factor is taken on the cleaned sheet and applies toevery cell alike.@@ -142,8 +161,7 @@ Every run writes `<out-dir>/<prefix>slice-sheet.json`:main subject's base, the point it stands on; `clipped_px` counts the cut's pixels with any alpha that fell pastthe canvas edge (always `0` with `contain`; the run also prints a line for each cell the canvas cut); `parts` ishow many parts the cell kept.-- `anchor` goes into a game pack's `images[].anchor` as it is: it is in the PNG's own pixels. When `--baseline-y`- equals `--cell-height`, the pack's default bottom-centre anchor is the same point.+- `anchor` is in the PNG's own pixels, so an engine can take it as the image's origin as it is.The PNGs of a default run (`--scale cell --fit none`) are byte for byte those of the version before these flags.diff --git a/docs/sound.md b/docs/sound.mddeleted file mode 100644index 3fca011..0000000--- a/docs/sound.md+++ /dev/null@@ -1,160 +0,0 @@-# Audio Asset Reference: `sprite-gen sound`--## Overview and CLI Usage--```bash-sprite-gen sound --kind sfx|bgm --prompt TEXT (or --prompt-file PATH) --duration SECONDS --event NAME --out-dir DIR [--cache-dir DIR] [--loop|--no-loop] [--target-lufs FLOAT] [--crossfade SECONDS]-```--### Options and System Requirements-- `--kind`: `sfx` (default `--no-loop`, -18 LUFS) or `bgm` (default `--loop`, -20 LUFS, instrumental).-- `--prompt` / `--prompt-file`: Prompt text or file. The provider may reject prompts containing artist names, franchises, or lyrics; the CLI omits a dialogue verb.-- `--duration`: Requested duration in seconds.-- `--event`: Safe identifier (1..128 characters); first character must be alphanumeric, remaining characters can be alphanumeric, dot, underscore, dash, or colon.-- `--out-dir`: Destination; must be new or match existing recipe and output file digests.-- `--cache-dir`: Defaults to `$XDG_CACHE_HOME/sprite-gen/audio` or `~/.cache/sprite-gen/audio` (never inside `--out-dir`; local by default but can be copied; no cross-cache-directory or cross-machine duplicate-request guarantee).-- `--target-lufs`: Target integrated loudness within `-36..-9` LUFS.-- `--crossfade`: Overlap duration in seconds.-- **Environment & PATH**: `ELEVENLABS_API_KEY` is required only for new paid requests (offline work needs none); ElevenLabs has no subscription login, so every new request is billed per call and says so on stderr before it leaves (`[gen] elevenlabs: running on ELEVENLABS_API_KEY — this is a per-call API charge …`, the line every metered route prints), and the receipt records `auth_source`. `SPRITE_GEN_ELEVENLABS_BASE_URL` sends new requests through another address ([provider addresses](gen.md#provider-addresses)). `ffmpeg` (with `libopus` and `aac` encoders) and `ffprobe` are required on `PATH` and checked before paid calls.--## Provider APIs and Cost Accounting--Requests use ElevenLabs (`output_format=mp3_44100_128`):-- **SFX**: `POST /v1/sound-generation` (`text`, `duration_seconds` 0.5..30 [API reference takes precedence over 0.1s overview bound], `loop`, `model_id="eleven_text_to_sound_v2"`, `prompt_influence=0.3`).-- **BGM**: `POST /v1/music` (`prompt` max 4100 characters, `music_length_ms` 3000..600000, `model_id="music_v1"`, `force_instrumental=true`).--### Billing and Usage Accounting-Checked 2026-10-13: [ElevenLabs Pricing](https://elevenlabs.io/pricing/api) quotes SFX at $0.12/min and music at $0.15/min (USD), FAQ notes generation metering, and legacy [Capabilities](https://elevenlabs.io/docs/overview/capabilities/sound-effects) states 40 credits/sec for fixed-duration SFX. Because plans vary, no currency conversion is hardcoded; the runtime records provider `character_cost` directly from responses when present (never guessed currency). Check quotas via [User Subscription](https://elevenlabs.io/docs/api-reference/user/subscription/get) (`character_count`/`character_limit`).--## Cache Idempotency and Retries--Raw paid audio is stored in SQLite keyed by provider parameter digest. Tuning `--event`, loudness, or exports reuses raw cache without new purchases:-- **Locking & Recovery**: Atomic claims precede requests; raw blobs and receipts commit on success. Duplicates, crashes, or uncertain results refuse resubmission. Do not delete unresolved cache entries blindly; inspect provider billing/history first. All errors remain unresolved.-- **Offline Processing**: Downstream processing runs offline. Identical runs require no network.-- **Retries**: Uses `sprite_gen.gen.retry` exclusively. ElevenLabs 429 retries only when `detail.status` is `system_busy` or `too_many_concurrent_requests` (max 2 retries via `Retry-After` or engine backoff; see [ElevenLabs 429 Errors](https://elevenlabs.io/docs/help-center/technical/api-error-code-429)). No other 429, 5xx, transport retries, or provider fallbacks occur. Emits only bounded status, code, and request IDs without error prose, and the billing line above.--## Audio DSP, Looping, and Quality Gates--1. **Export and Normalization**: Provider audio decodes to 48kHz stereo PCM. Normalization first runs two-pass [FFmpeg Loudnorm](https://ffmpeg.org/ffmpeg-filters.html#loudnorm) (`method: "loudnorm-two-pass"`). When loudnorm's first pass reports no finite second-pass offset, decoded PCM bypasses the second pass to limiter passes (`method: "limiter"`). Normalization applies up to three gain passes through an oversampled lookahead limiter ([FFmpeg Alimiter](https://ffmpeg.org/ffmpeg-filters.html#alimiter) at 192 kHz, auto-gain off, latency compensated, ceiling -2 dBTP) until the PCM is within 0.2 LU of the target with a true peak at or under -1.8 dBTP. Up to three per-format offline encode passes correct codec reconstruction overshoot using measured gain and tighter limiter settings without triggering provider retries.-2. **Export Formats**: Outputs complete normalized audio in 48kHz stereo Opus in OGG (`sound.ogg`, `libopus`, 160 kbps) and AAC in M4A (`sound.m4a`, `aac`, 192 kbps, `-aac_coder fast`). The exporter exports M4A with `-movie_timescale 48000`, equal to the normalized source sample rate (setting the movie header box time scale; see [FFmpeg Formats](https://ffmpeg.org/ffmpeg-formats.html#mov_002c-mp4_002c-ismv)), preserving fractional-millisecond source lengths without introducing declared tail padding. Export files remove all pre-encode crossfades, loop splices, and 5ms boundary zero-tapers; the complete normalized source is preserved intact in encoded audio.-3. **Quality Gates**: Output formats must decode finite, within 1 LU of the [loudness goal](#loudness-rule), with true peak <= -1 dBTP. After every AAC encode, the exporter invokes `ffprobe` and requires first audio stream `time_base=1/48000` and `duration_ts=end_frame-start_frame`; mismatch or unreadable duration fails clearly before publishing. Silence or unmeasurable audio fails. Numeric checks do not judge musical beat alignment.-4. **Looping and Playback Quality**: Crossfading is deferred to runtime preparation. Because playback overlap blending can alter loudness, applications must validate prepared and rendered audio output. No claim is made that all signals are perceptually seamless or beat aligned.-5. **Boundary Continuity Verification**: Computes loop boundary continuity by measuring the wrap delta and subtracting the difference between adjacent samples in the same decoded/resampled buffer at the decoded sample rate, evaluated separately for prepared buffers and rendered output. Artificial control discontinuities must fail; there is no absolute near-zero endpoint sample criterion. Tests verify numeric waveforms rather than subjective listening.--### Loudness Rule--Loudness evaluation uses a unified rule across exporter passes and version 4 bundle loading (version 3 bundles follow their own bullet below):--- **Measurement** (`sprite_gen/audio/processing.py` `measure`):- - Integrated loudness follows [ITU-R BS.1770-4](https://www.itu.int/rec/R-REC-BS.1770): double-precision FFmpeg `biquad` K-weighting at 48 kHz, 400 ms gating blocks every 100 ms, absolute gate at -70 LUFS, relative gate 10 LU under absolute-gated loudness. Audio shorter than 400 ms contains no gating block, is unmeasurable, and is refused.- - True peak is the sample peak after 4x oversampling to 192 kHz (`aresample=192000` then `astats` peak level).- - Encoded files are measured over normalized PCM frames `[0, N)` (first `N` decoded frames; MP4 edit lists remove AAC priming and Ogg headers remove Opus pre-skip) and over the blocks kept by the PCM's gating. Loops are measured on three repetitions. Reusing PCM gating prevents codec gating shifts: on synthetic FFmpeg 5.1 tests, a 0.6 s hit normalized to -18.15 LUFS had blocks at -18.15, -33.05, and -44.81 LUFS (the second 0.15 LU below the gate); standalone AAC decode lifted that block across the gate to read -21.5 LUFS (Opus: -18.3 LUFS), but reads -18.6 LUFS when measured over PCM blocks.-- **Loudness Goal and Passes** (`loudness_goal`, `meets`):- - Goal: `--target-lufs` (default -18 LUFS for sfx, -20 LUFS for bgm), unless the normalized PCM is peak-limited (loudness > 0.2 LU below target and true peak within 0.2 dB of the -2 dBTP ceiling, at or above -2.2 dBTP, after gain passes). A peak-limited sound's goal is its PCM loudness (`pcm_lufs`).- - Every encoded file must measure finite, within 1 LU of the goal, and with true peak <= -1 dBTP.- - Up to three offline encode passes run per format without provider requests. A pass that misses tightens the PCM limiter by measured overshoot plus 0.5 dB, applies gain `goal - measured loudness`, and re-encodes.-- **Transient Peak Limiting Rationale**: Millisecond transients (clicks, sharp hits) cannot reach integrated loudness targets under a -2 dBTP ceiling without limiter distortion. Synthetic example: a 0.5 s click ends normalization at -24.8 LUFS and -1.8 dBTP after three limiter passes; its OGG measures -25.0 LUFS and M4A -25.4 LUFS, both within 1 LU of that goal.-- **Refusal Criteria**: Refuses silent or unmeasurable audio, true peaks exceeding -1 dBTP, files more than 1 LU from the goal, quiet audio with headroom whose PCM peak never reached the ceiling, and files decoded quieter than their peak-limited PCM.-- **Rejected Alternatives**: Measuring one-shots on repeated context counts a single hit as if it repeated and its repeated blocks still cross the gate together; a separate short-clip measure (maximum momentary loudness, or ungated loudness) would change what the target means for every short sound, and ungated loudness also counts trailing silence.-- **AAC Encoder Configuration**: M4A encodes AAC 192 kbps with [`-aac_coder fast`](https://ffmpeg.org/ffmpeg-codecs.html#aac) ("Worse with low bitrates (less than 64kbps), but is better and much faster at higher bitrates."). In synthetic FFmpeg 5.1 tests, the default `twoloop` coder decoded up to 3.6 dB above PCM true peak (90th percentile 1.4 dB over 320 hits), prompting correction passes that cut transient loudness (a synthetic 0.6 s thud ended at -20.2 LUFS, -2.3 dBTP, and was refused). On a 27-hit sample, `fast` remained within 1.1 dB of PCM true peak (median -0.3 dB) compared to 1.9 dB for `twoloop`.-- **Version 3 Bundles**: Evaluated under their original export rules rather than version 4 manifest checks, re-measuring decoded audio:- - **Measurement**: Requires `ffmpeg` and `ffprobe` on `PATH`. Evaluates files against `target_lufs` (version 3 has no peak-limited goal, even if its manifest carries `pcm_lufs` or `pcm_true_peak_dbtp`). Decodes each file and re-measures via `measure_version_3` using FFmpeg `loudnorm` first-pass analysis (`input_i` as integrated loudness, `input_tp` as true peak) over `[start_frame, end_frame)` (three repetitions for loops). Enforces container duration checks (`time_base=1/48000`, `duration_ts=end_frame-start_frame`) and decoded frame counts via `file_frames`. The game pack records re-measured `lufs` and `true_peak_dbfs`; values in `sound.json` are not trusted.- - **Refusal Criteria**: Every file must measure finite, within 1 LU of `target_lufs`, and at a true peak at or under -1 dBTP. Refuses quiet files (such as a tone at -21.5 LUFS against a -18 LUFS target, even if the manifest claims -18.6 LUFS or carries a peak-limited normalization record), hot files (such as a -0.5 dBTP spike claiming -2 dBTP), and version 2 files with millisecond AAC timescales relabeled as version 3.- - **Measurement Rationale**: Uses FFmpeg `loudnorm` rather than this engine's BS.1770-4 meter because version 3 bundles retain no PCM for gating. When measured with an own-audio gate, boundary blocks sitting at the relative gate diverge slightly between implementations. In synthetic tests with FFmpeg 5.1 on 200 synthetic sources (190 bundles produced, 10 refused by the version 3 exporter), `loudnorm` passed 190 of 190 and matched `sound.json` identically. The engine's own-gate meter passed only 189 of 190, failing a 1.5 s hit recorded at -17.98 LUFS as -19.16 LUFS because its third block sat 0.011 LU above the engine's gate while falling under `loudnorm`'s gate. Across the other 376 files, the two meters differed by a median of 0.03 LU (at most 0.09 LU) and at most 0.01 dB true peak.--## Manifest Schema and Coordinates--Outputs `sound.json` (version 2, `kind="sprite-gen-sound"`, `recipe.processing_version=4`, independent of `playback` version 2). The bundle loader (`sprite-gen game-pack` and `sprite-gen sound` reuse) accepts `recipe.processing_version` 3 or 4 (an integer); version 1, 2, a missing recipe, or any other value is refused with a message to make the sound again into a new `--out-dir`. Reusing an existing `--out-dir` in `sprite-gen sound` still requires the bundle's recipe to equal the current one, so directories generated with recipe versions 1, 2, or 3 are rejected (specify a new `--out-dir`). Original provider request cache keys and blobs remain unchanged; reprocessing cached audio needs no key or new paid request. Provider APIs, caching, and retry behaviors remain unchanged.--### Manifest Properties--- `event`: Safe string identifier (1..128 characters).-- `audio_kind`: `"sfx"` or `"bgm"`.-- `loop`: Boolean looping flag.-- `duration_seconds`: Final playback duration in seconds, derived as `(end_frame - start_frame - overlap_frames) / sample_rate` (for example, `(144000 - 12000) / 48000 = 2.75` s).-- `target_lufs`: Target integrated loudness in LUFS (`-36..-9`).-- `playback`: Integer coordinate object governing client-side preparation:- ```json- {- "version": 2,- "sample_rate": 48000,- "start_frame": 0,- "end_frame": 144000,- "overlap_frames": 12000- }- ```- - Coordinates refer to the complete exported pre-overlap PCM source at `sample_rate` (48000 Hz, independent of provider container sample rate) over the half-open interval `[start_frame, end_frame)`.- - Let `N = end_frame - start_frame` and `M = overlap_frames`.- - For non-looping audio (`loop: false`), `M = 0`.- - For looping audio (`loop: true`), `2 <= M < N / 2` (see [helper mapping](#export-signatures) for the export minimum).- - Manifest `duration_seconds` is `(N - M) / sample_rate`.- - The CLI `--crossfade` parameter (seconds) is converted to integer frame count `M`, defaulting to `min(0.25, requested_duration / 8)`.-- `files`: Format dictionary for `ogg` and `m4a` containing `path`, decoded `duration_seconds` (full decoded file duration, which may include codec priming/tail padding), `lufs` (integrated loudness measured over normalized PCM frames and gated blocks; sits below `target_lufs` for peak-limited sounds), `true_peak_dbfs` (true peak level), `sha256`, `encode_passes`, and `pcm_peak_limit_dbtp`.-- `normalization`: Record containing `method` (`"loudnorm-two-pass"` or `"limiter"`), `peak_limit_dbtp` (`-2.0`), `gain_limiter_passes`, `pcm_lufs`, and `pcm_true_peak_dbtp`. For version 4 bundles, the bundle loader requires `pcm_lufs` and `pcm_true_peak_dbtp` to validate against the loudness rule (checking recorded `lufs` and `true_peak_dbfs` against `loudness_goal` via `meets` without decoding files) and rejects bundles without them.-- **Removed Fields**: `codec_taper_seconds`, `loop_start_seconds`, `loop_end_seconds`, and `crossfade_seconds` are removed from output manifest metadata (the recipe still accepts `--crossfade` in seconds).--## Client Playback Helper: sprite-gen-audio-v2.mjs--Loop blending and buffer trimming are executed in the browser via the standalone ES module `sprite-gen-audio-v2.mjs` (owned by the engine under `sprite_gen/audio`, bundled in wheels and emitted into game packs). The helper has no external imports or dependencies. The canonical algorithm resides solely in this module and must not be duplicated into consumer application code.--### Export Signatures--- `prepareAudioBuffer(decoded, playback) => AudioBuffer`:- - Coordinates:- - Input `playback` v2 provides integer fields `sample_rate=sr`, `start_frame=start`, `end_frame=end`, and `overlap_frames=M`.- - Coordinate dimensions are `N=end-start` and destination sample rate `r=decoded.sampleRate`. Rescaling is `rescale(f)=f*r/sr`, evaluating multiplication before division.- - Frame boundaries map to `first=floor(start*r/sr)` and `mappedEnd=floor(end*r/sr)`.- - Buffer length requires `decoded.length >= mappedEnd-1`, providing exactly one frame of tolerance universally, not per decoder; two or more missing frames cause a `RangeError`.- - Destination bounds evaluate to `last=min(mappedEnd,decoded.length)` and `N'=last-first`. All excess decoded padding is ignored.- - One-shots (`M=0`): `L'=N'` and `M'=0`, copying `source[first:last]` unchanged; a one-frame shortfall reduces one-shot length by making the output one frame shorter, with no synthesis or padding.- - Loops (`M>0`): `L'=Math.round((N-M)*r/sr)` is computed exactly once, rounding positive ties toward `+Infinity`, with `M'=N'-L'`. Thus, one missing decoded frame decreases `M'` by one without changing declared loop length `L'` (a one-frame shortfall reduces loop overlap, never declared loop length). The contract requires `2<=M'<N'/2` and `L'>0`; an overlap count `count<2` on a one-frame shortfall throws a `RangeError` containing the exact text `overlap too short after decoder one-frame shortfall`. Do not round overlap independently. The output copies `source[first+M':last-M']`, then blends the tail `M'` frames with the head `M'` frames using complementary cosine weights `0.5 - 0.5 * Math.cos(Math.PI * i / (M' - 1))`.- - Supported minimum decoded rate is `r_min=8000 Hz`; the shared frame-contract validator rejects exports (before normalization and encoding) and manifest imports unless `M*r_min/sr>=3.5` for loops, with the exact integer check `2*M*8000>=7*sr`. This guarantees at least two destination blend frames after interval quantization (`<1` frame), final length rounding (`<=0.5` frame), and the single decoder shortfall (`1` frame). The runtime minimum remains `M'>=2`; when `M'` is 0 or 1 after shortfall, it throws the explicit `RangeError` above. For a 48kHz export, `M=20` is rejected and `M=21` is the minimum allowed. This conservative bound protects arbitrary interval origin and duration for supported rates.- - Decoded-length rationale: Web Audio mandates resampling when context rates differ, but specifies no uniform length rounding. Chromium's official source uses `source_length/(source_rate/destination_rate)` truncated to an integer. Floating-point double arithmetic `48000/(48000/44100)` evaluates just below `44100` and truncates to `44099`. In a fractional example, `144003/(48000/44100)=132302.75625` truncates to `132302`. See [Blink AudioBus sample-rate conversion](https://chromium.googlesource.com/chromium/src/+/6718b706ff100957d755554cec783840a8f1f05b/third_party/blink/renderer/platform/audio/audio_bus.cc). This tolerance is an explicit contract allowance, not a universal specification guarantee.- - **Cache & Immutability**:- - The input `AudioBuffer` is not modified.- - Employs an internal `WeakMap` cache per module instance. Calling with the same input buffer and playback metadata returns the previously prepared buffer. Passing an already prepared buffer with identical metadata returns itself; passing altered metadata on an already prepared buffer throws. Applications should import the same module URL once, retain prepared buffers, and avoid copying prepared PCM back into raw inputs.-- `createAudioSource(context, decoded, audio) => AudioBufferSourceNode`: Creates and configures an audio source node. For looping playback, it internally creates and caches an L+1 frame buffer with the final sample set to the first prepared sample for cyclic boundary interpolation, setting `loopStart = 0` and `loopEnd = prepared.duration` (L / sampleRate) to exclude the guard frame. One-shots use the immutable L-frame prepared buffer without a guard frame. Consumers must use this function to configure loop playback and must not overwrite `loopEnd` with `source.buffer.duration`; context and audio sample rates should match.--## Examples--```bash-sprite-gen sound --kind sfx --prompt "laser shot" --duration 0.8 --event laser:shot --out-dir ./dist/laser-sprite-gen sound --kind bgm --prompt "synth cave" --duration 20.0 --event cave:bgm --crossfade 0.25 --out-dir ./dist/cave-```--### Manifest Audio Fragment (`sound.json`, Partial)--```json-{- "kind": "sprite-gen-sound",- "version": 2,- "event": "cave:bgm",- "audio_kind": "bgm",- "loop": true,- "duration_seconds": 19.75,- "target_lufs": -20.0,- "playback": {- "version": 2,- "sample_rate": 48000,- "start_frame": 0,- "end_frame": 960000,- "overlap_frames": 12000- },- "files": {- "ogg": { "path": "sound.ogg" },- "m4a": { "path": "sound.m4a" }- }-}-```--## References-- [ElevenLabs SFX](https://elevenlabs.io/docs/api-reference/text-to-sound-effects/convert)-- [ElevenLabs Music](https://elevenlabs.io/docs/api-reference/music/compose)-- [ElevenLabs 429 Errors](https://elevenlabs.io/docs/help-center/technical/api-error-code-429)-- [ElevenLabs Capabilities](https://elevenlabs.io/docs/overview/capabilities/sound-effects)-- [ElevenLabs Pricing](https://elevenlabs.io/pricing/api)-- [ElevenLabs Subscription](https://elevenlabs.io/docs/api-reference/user/subscription/get)-- [FFmpeg Loudnorm](https://ffmpeg.org/ffmpeg-filters.html#loudnorm)-- [FFmpeg Alimiter](https://ffmpeg.org/ffmpeg-filters.html#alimiter)-- [W3C Web Audio decodeAudioData](https://www.w3.org/TR/webaudio-1.0/#dom-baseaudiocontext-decodeaudiodata)-- [W3C Web Audio looping](https://www.w3.org/TR/webaudio-1.0/#looping)diff --git a/docs/ui-kit.md b/docs/ui-kit.mddeleted file mode 100644index 0db632f..0000000--- a/docs/ui-kit.md+++ /dev/null@@ -1,239 +0,0 @@-# `ui-kit` — one painted sheet to nine-slice UI elements--> Owns: The UI kit layout guide, splitting a transparent UI kit sheet into elements, writing a kit whole into a new directory, fitting the layout to a drawing that drifted from it, refusing a drawing that fits the layout in two ways, required and missing elements, nine-slice insets, content padding and fills · Index: [docs/README.md](README.md)--A game UI kit is one transparent image with every part of a game's menus and HUD on it: a panel, a button and its pressed state, a card frame, two bar frames and a timer badge, and on the taller sheet the two bars' fills, an item slot, a counter plate, a lit and an unlit dot, and a touch joystick's base and knob. `gen --layout-guide ui-kit` asks the image model to draw each element in a fixed box. `ui-kit` cuts the sheet along those boxes, measures where each element may stretch, and writes one PNG per element with a JSON report. [`game-pack`](game-pack.md#version-2-images-tiles-and-ui) reads that report. The seven frames are the kit; the taller sheet's other eight elements are optional, so a sheet that leaves one of them out still makes a kit, without it ([missing elements](#missing-elements)).--## Generate the sheet--```bash-sprite-gen gen --provider openai --quality high --transparent --aspect-ratio 2:3 \- --layout-guide ui-kit --prompt-file uikit-prompt.txt --out uikit.png-```--`--layout-guide ui-kit` draws the [layout](#layout) as a guide image, attaches it after any `--ref`, and adds a paragraph to the prompt that names every box and what to draw in it. The caller's prompt describes the style: material, palette, trim, mood. It does not need to list the elements or their positions. The guide asks for straight, even edges between corner ornaments, empty element centres, bare fills of one colour along their length, dots and joystick parts as circles with nothing square around them, no text and empty space between elements, because only those can be sliced.--The sheet's shape chooses the layout. `--aspect-ratio 2:3` draws the whole kit; `--aspect-ratio 1:1` (or no ratio) draws the seven frames alone, the layout every square sheet has had. Every provider that takes a ratio takes both.--The guide is an attached image, so `--transparent` keys the sheet out of a magenta background by default ([gen](gen.md#transparent-output--strategy-per-provider)). A model sometimes paints the grey and white checkerboard that editors show behind transparent pixels instead of that background. Keying the checkerboard would erase the sheet, so `gen` refuses it before keying, with its own reason (`chroma: the background is a painted transparency checkerboard …`). Generate the sheet again.--## Layout--The guide and the splitter read one table (`sprite_gen.frames.ui_kit.LAYOUT`). Boxes are in pixels of a sheet 1024 px wide: 1024 × 1024 for the square sheet, 1024 × 1536 for the 2:3 sheet. They scale with the sheet's size, and neighbouring boxes are 48 px apart. The square sheet holds the first seven elements. The 2:3 sheet holds the same seven at the same places and the other eight in a band below them. `ui-kit` reads a sheet's shape to know which: square or 2:3, each within 1 %; any other shape is refused. So a square sheet drawn before the 2:3 sheet existed is cut, measured and packed exactly as before.--| Element | Sheet | Box (x, y, w, h) | Stretch | Padding | What to draw |-|---|---|---|---|---|---|-| `panel` | both | 48, 48, 576, 400 | `xy` | measured | a large frame with an empty centre |-| `button` | both | 672, 48, 304, 128 | `xy` | measured | a wide button, normal state |-| `button_pressed` | both | 672, 224, 304, 128 | `xy` | measured | the same button, pressed |-| `card` | both | 704, 400, 272, 576 | `xy` | measured | a tall card frame with an empty centre |-| `hp_bar_frame` | both | 48, 496, 608, 112 | `x` | measured | an empty horizontal health bar frame |-| `xp_bar_frame` | both | 48, 656, 608, 112 | `x` | measured | an empty horizontal experience bar frame |-| `timer_badge` | both | 48, 816, 160, 160 | `none` | measured | a small round badge with an empty centre |-| `hp_bar_fill` | 2:3 | 48, 1024, 608, 64 | `x` | `0` | the health bar's fill alone, a bare strip of colour ([fills](#fills)) |-| `xp_bar_fill` | 2:3 | 48, 1136, 608, 64 | `x` | `0` | the experience bar's fill alone, the same kind of strip |-| `slot` | 2:3 | 48, 1248, 192, 192 | `xy` | measured | a square item slot frame with an empty centre |-| `badge` | 2:3 | 288, 1248, 176, 112 | `xy` | measured | a small counter plate with an empty centre |-| `pip_on` | 2:3 | 512, 1248, 96, 96 (circle) | `none` | `0` | a small round indicator dot, lit |-| `pip_off` | 2:3 | 512, 1392, 96, 96 (circle) | `none` | `0` | the same dot unlit |-| `joystick_base` | 2:3 | 704, 1024, 272, 272 (circle) | `none` | `0` | a round touch joystick base |-| `joystick_knob` | 2:3 | 768, 1344, 144, 144 (circle) | `none` | `0` | the joystick's round knob |--`stretch` is how a game may resize the element: `xy` as a nine-slice, `x` in width only (a three-slice), `none` not at all. Round parts (`timer_badge`, the pips, the joystick base and knob) are `none`, so they are only ever drawn at their own proportions. `stretch` belongs to the layout, not to the measurement; so does whether padding is measured: an element that holds no content (a fill, a pip, a joystick part) gets a padding of `0` on every side. The two pips have boxes of one size, so a row of dots can swap one for the other in place. The seven elements on both sheets are required, and the eight on the 2:3 sheet alone are optional ([missing elements](#missing-elements)).--The guide draws the pips and the joystick base and knob as the circles their boxes hold, and asks for them as circles with nothing square around them. A model may still draw a round part on a square plate that fills its box, so the splitter checks: when more than a quarter of the area outside the ellipse a round part's cut holds (the ellipse touching the cut's four sides) is opaque, at alpha 128 or more, the report is `needs-review` with `<element>: its corners are filled`. Regenerate the sheet; a plate behind a dot or a joystick shows as a square in the game. The timer badge keeps the square sheet's box and is not checked, so square sheets cut as they always have.--## Split the sheet--```bash-sprite-gen ui-kit --sheet uikit.png --out-dir ui/-```--The command writes `ui/<element>.png` for every element the sheet's layout holds (but a [missing](#missing-elements) one) and `ui/ui-kit.json`. Options:--* `--alpha-floor N` (default `64`, `0` turns it off) and `--alpha-edge N` (default `2`): the [alpha cleanup](#alpha-cleanup) that runs before anything is cut.-* `--report PATH`: write the JSON report elsewhere (default `<out-dir>/ui-kit.json`); it must end in `.json`, and outside `--out-dir` it must be a path that does not exist yet. Each element's `file` in it then leads from the report's directory to the PNG in `--out-dir`.--A kit is written whole into a new directory. `--out-dir` must not exist yet, or be an empty directory; one that holds anything, an earlier kit or any other file, is refused with its name and what it holds, and left as it was. Write each kit into a directory of its own, or remove the old one first. The command never changes the sheet, and a refused sheet writes nothing.--The kit (every element PNG, and the report when it is in `--out-dir`) is written into a hidden directory beside `--out-dir`, `.<name>.ui-kit-<random>`, which then takes `--out-dir`'s name in one rename. A report outside `--out-dir` is written to a hidden temp file beside it first and given its own name after the rename, in a step that fails when that name has been taken, so no run replaces another's report.--One step publishes the kit: that rename, or with the report outside `--out-dir`, the step that gives the report its name. A run that fails, or is stopped with Ctrl-C, before that step removes everything it made: the kit, the directories it created, its hidden directory and temp file; an empty `--out-dir` it was given is left empty. Stopped after that step, the command still exits with the interruption, but the kit is published: the run removes nothing but its temp file, and the whole kit and its report stay. So `--out-dir` holds either nothing or the whole kit, never part of one, and a report never names a PNG that is not there. When two runs write into one new `--out-dir`, the one whose kit lands second is refused and removes its own; the same holds for two runs and one outside report.--A run that is killed, rather than failing, cannot clean up after itself:--* It can leave its hidden `.<name>.ui-kit-<random>` directory beside `--out-dir`, or a hidden `.<report>.<random>.tmp` file beside an outside report, and the directories it created; remove them. Under `--out-dir`'s own name it never leaves anything but the whole kit.-* With the report outside `--out-dir`, a run killed between the rename and the step that publishes the kit leaves the whole kit in `--out-dir` and no report. Remove the directory and run again.-* On Windows, a rename takes no existing directory's name, not even an empty one's, so an empty `--out-dir` is removed just before the rename (a run that fails puts it back). A run killed at that moment leaves no `--out-dir`.-* A run that is interrupted again while it is removing what it made (for example, a second Ctrl-C during that clean-up) cannot finish the clean-up either. It can leave the same things a killed run leaves: its hidden staging directory or hidden report temp file beside the output, the directories it created, with an outside report the whole kit without its report, and on Windows no `--out-dir`. It never leaves part of a kit under `--out-dir`'s own name: `--out-dir` holds nothing or the whole kit.--The steps of the cut:--1. **Alpha cleanup.** Faint haze between elements would join them, so it is cleared first (below).-2. **Parts.** Pixels with alpha above zero form 8-connected parts. A part smaller than 16 pixels is dropped and counted.-3. **Assignment.** The drawing is read once ([reading the drawing](#reading-the-drawing)). A reading puts each part in the first box, in layout order, whose moved box, widened by half the gap, holds its centroid, or in no box. A part in no box is reported under `unassigned` and makes the report `needs-review` when it has at least 16 pixels. Every refusal comes from the same reading.-4. **Crop.** An element is the bounding box of its box's parts, so ornaments that reach past the box stay whole. A box with no part fails the command when its element is required (the sheet has to be generated again), and leaves its element out when it is optional ([missing elements](#missing-elements)).-5. **Insets** and **padding** are measured on the cropped element (below).--### Reading the drawing--A drift is (sx, tx, sy, ty): it moves each layout box (x, y, w, h), scaled to the sheet, to (x · sx + tx, y · sy + ty, w · sx, h · sy). Offsets are in the sheet's pixels. Along each axis, the drift a cut accepts is a scale from 0.9 to 1.1 and an offset of at most 96 px at 1024 (48 px on a 512 px wide sheet). The cut considers the drifts within that range and a quarter of it beyond either end: a scale from 0.875 to 1.125 and an offset of at most 120 px at 1024. A drawing drawn at the edge of the accepted range is read under its own drift, and a reading just beyond the edge still counts as a rival.--A reading at a drift assigns each part (an 8-connected part of 16 pixels or more, after the alpha cleanup) to the first box, in layout order, whose moved box widened by half the gap (24 px at 1024, the widening scaled with the box) holds the part's centroid, or to no box. A reading is valid when every frame's box (the seven required elements) holds a part.--A reading's cost, in pixels: each part in a box adds, for each of its four sides, how far that side falls short of lying 1 px inside the moved box (0 when it does: the guide asks for each element inside its box, without touching the box's edges). Each part in no box adds half the gap + 1 px + half its smaller extent (its bounding box's smaller side). That is about the least a part of its size costs against a box whose widened box does not hold its centroid. It is the same under every drift, so a part in no box never pulls the reading, and it grows with the part, so leaving a large element that overflows its box out of every box never costs less than keeping it. Two readings whose costs differ by at most 1 px fit the drawing equally well.--One search finds the least cost of any reading under the drifts the cut considers, and the least cost of a valid reading. The candidates: when the least valid cost is within 1 px of the least cost, the valid readings within 1 px of the least valid cost. Otherwise, every reading within 1 px of the least cost (then none of them is valid). The sheet is cut as its one candidate when no refusal in the list below applies; two or more candidates refuse it as ambiguous (refusal 3) unless an earlier refusal applies. Everything the cut reports and every refusal comes from that one result: there is no second notion of the reading.--Refusals happen in this order (in every case `ui-kit` writes nothing and fails; each refusal is a `ValueError` whose `reason` is the word in parentheses):--1. Drifted further (`drifted`): the cheapest candidate costs more than 1 px (no drift the cut considers keeps the parts clear of their boxes' edges); the least-squares fit of the layout's box centres to the centres of what each of its boxes holds (the bounding box of the box's parts; along an axis on which every such box is centred on one line, an offset alone) lies outside 0.875–1.125 / 120 px at 1024; and at that fit the drawing, read afresh, costs more than 1 px less than the cheapest candidate. So the refusal says something about the drawing, not only about a fit: for a small or off-centre drawing a fit alone means little. Message: `the drawing drifted further from the layout than a cut accepts: fitted to it, the layout is scaled 1.000 along x and 0.800 along y and offset 0.0, 0.0 px, where a cut accepts a scale from 0.9 to 1.1 and an offset of at most 96 px along each axis; generate the sheet again` (the numbers are the fit's).-2. Required frame (`required`): the candidates are not valid. The refusal names the frames whose boxes are empty in every candidate: `<element>: its box holds no element; generate the sheet again`, for several `panel, card: their boxes hold no element; generate the sheet again`. What it means: no reading within 1 px of the best holds a part in that box. On a sheet whose frame was not drawn, that is literally so; on a sheet with stray marks (see below), the cheapest readings may leave out a tiny frame to place the marks. When no frame is empty in every candidate, the sheet is refused as ambiguous (the next refusal) instead.-3. Ambiguous (`ambiguous`): the candidates put some part in different boxes. The refusal names the boxes whose contents differ, in layout order: `pip_on: under another drift the cut accepts, the drawing fits the layout at least as well (to within 1 px) with this element named differently, so it does not say which element it is; generate the sheet again`, and for several `pip_on, pip_off: under another drift the cut accepts, the drawing fits the layout at least as well (to within 1 px) with these elements named differently, so it does not say which elements they are; generate the sheet again`. Readings are compared on every part's box, not only on the elements' names: each element is cut as the bounding box of its parts, so two readings that keep every name but put one small part in another element's box would cut different rects. The exception carries the two readings (`witnesses`): each its drift and the box of every part.-4. Off-centre (`off-centre`): no drift whose cost is within 1 px of the cut's, that keeps the cut's parts in their widened boxes, puts the centre of each box's parts' bounding box inside the moved box. The refusal names the boxes whose parts are centred outside them at the cut's least-cost drift: `pip_on: its box holds a part centred outside it (in the gap beside it or further, so the drawing does not say which element it is); generate the sheet again`, for several `pip_on, badge: their boxes hold parts centred outside them (in the gap beside them or further, so the drawing does not say which elements they are); generate the sheet again`.-5. Off the layout (`off-layout`): the search reached its work bound, 6000 spans of drifts, having proven that every reading costs more than 1 px: `the drawing does not lie on the layout under any drift a cut accepts: every reading leaves its parts at least N px across their boxes' edges or in no box; generate the sheet again`, N the proven least cost rounded down. A drawing whose parts lie inside their boxes has a reading of cost 0, so it is never refused this way. The bound is a count of spans, not a time, set well above what drawn sheets need.--When the drawing is cut, each element is the bounding box of its box's parts, so ornaments that reach past the box stay whole. Parts in no box are reported under `unassigned` and make the report `needs-review`. `missing` lists the optional elements whose boxes are empty.--The report's drift is the first of these that reads the drawing as the cut does, at a cost within 1 px of the cut's: the layout's own boxes (then the report has no `layout_fit` and each `box` is the layout's box, so a sheet drawn on its guide is reported exactly as before); the least-squares fit of the cut (the fit described in refusal 1); the centring drift found for refusal 4; the cut's least-cost drift. Each element's `box` is its layout box moved by that drift, and `layout_fit` gives the drift.--The guarantee: take a sheet whose parts all lie at least 1 px inside their boxes under some drift within the accepted range, with all seven frames drawn. It is cut exactly as drawn: each part under the name of the box it was drawn in, and `missing` exactly the band elements not drawn. Or it is refused as ambiguous, and the refusal names two readings that fit within 1 px and put the parts differently. It is never refused for another reason and never cut otherwise, and a cut is never one of two readings within 1 px. Why, briefly: the drawn reading costs 0, so the least cost and the least valid cost are 0, and every candidate is a valid reading with every part inside its box; the drifted and off-layout refusals need a least cost above 1 px; the required refusal needs no valid candidate, and the drawn reading is one; the off-centre refusal needs no centring drift, and the drawn drift centres every box's parts, since each part lies inside its box.--Outside the guarantee: a sheet with parts that lie in no box under the drift it was drawn with (stray marks, specks in the gaps) is outside the guarantee. There the drawing alone does not say what was meant: a tiny element that some drift leaves in a gap and a stray mark that some drift places in a box look the same, and no rule that sees only the drawing can tell them apart. The cut prefers the reading that places parts in boxes (a part in no box costs more than any part inside its box), which keeps every drawing inside its boxes exact. On a sheet with stray marks, a mark within reach of a box may be cut as an element or joined to one, or the cheapest readings may leave out a tiny frame to place the marks, so the sheet is refused for that frame. Whatever the outcome, it is still the one reading within 1 px of the least cost, and every refusal's condition holds. Clear stray marks from the sheet, or generate it again.--The search is exact: no grid and no sampling. It is a best-first branch and bound over the drifts the cut considers. A span of drifts is bounded below by the least each part can cost in it. It is split across its widest side, and solved whole once its undecided parts can be read in only a few ways: each way's cost is then convex and piecewise linear along each axis, and least at a corner. "Within 1 px" means within 1 px. The search stops early once it has found two valid readings that cost 1 px or less (the drawing is ambiguous whatever else there is). It stops at its work bound only once every reading is proven to cost more than 1 px.--The tests (all synthetic sheets):--* The two-way sheet: 2:3 (512 × 768 px), seven frames drawn small (20 × 8 px), each inside its box both where the layout puts it and with the layout squeezed to 0.9 from the top edge, and one dot centred on `pip_on`'s box (also `pip_off`'s box squeezed to 0.9), with an 18 px dot and a dot 60 px wide; refused as ambiguous by `split_ui_kit` and by the CLI, which writes nothing.-* The control: frames 96 % as wide and 55 % as tall as their boxes squeezed to 0.9, each inside that squeezed box, and the dot of `pip_off` alone in the band at `pip_off`'s squeezed centre: cut as `pip_off`.-* 512 sheets of small drawings (each element a rectangle a random share of its box across, from a twentieth to nine tenths, anywhere inside its moved box at least 1 px clear of its edges, under a drift picked at random within the accepted range, with a random set of band elements left out) and 256 sheets of full-size frames with such small band drawings: each is cut exactly as drawn, or refused as ambiguous, and then the test checks both readings the refusal names with its own evaluation of the reading at each drift: it reads the drawing as the refusal says, every frame holds a part, it costs at most 1 px, and the two differ. No other refusal passes.-* Three of those sheets, which the earlier cut refused as drifted further although each fits the layout one way, are cut as drawn, by the CLI too.-* Each of the 256 sets of band elements that can be left out, on a sheet whose elements fill most of their boxes, under a random accepted drift: exactly the elements not drawn are missing, every drawn element is cut as itself, and a `layout_fit` is the drift drawn to within a hundredth in scale and 4 px in offset.-* A sheet squeezed from the top by 0.90 to 0.99 with three band elements left out names exactly those missing.-* A counterexample search, which proves nothing when it finds none: on 17 sheets, thousands of drifts at random (uniform over the drifts the cut considers, and near the drift drawn and the cut's), evaluated by the test itself. None reads the drawing at a lower cost than the least the cut found, and for a cut sheet no valid reading within 1 px of the least valid cost reads it otherwise.-* Still refused with their own reasons: a sheet drawn 20 % shorter (drifted further), the lit dot drawn into the gap below its box (off-centre, named by the box whose widened box holds it), each frame left out (required).-* The gap between the boxes of the two dots (`pip_on` above, `pip_off` below) is exactly twice the reach (half the gap is the widening), so their widened boxes touch: under every drift that keeps a mark inside the dots' columns, the mark's centroid lies in one of the two widened boxes. The test draws a 2:3 sheet on its guide and a mark 4 px wide and 20 px tall centred in that gap. In no box it would cost less than in either dot's box, but no drift reads it in no box, so no such reading is cut or named. The two readings that put it in a dot's box fit the sheet equally well: the sheet is refused as ambiguous (`pip_on, pip_off`), and each of the two readings the refusal names reads the sheet as it says (checked by the test's own evaluation), with the mark in a box.-* A sheet whose elements are 4 px squares (16 px, the smallest part kept), each anywhere inside its moved box, with about half the band left out and sixty more such squares scattered over the sheet, is decided within 10 seconds: most squares lie in no box under any drift, and the search proves every reading costs more than 1 px within its work bound and refuses it as off the layout.-* A square sheet and a 2:3 sheet drawn on their guide are cut byte for byte as before, with no `layout_fit`.--## Missing elements--The seven frames are the kit, and each is required: `panel`, `button`, `button_pressed`, `card`, `hp_bar_frame`, `xp_bar_frame` and `timer_badge`. When a frame's box is empty in every candidate ([reading the drawing](#reading-the-drawing)), `ui-kit` writes nothing and fails with `<element>: its box holds no element; generate the sheet again`, or, for several, `panel, card: their boxes hold no element; generate the sheet again`. That means no reading within 1 px of the best holds a part in that box; when no frame is empty in every candidate, the sheet is refused as ambiguous instead.--The eight elements of the 2:3 band are optional: the two fills, the slot, the badge, the two dots and the joystick base and knob. When one's box is empty, the kit is made without it:--* It has no PNG and no entry in `elements`. The report names it under `missing`, in layout order. A 2:3 report always has `missing` (`[]` when nothing is missing); a square report has none, as before, since a square sheet's elements are all required.-* The command exits `0`, and its line ends with `; missing, left out of the kit: pip_off`.-* A missing element is not a measurement to review: `status` and `review_reasons` are about the elements that are there.-* [`game-pack`](game-pack.md#version-2-manifest) packs the elements the report has, so a missing element has no `ui.nine_slice` entry, and a game falls back for exactly that part. A game that needs both dots, or both joystick parts, falls back for both when one of them is missing.--The whole kit is drawn in one image call, so a model that leaves one box of the band empty costs that element, not the kit. Generate the sheet again to get it.--## Insets--Insets are measured only along the axes the layout lets the element stretch; the others are `0`. Along x (columns; y is the same with rows):--1. Colours are taken premultiplied by alpha, with alpha as a fourth channel, in 8-bit units.-2. The reference band is the middle fifth of the columns (from 40 % to 60 % of the width). The reference column is the per-row median over that band.-3. A pixel deviates when its largest channel difference from the reference column, in its row, exceeds twice the largest difference found in the reference band in that row, plus 8.-4. A column with no deviating pixel is plain. The stretch band is the run of plain columns that contains the reference band.-5. `left` is the band's first column plus a 2 px margin, and `right` is the distance from the band's end to the right edge plus 2 px; a side with no deviating column at all gets `0`. An inset never reaches into the reference band.--So every column with an ornament, a cap, a border line or their anti-aliased edge lies inside a fixed slice, and the stretched middle holds only columns that look like the middle of the element. Two cases make the report `needs-review`, naming the element and the axis: an ornament that reaches the reference band (the band could not grow on that side), and a reference band that is not uniform itself, so an ornament probably sits in the middle of an edge (in some row its largest difference exceeds both 64 and four times the median over the rows). A frame with an ornament in the middle of an edge cannot be nine-sliced; regenerate it.--## Padding--Padding places the content (text, a card's contents, a bar's fill, a badge's digits, a slot's icon). It is measured for the elements the [layout](#layout) marks `measured`; the others get `0` on every side. On the element's middle five rows, take the per-column median. The interior is the run of columns around the centre that continues while each step to the next column changes no channel by more than 16 and every column stays within 96 of the centre (the median of the central 5 × 5 pixels): a smooth gradient on a button face stays interior, a border's sharp edge ends it. The same on the middle five columns gives the interior rows. A pixel counts as interior when every channel lies within 16 of the range those two runs cover; when a corner of the rectangle is not interior (a round badge, an ornament reaching inward), the rectangle shrinks evenly toward the centre until all four corners are. Each padding is the distance from an element edge to that rectangle, plus 2 px. A content area narrower or shorter than a quarter of its element makes the report `needs-review`: the centre was probably not empty.--## Fills--`hp_bar_fill` and `xp_bar_fill` go inside `hp_bar_frame` and `xp_bar_frame`: in the frame's content rectangle, the rectangle its [padding](#padding) leaves (`x = padding.left`, `y = padding.top`, `w = size.w - padding.left - padding.right`, `h = size.h - padding.top - padding.bottom`, in the frame's pixels). The image model draws a fill at its own size, so its report entry says how it fits:--```json-"hp_bar_fill": {- "...": "...",- "stretch": "x",- "insets": { "left": 14, "right": 14, "top": 0, "bottom": 0 },- "padding": { "left": 0, "right": 0, "top": 0, "bottom": 0 },- "inside": { "element": "hp_bar_frame", "rect": { "x": 46, "y": 30, "w": 520, "h": 52 }, "scale": 0.928571 }-}-```--* `inside.element` is the frame and `inside.rect` its content rectangle.-* `inside.scale` (`rect.h / size.h`, rounded to six decimals) resizes the fill, ends and insets with it, to exactly the rectangle's height. Never resize a fill by a second factor for its width: it is a three-slice, so its ends keep their shape and its middle stretches.-* Drawn `rect.w` wide at `rect.x`, `rect.y` from the frame's top-left corner, a full fill covers the content rectangle to the pixel and never reaches past it. A fraction `f` of a bar is the fill drawn `f × rect.w` wide from the rectangle's left edge. Below its two ends' width (`insets.left + insets.right`, times `scale`), a three-slice cannot shrink: show its left part instead.-* When the two ends, scaled, are at least as wide as the content rectangle, a full bar would overflow it, and the report is `needs-review` naming the fill and its frame.--[`game-pack`](game-pack.md#version-2-manifest) does this sizing for you: it stores each fill at its frame's content rectangle.--## Alpha cleanup--Transparent sheets from image models often carry a faint alpha haze: barely visible pixels around and between the drawn objects. The cleanup is shared by `ui-kit` and [`slice-sheet --alpha-floor`](sheet-slicing.md#transparent-sheets) (`sprite_gen.frames.alpha_floor.clear_haze`).--* A pixel at or above the floor (`--alpha-floor`) is solid. A pixel above zero and below the floor is faint.-* A faint pixel within `--alpha-edge` pixels (8-connected, so diagonals count) of a solid pixel is part of an object's anti-aliased edge and is kept unchanged.-* Every other faint pixel is haze and becomes fully transparent (`0, 0, 0, 0`). A pixel that was already fully transparent is left as it was.--Solid pixels and edge pixels are never changed, so a stroke stays whole as long as some of its pixels reach the floor. A stroke drawn entirely below the floor is indistinguishable from haze and is removed: lower the floor for very faint art. The report measures instead of asserting: it counts what actually changed.--| Field | Meaning |-|---|---|-| `floor`, `edge_px` | the settings |-| `pixels` | pixels in the image |-| `faint_fraction_before`, `faint_fraction_after` | share of all pixels with alpha from 1 to `floor - 1`, before and after |-| `haze_fraction_before`, `haze_fraction_after` | share of all pixels that are faint and farther than `edge_px` from a solid pixel |-| `cleared_pixels` | pixels made transparent |-| `changed_solid_pixels`, `changed_edge_pixels` | solid and kept-edge pixels whose value changed; `0` unless the cleanup is wrong |--## Report--`ui-kit.json`:--```json-{- "kind": "sprite-gen-ui-kit",- "version": 1,- "sheet": "/abs/path/uikit.png",- "sheet_size": [1024, 1024],- "status": "pass",- "review_reasons": [],- "alpha_cleanup": { "floor": 64, "edge_px": 2, "...": "..." },- "dropped_parts": 3,- "unassigned": [],- "elements": {- "panel": {- "file": "panel.png",- "box": { "x": 48, "y": 48, "w": 576, "h": 400 },- "rect": { "x": 52, "y": 50, "w": 570, "h": 396 },- "size": { "w": 570, "h": 396 },- "stretch": "xy",- "insets": { "left": 112, "right": 110, "top": 92, "bottom": 90 },- "padding": { "left": 40, "right": 40, "top": 38, "bottom": 38 },- "parts": 1- }- }-}-```--`box` is the layout box scaled to this sheet (its moved box when the report has `layout_fit`) and `rect` the element's bounding box, both in sheet pixels. A fill also has [`inside`](#fills); no other element has it. `file` is the element PNG's path from the report's own directory, with `/` separators: `panel.png` when the report is in `--out-dir` (the default), `../elements/panel.png` for `--out-dir elements --report reports/kit.json`. A reader joins it to the report's directory, as [`game-pack`](game-pack.md#version-2-request) does, so a report and its elements move together. `size`, `insets` and `padding` are in pixels of the element PNG. Elements appear in layout order. `status` is `needs-review` when any `review_reasons` apply; the PNGs are written either way, so the elements can be inspected.--A 2:3 report also has `missing`, the optional elements whose boxes were empty, in layout order ([missing elements](#missing-elements)). When the layout was moved to read the drawing ([reading the drawing](#reading-the-drawing)), the report has `layout_fit`, after `missing` and before `elements`; for a synthetic 1024 × 1536 sheet drawn 7 % shorter than its guide:--```json-"layout_fit": { "scale": { "x": 1.0, "y": 0.9298 }, "offset": { "x": 1.0, "y": 0.7 } }-```--A layout box at (x, y, w, h), scaled to the sheet, is moved to (x · scale.x + offset.x, y · scale.y + offset.y, w · scale.x, h · scale.y). `offset` is in sheet pixels, rounded to a tenth; `scale` is rounded to four decimals.--Like every measurement here, `pass` means the numbers found nothing to flag. Look at the elements stretched to a few sizes before shipping them.--## Python API--* `sprite_gen.frames.ui_kit.split_ui_kit(image, *, alpha_floor=64, alpha_edge=2) -> (elements, report)`: the elements as images by name, and the report as written to its default place, `<out-dir>/ui-kit.json` (each `file` is `<element>.png`), without `sheet`. A missing optional element is in neither. The least cost of a cut sheet is not in the report. `split_ui_kit` raises `sprite_gen.frames.ui_kit.Refusal`, a `ValueError`, for every refusal of the cut. Its message is the refusal's. `reason` is one of `drifted`, `required`, `ambiguous`, `off-centre`, `off-layout`. `least` is the least cost of a reading the search found, or for `off-layout` the cost every reading is proven to exceed. `parts` are the parts read. For `ambiguous`, `witnesses` holds the two readings (each a `Reading`: `drift` (sx, tx, sy, ty), `boxes`, the box of each part of `parts` by name, None for none, and `cost`). The shape refusal (neither square nor 2:3) stays a plain `ValueError`, as before.-* `sprite_gen.frames.ui_kit.report_file(report, png) -> str` and `element_path(report, file) -> Path`: the `file` a report at `report` gives an element PNG, and the PNG a report's `file` names.-* `sprite_gen.frames.ui_kit.measure_insets(image, stretch) -> (insets, notes)` and `measure_padding(image) -> (padding, notes)`: the measures above on one element image, with the review notes they raise.-* `sprite_gen.frames.ui_kit.content_rect(record)` and `fit_inside(fill, frame, name) -> (inside, note)`: an element record's content rectangle, and a fill's `inside` with its review note.-* `sprite_gen.frames.ui_kit.sheet_layout(size) -> (reference_size, slots)`: the layout a sheet of that size holds; a `ValueError` for a shape that is neither square nor 2:3. Each slot's `optional` says whether a sheet may leave it out.-* `sprite_gen.frames.ui_kit.boxes(size)`, `draw_guide(path, size)` and `guide_text(size)`: the boxes a sheet of that size holds, the guide image and its prompt paragraph (`size` defaults to the square sheet).-* `sprite_gen.frames.alpha_floor.clear_haze(image, *, floor=64, edge=2) -> (image, report)`.diff --git a/pyproject.toml b/pyproject.tomlindex a6d6f07..3cb729d 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -112,4 +112,4 @@ include = ["sprite_gen*"]# not feared: adding curator/src/deep/new.js under the old patterns built a wheel without it.# `curator/**/*` derives the answer from the filesystem, the same fix as packages.find above.[tool.setuptools.package-data]-sprite_gen = ["serve/curator/**/*", "serve/composer/**/*", "audio/*.mjs", "video/*.mjs"]+sprite_gen = ["serve/curator/**/*", "serve/composer/**/*", "video/*.mjs"]diff --git a/sprite_gen/__init__.py b/sprite_gen/__init__.pyindex e0b2166..852a97c 100644--- a/sprite_gen/__init__.py+++ b/sprite_gen/__init__.py@@ -11,7 +11,6 @@ from sprite_gen import _deps as _deps # noqa: F401__all__ = ["spec", # run dir IO, request/layout, migrations"gen", # provider-backed image generation- "audio", # provider-backed sound generation and browser exports"frames", # sheet -> frames extraction (+ inverse unpack)"curate", # curation decisions / sidecar / anchors"compose", # bake atlas / cycle / gif / exportdiff --git a/sprite_gen/_modules.py b/sprite_gen/_modules.pyindex 0b37dc7..3f1424c 100644--- a/sprite_gen/_modules.py+++ b/sprite_gen/_modules.py@@ -6,7 +6,6 @@ the reorg tooling. Keep in sync with the physical folder layout."""MODULE_DOMAIN = {- 'sound': 'audio','guide': 'workflow','preferences': 'workflow','capabilities': 'workflow',@@ -49,7 +48,6 @@ MODULE_DOMAIN = {'cutout': 'frames','segment': 'frames','slice_sheet': 'frames',- 'ui_kit': 'frames','logo_matte': 'frames','alpha_floor': 'frames','check_visible_magenta': 'frames',@@ -57,7 +55,6 @@ MODULE_DOMAIN = {'curation': 'curate','anchor': 'curate','compose_atlas': 'compose',- 'game_pack': 'compose','compose_cycle': 'compose','compose_gif': 'compose','export_pngs': 'compose',@@ -85,7 +82,6 @@ MODULE_DOMAIN = {DOMAINS: list[tuple[str, str]] = [("workflow", "Start here — image or sprite choices, access checks, saved defaults"),("gen", "Generation — prepare a run, generate stills / rows / clips"),- ("audio", "Audio — named effects, music, loop processing and browser exports"),("video", "Video → loop — canvas, keyed frames, seamless cycle, batch"),("frames", "Frames — chroma/white removal, row extraction, sheet slicing, atlas unpacking"),("curate", "Curation — direction anchors and the curation sidecar"),@@ -113,8 +109,8 @@ PIPELINES: list[dict[str, object]] = []TOOL_GROUPS: list[dict[str, object]] = [- {"key": "C", "name": "utilities", "verbs": ["cutout", "slice-sheet", "ui-kit", "unpack-atlas"],- "chain": "cutout · slice-sheet · ui-kit · unpack-atlas (each stands alone)", "doc": "docs/sheet-slicing.md"},+ {"key": "C", "name": "utilities", "verbs": ["cutout", "slice-sheet", "unpack-atlas"],+ "chain": "cutout · slice-sheet · unpack-atlas (each stands alone)", "doc": "docs/sheet-slicing.md"},{"key": "D", "name": "post-processing", "verbs": ["recolor", "recolor-palette", "breathe", "export-pngs", "export-aseprite"],"chain": "recolor · breathe · export-pngs · export-aseprite", "doc": "docs/recolor.md"},{"key": "E", "name": "asset tools", "verbs": ["background-tile", "shadow", "inspect-motion"],diff --git a/sprite_gen/audio/__init__.py b/sprite_gen/audio/__init__.pydeleted file mode 100644index c7a7365..0000000--- a/sprite_gen/audio/__init__.py+++ /dev/null@@ -1,2 +0,0 @@-# SPDX-License-Identifier: Apache-2.0-"""Game audio generation, durable request cache and browser exports."""diff --git a/sprite_gen/audio/cache.py b/sprite_gen/audio/cache.pydeleted file mode 100644index 46e2935..0000000--- a/sprite_gen/audio/cache.py+++ /dev/null@@ -1,38 +0,0 @@-# SPDX-License-Identifier: Apache-2.0-"""SQLite claim before POST, atomic audio receipt after POST. No expiring paid-request lease."""-from __future__ import annotations--from contextlib import closing-import hashlib-import json-from pathlib import Path-import sqlite3---def digest(document):- return hashlib.sha256(json.dumps(document, sort_keys=True, separators=(',', ':'), allow_nan=False).encode()).hexdigest()---def obtain(path, document, make, *, prepare=None):- path = Path(path)- path.parent.mkdir(parents=True, exist_ok=True)- key = digest(document)- with closing(sqlite3.connect(path, timeout=30)) as db:- db.execute('CREATE TABLE IF NOT EXISTS audio (id TEXT PRIMARY KEY, audio BLOB, metadata TEXT)')- # The committed NULL receipt is a durable in-flight/unknown outcome. Another process,- # a crash or a timeout cannot turn it into an automatic second purchase.- with db:- db.execute('BEGIN IMMEDIATE')- row = db.execute('SELECT audio, metadata FROM audio WHERE id=?', (key,)).fetchone()- if row is not None:- if row[0] is None:- raise ValueError(f'sound request {key} is unresolved (in progress or failed); inspect the provider request before any new purchase')- return bytes(row[0]), json.loads(row[1]), True- if prepare is not None:- prepare()- db.execute('INSERT INTO audio(id) VALUES (?)', (key,))- audio, metadata = make()- with db:- db.execute('UPDATE audio SET audio=?, metadata=? WHERE id=?',- (audio, json.dumps(metadata, allow_nan=False), key))- return audio, metadata, Falsediff --git a/sprite_gen/audio/manifest.py b/sprite_gen/audio/manifest.pydeleted file mode 100644index 474f783..0000000--- a/sprite_gen/audio/manifest.py+++ /dev/null@@ -1,91 +0,0 @@-# SPDX-License-Identifier: Apache-2.0-"""Validated playback metadata and file digests for a sound bundle."""-from __future__ import annotations--import hashlib-import json-import math-from pathlib import Path-import re--from sprite_gen.audio import playback, processing--# A sound bundle's kind and its audio kinds, each written once: `sound` writes them into sound.json and offers-# the audio kinds as --kind, `load` reads them back, `provider` asks ElevenLabs for one.-KIND = 'sprite-gen-sound'-SFX, BGM = AUDIO_KINDS = ('sfx', 'bgm')---def event_name(value):- if not isinstance(value, str) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}', value):- raise ValueError('event requires 1 to 128 letters, digits, dots, colons, dashes or underscores')- return value---def _number(value, name, low, high):- if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or not low <= value <= high:- raise ValueError(f'invalid audio {name}')- return value---def load(path, max_bytes):- path = Path(path).resolve()- value = json.loads(path.read_text())- if not isinstance(value, dict) or value.get('kind') != KIND or value.get('version') != playback.VERSION:- raise ValueError('audio source must be a sprite-gen-sound version 2 manifest')- if value.get('audio_kind') not in AUDIO_KINDS or type(value.get('loop')) is not bool:- raise ValueError('invalid audio kind or loop flag')- frames = playback.validate(value.get('playback'), value['loop'])- duration = playback.duration(frames)- if _number(value.get('duration_seconds'), 'duration', 0, 601) != duration:- raise ValueError('audio duration must be derived from playback frames')- result = {'event': event_name(value.get('event')), 'audio_kind': value['audio_kind'], 'loop': value['loop'],- 'duration_seconds': duration, 'target_lufs': _number(value.get('target_lufs'), 'target LUFS', -36, -9),- 'playback': frames, 'files': {}}- files = value.get('files')- if not isinstance(files, dict) or set(files) != {'ogg', 'm4a'}:- raise ValueError('audio source requires ogg and m4a files')- recipe = value.get('recipe')- version = recipe.get('processing_version') if isinstance(recipe, dict) else None- if type(version) is not int or version not in (3, processing.PROCESSING_VERSION):- raise ValueError('audio source must come from sound processing version 3 or 4; make it again with sprite-gen '- 'sound into a new --out-dir (its cached provider audio is reused)')- if version == 3:- # Version 3 had no peak-limited goal. Its files are measured again here, the way it measured- # them, and must meet their target.- processing.require_programs()- goal = result['target_lufs']- else:- level = value.get('normalization')- if not isinstance(level, dict) or not {'pcm_lufs', 'pcm_true_peak_dbtp'} <= set(level):- raise ValueError('a sound processing version 4 source requires normalization.pcm_lufs and pcm_true_peak_dbtp')- goal = processing.loudness_goal(result['target_lufs'], _number(level['pcm_lufs'], 'PCM LUFS', -70, 0),- _number(level['pcm_true_peak_dbtp'], 'PCM true peak', -100, 0))- payloads, sources, size = {}, {path}, 0- for fmt in ('ogg', 'm4a'):- file = files[fmt]- name = file.get('path') if isinstance(file, dict) else None- if not isinstance(name, str) or not re.fullmatch(r'[A-Za-z0-9_-][A-Za-z0-9_.-]*\.'+fmt, name):- raise ValueError('audio file must be a local filename of the declared format')- source = (path.parent/name).resolve()- if source.parent != path.parent:- raise ValueError('audio source must stay within its bundle')- size += source.stat().st_size- if size > max_bytes:- raise ValueError(f'audio exceeds {max_bytes} bytes')- data = source.read_bytes()- if hashlib.sha256(data).hexdigest() != file.get('sha256'):- raise ValueError('audio file digest does not match its manifest')- record = {'path': name, 'sha256': file['sha256'],- 'duration_seconds': _number(file.get('duration_seconds'), 'file duration', frames['end_frame']/frames['sample_rate'], 602),- 'lufs': _number(file.get('lufs'), 'LUFS', -70, 0),- 'true_peak_dbfs': _number(file.get('true_peak_dbfs'), 'true peak', -100, -1)}- if version == 3:- measured = processing.measure_version_3(processing.file_frames(source, frames, value['loop'])[1], goal)- record.update(lufs=measured['lufs'], true_peak_dbfs=measured['true_peak'])- if not processing.meets(record['lufs'], record['true_peak_dbfs'], goal):- raise ValueError('audio loudness does not match its target or its peak-limited PCM')- result['files'][fmt] = record- payloads[fmt] = data- sources.add(source)- return result, payloads, sourcesdiff --git a/sprite_gen/audio/playback.py b/sprite_gen/audio/playback.pydeleted file mode 100644index 2a52ecc..0000000--- a/sprite_gen/audio/playback.py+++ /dev/null@@ -1,38 +0,0 @@-# SPDX-License-Identifier: Apache-2.0-"""Frame contract and the browser player shipped with every audio pack."""-from __future__ import annotations--import hashlib-from pathlib import Path--VERSION = 2-MIN_PLAYBACK_RATE = 8000-PLAYER_PATH = Path(__file__).with_name('sprite-gen-audio-v2.mjs')---def validate(value, loop):- if not isinstance(value, dict) or value.get('version') != VERSION:- raise ValueError('audio playback requires frame contract version 2')- fields = ('sample_rate', 'start_frame', 'end_frame', 'overlap_frames')- if any(type(value.get(k)) is not int for k in fields):- raise ValueError('audio playback coordinates must be integer frames')- rate, start, end, overlap = (value[k] for k in fields)- if not 8000 <= rate <= 192000 or not 0 <= start < end <= 601*rate:- raise ValueError('invalid audio playback interval')- if (loop and not 2 <= overlap < (end-start)/2) or (not loop and overlap != 0):- raise ValueError('invalid audio playback overlap')- # Reserve 3.5 destination frames: interval truncation (<1), final-loop- # rounding (<=0.5), and a decoder shortfall (1) still leave >=2 blend frames.- if loop and 2*overlap*MIN_PLAYBACK_RATE < 7*rate:- raise ValueError(f'audio playback overlap too short for {MIN_PLAYBACK_RATE} Hz decoding')- return {'version': VERSION, **{k: value[k] for k in fields}}---def duration(value):- return (value['end_frame']-value['start_frame']-value['overlap_frames'])/value['sample_rate']---def player():- data = PLAYER_PATH.read_bytes()- return {'path': PLAYER_PATH.name, 'sha256': hashlib.sha256(data).hexdigest(),- 'export': 'createAudioSource'}, datadiff --git a/sprite_gen/audio/processing.py b/sprite_gen/audio/processing.pydeleted file mode 100644index d37359e..0000000--- a/sprite_gen/audio/processing.py+++ /dev/null@@ -1,250 +0,0 @@-# SPDX-License-Identifier: Apache-2.0-"""EBU R128 normalization and unspliced browser audio encodes."""-from __future__ import annotations--import hashlib-import json-import math-from pathlib import Path-import re-import shutil-import subprocess--from sprite_gen._deps import np--from sprite_gen.audio import playback--RATE = 48000-PROCESSING_VERSION = 4-PCM_PEAK_DBTP = -2.0 # the normalizer's limiter ceiling-FILE_PEAK_DBTP = -1.0 # no encoded file may decode above this true peak-SETTLED = .2 # normalization stops this close (LU) to the target with its peak this close (dB) to the ceiling-TOLERANCE_LU = 1.0 # an encoded file's loudness may sit this far from its goal-BLOCK, HOP = RATE*2//5, RATE//10 # ITU-R BS.1770-4 gating blocks: 400 ms long, one every 100 ms-# ITU-R BS.1770-4 K-weighting at 48 kHz (the high shelf, then the RLB high-pass), filtered in double precision.-K_WEIGHTING = ('aformat=sample_fmts=dblp,'- 'biquad=b0=1.53512485958697:b1=-2.69169618940638:b2=1.19839281085285:'- 'a0=1:a1=-1.69065929318241:a2=0.73248077421585,'- 'biquad=b0=1:b1=-2:b2=1:a0=1:a1=-1.99004745483398:a2=0.99007225036621,'- 'aformat=sample_fmts=flt')---def require_programs():- for name in ('ffmpeg', 'ffprobe'):- if not shutil.which(name):- raise ValueError(f'{name} is required on PATH for sound processing')---def require_tools():- require_programs()- encoders = _ffmpeg(['-encoders']).stdout.decode(errors='replace')- for codec in ('libopus', 'aac'):- if not re.search(r'(?m)^\s*A\S*\s+'+codec+r'\s', encoders):- raise ValueError(f'ffmpeg requires the {codec} encoder before a paid sound request')---def _ffmpeg(args, data=None):- result = subprocess.run(['ffmpeg', '-hide_banner', '-nostdin', '-y', *args],- input=data, capture_output=True, timeout=180)- if result.returncode:- # Source metadata can contain untrusted prose. Keep diagnostics local and bounded.- raise ValueError('ffmpeg audio processing failed; check input audio and codec availability')- return result---def decode(path):- result = _ffmpeg(['-v', 'error', '-i', str(path), '-map', '0:a:0', '-ac', '2', '-ar', str(RATE),- '-f', 'f32le', 'pipe:1'])- samples = np.frombuffer(result.stdout, dtype='<f4').reshape(-1, 2).copy()- if not len(samples) or not np.isfinite(samples).all():- raise ValueError('source has no finite audio samples')- return samples---def _pcm_args():- return ['-f', 'f32le', '-ar', str(RATE), '-ac', '2', '-i', 'pipe:0']---def _check_m4a_duration(path, frames):- result = subprocess.run(['ffprobe', '-v', 'error', '-select_streams', 'a:0',- '-show_entries', 'stream=duration_ts,time_base', '-of', 'json', str(path)],- capture_output=True, timeout=180)- try:- stream, = json.loads(result.stdout)['streams']- except (ValueError, KeyError, TypeError):- stream = None- if (result.returncode or not isinstance(stream, dict) or- (stream.get('time_base'), stream.get('duration_ts')) != (f'1/{RATE}', frames)):- raise ValueError(f'm4a container duration must match the declared {frames} frames at {RATE} Hz')---def _loudnorm(samples, target):- """loudnorm's own first-pass analysis, the parameters of its second pass."""- result = _ffmpeg([*_pcm_args(), '-af', f'loudnorm=I={target}:TP={PCM_PEAK_DBTP:g}:LRA=11:print_format=json',- '-f', 'null', '-'], samples.astype('<f4').tobytes())- matches = re.findall(r'\{\s*"input_i".*?\}', result.stderr.decode(errors='replace'), re.S)- if not matches:- raise ValueError('ffmpeg did not report loudness')- values = json.loads(matches[-1])- return {k: float(v) for k, v in values.items() if k != 'normalization_type'}---def _block_power(samples):- """K-weighted mean square of every complete gating block, summed over both channels."""- result = _ffmpeg([*_pcm_args(), '-af', K_WEIGHTING, '-f', 'f32le', 'pipe:1'], samples.astype('<f4').tobytes())- weighted = np.frombuffer(result.stdout, dtype='<f4').reshape(-1, 2)- hops = np.array([np.square(weighted[i:i+HOP], dtype=np.float64).sum()- for i in range(0, len(weighted) - HOP + 1, HOP)])- # Four 100 ms hops make one 400 ms block; a clip shorter than one block has none.- return (hops[:-3] + hops[1:-2] + hops[2:-1] + hops[3:]) / BLOCK---def _true_peak(samples):- """Sample peak (dBTP) after 4x oversampling to 192 kHz, as loudnorm reports true peak."""- result = _ffmpeg([*_pcm_args(), '-af', 'aresample=192000,astats=measure_perchannel=none:measure_overall=Peak_level',- '-f', 'null', '-'], samples.astype('<f4').tobytes())- peaks = re.findall(r'Peak level dB:\s*(\S+)', result.stderr.decode(errors='replace'))- if not peaks:- raise ValueError('ffmpeg did not report a true peak')- return float(peaks[-1])---def measure(samples, gate=None):- """ITU-R BS.1770-4 integrated loudness (LUFS) and true peak (dBTP) of 48 kHz stereo PCM.-- `gate` is the block selection of the PCM a file was encoded from. The file is then measured- over the same frames and the same blocks as its PCM: a short clip has two or three blocks,- and a codec that moves one of them a tenth of a dB across the relative gate would otherwise- move the file's loudness by whole LU."""- power = _block_power(samples)- if gate is None:- gate = power > 10 ** ((-70 + .691) / 10) # absolute gate, -70 LUFS- if gate.any():- gate &= power > power[gate].mean() / 10 # relative gate, 10 LU under the absolute-gated loudness- elif len(gate) != len(power):- raise ValueError('an encoded file must be measured over the frames of its PCM')- mean = power[gate].mean() if gate.any() else 0.- return {'lufs': -.691 + 10 * math.log10(mean) if mean > 0 else -math.inf,- 'true_peak': _true_peak(samples), 'gate': gate}---def file_frames(path, frames, loop):- """The decoded length of an encoded file, and the frames its loudness is measured over: its- playback frames, three times over for a loop."""- if frames['sample_rate'] != RATE:- raise ValueError(f'sound files are measured at {RATE} Hz frames')- if path.suffix == '.m4a':- _check_m4a_duration(path, frames['end_frame']-frames['start_frame'])- decoded = decode(path)- if len(decoded) < frames['end_frame']:- raise ValueError(f'{path.suffix[1:]} truncated the audio')- interval = decoded[frames['start_frame']:frames['end_frame']] # AAC may retain a final partial codec frame.- return len(decoded), np.tile(interval, (3, 1)) if loop else interval---def measure_version_3(samples, target):- """Loudness and true peak as processing version 3 measured its files: loudnorm's first pass.-- A version 3 bundle keeps no PCM, so its files have no PCM gate to be measured over, and a- block at the relative gate can move this engine's measure across the tolerance where- loudnorm's accepted the file (docs/sound.md)."""- values = _loudnorm(samples, target)- return {'lufs': values['input_i'], 'true_peak': values['input_tp']}---def loudness_goal(target, pcm_lufs, pcm_peak):- """The integrated loudness every encoded file of a sound must reach, within TOLERANCE_LU.-- Normalization gains a sound toward the target until its true peak meets the PCM ceiling. A- sound it leaves short of the target with its peak at that ceiling (a click, a short hit)- cannot get louder without the limiter rewriting its transient, so its files must match the- loudness its PCM reached. Every other sound must reach the target."""- if pcm_lufs < target - SETTLED and pcm_peak >= PCM_PEAK_DBTP - SETTLED:- return pcm_lufs- return target---def meets(lufs, peak, goal):- """The one loudness check of an encoded file."""- return math.isfinite(lufs) and abs(lufs - goal) <= TOLERANCE_LU and peak <= FILE_PEAK_DBTP---def limit_gain(samples, gain, ceiling, loop):- context = np.tile(samples, (3, 1)) if loop else samples- limit = 10 ** (ceiling / 20)- filt = (f'aresample=192000,volume={gain}dB,'- f'alimiter=limit={limit}:level=false:latency=true:attack=1:release=20')- result = _ffmpeg([*_pcm_args(), '-af', filt, '-ar', str(RATE), '-f', 'f32le', 'pipe:1'],- context.astype('<f4').tobytes())- pcm = np.frombuffer(result.stdout, dtype='<f4').reshape(-1, 2).copy()- return pcm[len(samples):2*len(samples)] if loop else pcm[:len(samples)]---def normalize(samples, target, loop):- """The PCM to encode, its manifest `normalization` record, and its measure."""- # Repeated context avoids loudnorm's startup/lookahead envelope at the loop boundary.- source = np.tile(samples, (3, 1)) if loop else samples- if not math.isfinite(measure(source)['lufs']):- raise ValueError('silent or unmeasurable audio cannot be loudness normalized')- measured, output, method = _loudnorm(source, target), samples, 'limiter'- # loudnorm's first pass over some short clips measures its own output at -inf LUFS, so it- # has no second-pass offset; such a clip starts the limiter passes below as decoded.- if all(math.isfinite(measured[k]) for k in ('input_i', 'input_tp', 'input_thresh', 'target_offset')):- filt = (f'loudnorm=I={target}:TP={PCM_PEAK_DBTP:g}:LRA=11:measured_I={measured["input_i"]}:'- f'measured_TP={measured["input_tp"]}:measured_LRA={measured["input_lra"]}:'- f'measured_thresh={measured["input_thresh"]}:offset={measured["target_offset"]}:linear=true')- result = _ffmpeg([*_pcm_args(), '-af', filt, '-ar', str(RATE), '-f', 'f32le', 'pipe:1'],- source.astype('<f4').tobytes())- output = np.frombuffer(result.stdout, dtype='<f4').reshape(-1, 2).copy()- output = output[len(samples):2*len(samples)] if loop else output[:len(samples)]- method = 'loudnorm-two-pass'- corrections = 0- # A short transient can make loudnorm stop at the peak ceiling below the LUFS target.- # Measure the actual playback, then apply gain with an oversampled lookahead limiter.- # These are local DSP passes over the paid source, never provider retries.- while True:- stats = measure(np.tile(output, (3, 1)) if loop else output)- if corrections == 3 or (abs(stats['lufs'] - target) <= SETTLED and- stats['true_peak'] <= PCM_PEAK_DBTP + SETTLED):- break- output = limit_gain(output, target - stats['lufs'], PCM_PEAK_DBTP, loop)- corrections += 1- return output, {'method': method, 'peak_limit_dbtp': PCM_PEAK_DBTP, 'gain_limiter_passes': corrections,- 'pcm_lufs': stats['lufs'], 'pcm_true_peak_dbtp': stats['true_peak']}, stats---def export(source: Path, out_dir: Path, *, target_lufs, loop, crossfade):- samples = decode(source)- frames = playback.validate({'version': playback.VERSION, 'sample_rate': RATE,- 'start_frame': 0, 'end_frame': len(samples),- 'overlap_frames': round(crossfade*RATE) if loop else 0}, loop)- samples, normalization, pcm = normalize(samples, target_lufs, loop)- goal = loudness_goal(target_lufs, pcm['lufs'], pcm['true_peak'])- files = {}- # The twoloop AAC coder rebuilds a limited transient up to several dB over its PCM true peak;- # FFmpeg documents the fast coder as the better one above 64 kbps (docs/sound.md).- for fmt, codec in (('ogg', ['-c:a', 'libopus', '-b:a', '160k']),- ('m4a', ['-c:a', 'aac', '-aac_coder', 'fast', '-b:a', '192k', '-movflags', '+faststart',- '-movie_timescale', str(RATE)])):- path = out_dir / f'sound.{fmt}'- encoded_samples, ceiling = samples, PCM_PEAK_DBTP- for attempt in range(3):- _ffmpeg([*_pcm_args(), '-map_metadata', '-1', *codec, str(path)], encoded_samples.astype('<f4').tobytes())- length, played = file_frames(path, frames, loop)- measured = measure(played, pcm['gate'])- lufs, peak = measured['lufs'], measured['true_peak']- if meets(lufs, peak, goal):- break- if not math.isfinite(lufs) or attempt == 2:- raise ValueError(f'{fmt} failed loudness/peak check ({lufs:g} LUFS, {peak:g} dBTP; needs {goal:g} '- f'+/-{TOLERANCE_LU:g} LUFS at <= {FILE_PEAK_DBTP:g} dBTP); cached source retained')- # Lossy codec reconstruction can overshoot PCM peaks. Tighten the PCM limiter- # by the measured overshoot plus headroom, then encode and measure again.- ceiling -= max(0, peak + 1.5) if peak > FILE_PEAK_DBTP else 0- encoded_samples = limit_gain(encoded_samples, goal - lufs, ceiling, loop)- files[fmt] = {'path': path.name, 'duration_seconds': length/RATE,- 'lufs': lufs, 'true_peak_dbfs': peak, 'encode_passes': attempt + 1,- 'pcm_peak_limit_dbtp': ceiling,- 'sha256': hashlib.sha256(path.read_bytes()).hexdigest()}- return {'files': files, 'duration_seconds': playback.duration(frames), 'playback': frames,- 'normalization': normalization}diff --git a/sprite_gen/audio/provider.py b/sprite_gen/audio/provider.pydeleted file mode 100644index 0dafb35..0000000--- a/sprite_gen/audio/provider.py+++ /dev/null@@ -1,95 +0,0 @@-# SPDX-License-Identifier: Apache-2.0-"""ElevenLabs HTTP contract; retry decisions belong to gen.retry."""-from __future__ import annotations--import json-import math-import re-from urllib.error import HTTPError-from urllib.request import Request, urlopen--from sprite_gen.audio.manifest import AUDIO_KINDS, SFX-from sprite_gen.gen import address, retry-from sprite_gen.gen.base import announce_api_billing, env_api_key-from sprite_gen.gen.xai import error_body, NO_ANSWER--AUTH_ENV = 'ELEVENLABS_API_KEY'-FORMAT = 'mp3_44100_128'-SAFE_CODES = frozenset({*retry.ELEVENLABS_BUSY, 'quota_exceeded',- 'invalid_api_key', 'missing_permissions', 'bad_prompt', 'bad_composition_plan',- 'content_policy_violation', 'unauthorized', 'invalid_request'})---def request(kind, prompt, duration, loop):- if kind not in AUDIO_KINDS:- raise ValueError('kind must be sfx or bgm')- if not isinstance(prompt, str) or not prompt.strip() or len(prompt) > 4100:- raise ValueError('prompt requires 1 to 4100 characters')- duration = float(duration)- low, high = (0.5, 30) if kind == SFX else (3, 600)- if not math.isfinite(duration) or not low <= duration <= high:- raise ValueError(f'{kind} duration must be between {low} and {high} seconds')- if type(loop) is not bool:- raise ValueError('loop must be a boolean')- body = ({'text': prompt, 'duration_seconds': duration, 'loop': loop,- 'model_id': 'eleven_text_to_sound_v2', 'prompt_influence': 0.3} if kind == SFX- else {'prompt': prompt, 'music_length_ms': round(duration * 1000),- 'model_id': 'music_v1', 'force_instrumental': True})- return {'endpoint': 'sound-generation' if kind == SFX else 'music',- 'output_format': FORMAT, 'body': body}---def credential():- # ElevenLabs has no subscription login to prefer: the key is the only route, billed per call.- try:- key = env_api_key(AUTH_ENV, who='sound')- except SystemExit as exc:- raise ValueError(str(exc)) from None- if not key:- raise ValueError(f'{AUTH_ENV} is required for a new sound request')- return key---def _code(body):- detail = body.get('detail') if isinstance(body, dict) else None- code = detail.get('status') if isinstance(detail, dict) else None- return code if isinstance(code, str) and code in SAFE_CODES else None---def generate(document):- key = credential()- req = Request(address.url(address.ELEVENLABS, f"/{document['endpoint']}?output_format={document['output_format']}"),- data=json.dumps(document['body']).encode(),- headers={'xi-api-key': key, 'Content-Type': 'application/json'}, method='POST')-- def send():- try:- with urlopen(req, timeout=600) as response:- return response.status, response.read(), response.headers- except HTTPError as exc:- try:- body = error_body(exc)- except NO_ANSWER:- raise ValueError('ElevenLabs refusal body unavailable; request outcome unresolved; no resubmission') from None- return exc.code, body, exc.headers- except Exception:- # Transport exceptions may include headers or body text. Never print them.- raise ValueError('ElevenLabs response unavailable; request outcome unresolved; no resubmission') from None-- announce_api_billing('elevenlabs', AUTH_ENV, f" ({document['endpoint']}; the audio is cached, so the same "- "request is not bought twice).")- status, body, headers, asks = retry.ask(send, provider=address.ELEVENLABS, who='ElevenLabs', label='sound', kind=_code)- if not 200 <= status < 300:- raise ValueError(f'ElevenLabs refused sound (HTTP {status}, {_code(body) or "unclassified"}); {retry.tail(asks)}')- if not isinstance(body, bytes) or not body:- raise ValueError('ElevenLabs returned no audio; request outcome unresolved')- meta = {'provider': address.ELEVENLABS, 'auth_source': AUTH_ENV, 'model': document['body']['model_id'], 'asks': asks}- # Only documented, constrained metadata; provider prose never enters a report or log.- for header, field in (('request-id', 'request_id'), ('song-id', 'song_id')):- value = headers.get(header, '')- if value and key not in value and re.fullmatch(r'[A-Za-z0-9_-]{1,128}', value):- meta[field] = value- value = headers.get('character-cost', '')- if str(value).isdigit() and len(str(value)) < 12:- meta['character_cost'] = int(value)- return body, metadiff --git a/sprite_gen/audio/sound.py b/sprite_gen/audio/sound.pydeleted file mode 100644index 64991e4..0000000--- a/sprite_gen/audio/sound.py+++ /dev/null@@ -1,90 +0,0 @@-# SPDX-License-Identifier: Apache-2.0-"""Generate one named game sound and publish its immutable audio bundle."""-from __future__ import annotations--import argparse-import json-import math-import os-from pathlib import Path-import shutil-import tempfile--from sprite_gen.audio import cache, processing, provider, playback-from sprite_gen.audio.manifest import AUDIO_KINDS, BGM, KIND, SFX, event_name, load as load_sound-from sprite_gen.util.cli_kwargs import namespace_from_kwargs---def generate(*, kind, prompt, duration, event, out_dir, cache_dir=None, loop=None, target_lufs=None, crossfade=None):- loop = kind == BGM if loop is None else loop- request = provider.request(kind, prompt, duration, loop)- event_name(event)- target = (-18.0 if kind == SFX else -20.0) if target_lufs is None else float(target_lufs)- if not math.isfinite(target) or not -36 <= target <= -9:- raise ValueError('target_lufs must be between -36 and -9')- crossfade = (min(.25, float(duration)/8) if crossfade is None else float(crossfade)) if loop else 0- if loop and (not math.isfinite(crossfade) or not 2/processing.RATE <= crossfade < float(duration)/2):- raise ValueError('crossfade must be positive and shorter than half the duration')- out_dir = Path(out_dir).expanduser().resolve()- recipe = {'request': cache.digest(request), 'event': event, 'loop': loop,- 'target_lufs': target, 'crossfade_seconds': crossfade, 'processing_version': processing.PROCESSING_VERSION}- if out_dir.exists():- manifest = json.loads((out_dir / 'sound.json').read_text()) if (out_dir / 'sound.json').is_file() else {}- if manifest.get('recipe') != recipe:- raise ValueError('output directory already exists with a different sound; use a new directory')- load_sound(out_dir/'sound.json', 50_000_000)- return {**manifest, 'cache_hit': True}- processing.require_tools()- cache_dir = Path(cache_dir).expanduser() if cache_dir else Path(os.environ.get('XDG_CACHE_HOME', Path.home()/'.cache'))/'sprite-gen'/'audio'- # Resolve missing credentials before claiming a request, but allow fully offline cache use.- def make():- return provider.generate(request)- if cache_dir.resolve() == out_dir or out_dir in cache_dir.resolve().parents:- raise ValueError('cache directory must be outside the output bundle')- data, receipt, hit = cache.obtain(cache_dir/'requests.sqlite3', request, make, prepare=provider.credential)- out_dir.parent.mkdir(parents=True, exist_ok=True)- stage = Path(tempfile.mkdtemp(prefix=f'.{out_dir.name}-', dir=out_dir.parent))- try:- source = stage/'source.mp3'- source.write_bytes(data)- details = processing.export(source, stage, target_lufs=target, loop=loop, crossfade=crossfade)- source.unlink()- manifest = {'kind': KIND, 'version': playback.VERSION, 'event': event, 'audio_kind': kind,- 'loop': loop, 'target_lufs': target, 'recipe': recipe, 'provider': receipt, **details}- (stage/'sound.json').write_text(json.dumps(manifest, indent=2, allow_nan=False)+'\n')- stage.rename(out_dir)- finally:- shutil.rmtree(stage, ignore_errors=True)- return {**manifest, 'cache_hit': hit}---def add_arguments(parser):- parser.add_argument('--kind', choices=AUDIO_KINDS, required=True)- prompts = parser.add_mutually_exclusive_group(required=True)- prompts.add_argument('--prompt')- prompts.add_argument('--prompt-file', type=Path)- parser.add_argument('--duration', type=float, required=True, help='provider duration in seconds; loops subtract crossfade')- parser.add_argument('--event', required=True)- parser.add_argument('--out-dir', type=Path, required=True)- parser.add_argument('--cache-dir', type=Path)- parser.add_argument('--loop', action=argparse.BooleanOptionalAction, default=None)- parser.add_argument('--target-lufs', type=float)- parser.add_argument('--crossfade', type=float, help='loop overlap seconds (default <=0.25s)')---def run(**kwargs):- parser = argparse.ArgumentParser()- add_arguments(parser)- args = namespace_from_kwargs(parser, kwargs)- try:- if (args.prompt is None) == (args.prompt_file is None):- raise ValueError('provide exactly one of prompt or prompt_file')- prompt = Path(args.prompt_file).read_text() if args.prompt_file is not None else args.prompt- result = generate(kind=args.kind, prompt=prompt, duration=args.duration, event=args.event,- out_dir=args.out_dir, cache_dir=args.cache_dir, loop=args.loop,- target_lufs=args.target_lufs, crossfade=args.crossfade)- except (ValueError, OSError) as exc:- raise SystemExit(f'sound: {exc}') from None- print(json.dumps({'ok': True, 'manifest': str(Path(args.out_dir)/'sound.json'),- 'cache_hit': result['cache_hit'], 'duration_seconds': result['duration_seconds']}))- return 0diff --git a/sprite_gen/audio/sprite-gen-audio-v2.mjs b/sprite_gen/audio/sprite-gen-audio-v2.mjsdeleted file mode 100644index 3fcda2d..0000000--- a/sprite_gen/audio/sprite-gen-audio-v2.mjs+++ /dev/null@@ -1,87 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// Frame contract v2. Loop preparation runs after decoding, never on each repeat.-const prepared = new WeakMap();-const cached = new WeakMap();-const guarded = new WeakMap();--export function prepareAudioBuffer(decoded, playback) {- const { version, sample_rate: rate, start_frame: start, end_frame: end,- overlap_frames: overlap } = playback;- if (version !== 2 || ![rate, start, end, overlap].every(Number.isSafeInteger) ||- rate < 8000 || rate > 192000 || start < 0 || end <= start || end > 601 * rate ||- overlap < 0 || (overlap !== 0 && (overlap < 2 || overlap * 2 >= end - start))) {- throw new RangeError('Invalid audio playback frame contract');- }- const key = [version, rate, start, end, overlap].join(':');- if (prepared.has(decoded)) {- if (prepared.get(decoded) !== key) throw new RangeError('AudioBuffer is already prepared');- return decoded;- }- if (cached.get(decoded)?.has(key)) return cached.get(decoded).get(key);- const rescale = frames => frames * decoded.sampleRate / rate;- // Resampling truncates fractional frames; double division can also lose one- // complete frame. Permit that single shortfall and discard decoder padding.- const first = Math.floor(rescale(start));- const mappedEnd = Math.floor(rescale(end));- if (decoded.length < mappedEnd - 1) {- throw new RangeError(`Decoded audio does not contain the playback interval: requires at least ${mappedEnd - 1} frames, has ${decoded.length} frames at ${decoded.sampleRate} Hz`);- }- const last = Math.min(mappedEnd, decoded.length);- // Round the declared final duration once. Independent rounding of N and M can- // change N-M by a frame; derive the overlap from the mapped interval instead.- const length = overlap ? Math.round(rescale(end - start - overlap)) : last - first;- const count = last - first - length;- if (overlap > 0 && count < 2) {- const reason = last < mappedEnd ? 'overlap too short after decoder one-frame shortfall' : 'overlap too short after sample-rate conversion';- throw new RangeError(`Audio playback ${reason}: requires at least 2 frames, has ${count}`);- }- if (length < 1 || count < 0 || (overlap > 0 && count * 2 >= last - first)) {- throw new RangeError(`Decoded audio does not contain the playback interval: requires [${first}, ${last}), has ${decoded.length} frames at ${decoded.sampleRate} Hz`);- }- const output = new AudioBuffer({ numberOfChannels: decoded.numberOfChannels,- length, sampleRate: decoded.sampleRate });- for (let channel = 0; channel < decoded.numberOfChannels; channel++) {- const source = decoded.getChannelData(channel);- const target = output.getChannelData(channel);- if (!overlap) {- target.set(source.subarray(first, first + length));- continue;- }- const middle = last - first - 2 * count;- target.set(source.subarray(first + count, last - count));- for (let i = 0; i < count; i++) {- const headWeight = 0.5 - 0.5 * Math.cos(Math.PI * i / (count - 1));- target[middle + i] = source[last - count + i] * (1 - headWeight) +- source[first + i] * headWeight;- }- }- prepared.set(output, key);- if (!cached.has(decoded)) cached.set(decoded, new Map());- cached.get(decoded).set(key, output);- return output;-}--export function createAudioSource(context, decoded, audio) {- if (typeof audio.loop !== 'boolean' || audio.loop !== (audio.playback.overlap_frames > 0)) {- throw new RangeError('Audio loop flag does not match playback overlap');- }- const source = context.createBufferSource();- const buffer = prepareAudioBuffer(decoded, audio.playback);- if (audio.loop && !guarded.has(buffer)) {- // Some renderers interpolate at the buffer end before wrapping. Supply- // the next cyclic sample without extending the declared loop interval.- const playback = new AudioBuffer({ numberOfChannels: buffer.numberOfChannels,- length: buffer.length + 1, sampleRate: buffer.sampleRate });- for (let channel = 0; channel < buffer.numberOfChannels; channel++) {- const target = playback.getChannelData(channel);- target.set(buffer.getChannelData(channel));- target[buffer.length] = target[0];- }- guarded.set(buffer, playback);- }- source.buffer = audio.loop ? guarded.get(buffer) : buffer;- source.loop = audio.loop;- source.loopStart = 0;- source.loopEnd = buffer.duration;- return source;-}diff --git a/sprite_gen/background/tile.py b/sprite_gen/background/tile.pyindex c493537..4fd73c3 100644--- a/sprite_gen/background/tile.py+++ b/sprite_gen/background/tile.py@@ -7,11 +7,6 @@ overlap B replaces part of the leading overlap A along a connected seam.Every output pixel is copied intact from A or B, including its original alpha.There is no resampling, blur, compositing, or colour interpolation.-``axis="xy"`` quilts along x, then along y with a cyclic seam: the second seam's-two ends, which meet across the x wrap, may differ by one step at most, so the-second pass cannot break the join the first one made. Its report measures both-joins of the finished tile.-Reports describe local pixel differences, not semantic continuity of a painting.Inspect repeated tiles visually even when the numerical checks pass."""@@ -126,22 +121,16 @@ def inspect_tile(image: Image.Image, axis: str = "x") -> dict[str, Any]:}-def _minimum_seam(error: Any, cyclic: bool = False) -> tuple[Any, float]:+def _minimum_seam(error: Any) -> tuple[Any, float]:"""Minimum accumulated error, with neighbouring rows moving at most one px.``cut`` is the LAST B pixel, not the first A pixel. In particular cut=0must copy B at x=0: the wrap then joins adjacent source pixels P-1 and P.Reserve the overlap's final column for A when overlap > 1. A one-columnoverlap necessarily copies B there and switches to A at the next column.-- ``cyclic``: the first and last rows are neighbours too (they meet across the- other axis's wrap), so the seam's two ends may differ by one step at most.- One search per starting column, all at once."""height, overlap = error.shapewidth = max(1, overlap - 1)- if cyclic and height > 1:- return _cyclic_seam(error[:, :width].astype(np.float64))costs = error[0, :width].astype(np.float64)steps = np.zeros((height, width), dtype=np.int8)for row in range(1, height):@@ -158,34 +147,27 @@ def _minimum_seam(error: Any, cyclic: bool = False) -> tuple[Any, float]:return seam, score-def _cyclic_seam(error: Any) -> tuple[Any, float]:- height, width = error.shape- costs = np.full((width, width), np.inf)- costs[np.arange(width), np.arange(width)] = error[0]- steps = np.zeros((height, width, width), dtype=np.int8)- blocked = np.full((width, 1), np.inf)- for row in range(1, height):- left = np.concatenate((blocked, costs[:, :-1]), axis=1)- right = np.concatenate((costs[:, 1:], blocked), axis=1)- steps[row][(left < costs) & (left <= right)] = -1- steps[row][(right < costs) & (right < left)] = 1- costs = np.minimum(costs, np.minimum(left, right)) + error[row]- start_column, end_column = np.indices((width, width))- final = np.where(np.abs(start_column - end_column) <= 1, costs, np.inf)- start, end = divmod(int(np.argmin(final)), width)- seam = np.empty(height, dtype=np.int32)- seam[-1] = end- for row in range(height - 1, 0, -1):- seam[row - 1] = seam[row] + steps[row, start, seam[row]]- return seam, float(final[start, end] / height)--def _crop_box(start: int, length: int, cross: int, axis: str) -> list[int]:return [start, 0, start + length, cross] if axis == "x" else [0, start, cross, start + length]-def _quilt(pixels: Any, period: int, overlap: int, axis: str, *, cyclic: bool = False) -> tuple[Any, dict[str, Any]]:- """Quilt one axis of axis-oriented pixels (the tiling axis is dimension 1)."""+def make_tile(+ image: Image.Image, period: int, *, axis: str = "x", overlap: int = 32,+) -> tuple[Image.Image, dict[str, Any]]:+ """Return an RGBA tile and JSON-safe report, leaving ``image`` untouched.++ The tile is ``period`` pixels along ``axis`` with the other dimension+ unchanged. At most MAX_CANDIDATES evenly spaced crop starts are evaluated,+ including both endpoints. The seam search is exact within each candidate,+ but the bounded crop search does not claim a global optimum.+ """+ for name, value in (("period", period), ("overlap", overlap)):+ if isinstance(value, bool) or not isinstance(value, Integral):+ raise TypeError(f"{name} must be an integer")+ period, overlap = int(period), int(overlap)+ if period < 2 or not 1 <= overlap < period:+ raise ValueError("geometry requires period >= 2 and 1 <= overlap < period")+ pixels = _pixels(image, axis)height, length, _ = pixels.shapeslack = length - period - overlapif slack < 0:@@ -203,7 +185,7 @@ def _quilt(pixels: Any, period: int, overlap: int, axis: str, *, cyclic: bool =# independent equally weighted channel. Selection still copies raw RGBA.a[..., :3] *= a[..., 3:] / 255b[..., :3] *= b[..., 3:] / 255- seam, score = _minimum_seam(np.square(a - b).mean(axis=-1), cyclic)+ seam, score = _minimum_seam(np.square(a - b).mean(axis=-1))if score < best_score:best_score, best_start, best_seam = score, int(start), seamassert best_seam is not None@@ -211,21 +193,19 @@ def _quilt(pixels: Any, period: int, overlap: int, axis: str, *, cyclic: bool =result = crop[:, :period].copy()use_b = np.arange(overlap)[None, :] <= best_seam[:, None]result[:, :overlap] = np.where(use_b[..., None], crop[:, period:], crop[:, :overlap])+ tile = Image.fromarray(result if axis == "x" else result.transpose(1, 0, 2))+ report = inspect_tile(tile, axis)# The wrap is now a natural source adjacency. It can pass while the new# internal cut is bad, so inspect that cut separately against SOURCE detail.- # Include vertical mask transitions as well as each row's horizontal cut;- # a cyclic seam also turns between its last and first rows.+ # Include vertical mask transitions as well as each row's horizontal cut.rows = np.arange(height)seam_color, seam_alpha = _differences(result[rows, best_seam], result[rows, best_seam + 1])reference_color, reference_alpha = _differences(crop[:, :-1], crop[:, 1:])turn_rows = np.flatnonzero(np.diff(best_seam))- turn_next = turn_rows + 1- if cyclic and height > 1 and best_seam[-1] != best_seam[0]:- turn_rows, turn_next = np.append(turn_rows, height - 1), np.append(turn_next, 0)if turn_rows.size:- turn_cols = np.maximum(best_seam[turn_rows], best_seam[turn_next])- turn_color, turn_alpha = _differences(result[turn_rows, turn_cols], result[turn_next, turn_cols])+ turn_cols = np.maximum(best_seam[turn_rows], best_seam[turn_rows + 1])+ turn_color, turn_alpha = _differences(result[turn_rows, turn_cols], result[turn_rows + 1, turn_cols])seam_color = np.concatenate((seam_color, turn_color))seam_alpha = np.concatenate((seam_alpha, turn_alpha))vertical_color, vertical_alpha = _differences(crop[:-1], crop[1:])@@ -234,14 +214,17 @@ def _quilt(pixels: Any, period: int, overlap: int, axis: str, *, cyclic: bool =quilt_color, quilt_alpha = _stats(seam_color), _alpha_stats(seam_alpha)reference_color_stats, reference_alpha_stats = _stats(reference_color), _alpha_stats(reference_alpha)quilt_color_limits, quilt_alpha_limits = _limits(reference_color_stats), _limits(reference_alpha_stats)- reasons = []if _exceeds(quilt_color, quilt_color_limits):- reasons.append("Internal quilt color difference exceeds source interior variation.")+ report["review_reasons"].append("Internal quilt color difference exceeds source interior variation.")if _exceeds(quilt_alpha, quilt_alpha_limits):- reasons.append("Internal quilt alpha mismatch exceeds source interior variation.")- return result, {- "start": best_start,- "reasons": reasons,+ report["review_reasons"].append("Internal quilt alpha mismatch exceeds source interior variation.")+ report.update({+ "status": "needs-review" if report["review_reasons"] else "pass",+ "method": "crop-overlap-minimum-error-quilt",+ "source_size": list(image.size),+ "source_crop": _crop_box(best_start, period + overlap, height, axis),+ "core_crop": _crop_box(best_start, period, height, axis),+ "overlap": overlap,"search": {"evaluated_candidates": int(starts.size), "candidate_limit": MAX_CANDIDATES,"available_crops": slack + 1, "strategy": "evenly-spaced including endpoints"},"quilt_seam": {@@ -252,101 +235,10 @@ def _quilt(pixels: Any, period: int, overlap: int, axis: str, *, cyclic: bool ="source_interior_alpha_difference": reference_alpha_stats,"thresholds": {"color": quilt_color_limits, "alpha": quilt_alpha_limits},},- }---def _geometry(period: Any, overlap: Any) -> tuple[int, int]:- for name, value in (("period", period), ("overlap", overlap)):- if isinstance(value, bool) or not isinstance(value, Integral):- raise TypeError(f"{name} must be an integer")- period, overlap = int(period), int(overlap)- if period < 2 or not 1 <= overlap < period:- raise ValueError("geometry requires period >= 2 and 1 <= overlap < period")- return period, overlap---def make_tile(- image: Image.Image, period: int, *, axis: str = "x", overlap: int = 32,-) -> tuple[Image.Image, dict[str, Any]]:- """Return an RGBA tile and JSON-safe report, leaving ``image`` untouched.-- The tile is ``period`` pixels along ``axis`` with the other dimension- unchanged; with ``axis="xy"`` it is ``period`` pixels square. At most- MAX_CANDIDATES evenly spaced crop starts are evaluated per axis, including- both endpoints. The seam search is exact within each candidate, but the- bounded crop search does not claim a global optimum.- """- period, overlap = _geometry(period, overlap)- if axis == "xy":- return _make_tile_xy(image, period, overlap)- pixels = _pixels(image, axis)- height = pixels.shape[0]- result, quilt = _quilt(pixels, period, overlap, axis)- tile = Image.fromarray(result if axis == "x" else result.transpose(1, 0, 2))- report = inspect_tile(tile, axis)- report["review_reasons"].extend(quilt["reasons"])- start = quilt["start"]- report.update({- "status": "needs-review" if report["review_reasons"] else "pass",- "method": "crop-overlap-minimum-error-quilt",- "source_size": list(image.size),- "source_crop": _crop_box(start, period + overlap, height, axis),- "core_crop": _crop_box(start, period, height, axis),- "overlap": overlap,- "search": quilt["search"],- "quilt_seam": quilt["quilt_seam"],- })- return tile, report---def _make_tile_xy(image: Image.Image, period: int, overlap: int) -> tuple[Image.Image, dict[str, Any]]:- source = _pixels(image, "x")- height, width, _ = source.shape- for axis, length in (("x", width), ("y", height)):- if length < period + overlap:- raise ValueError(- f"source has {length} pixels along {axis}; period + overlap requires {period + overlap}"- )- across, x_quilt = _quilt(source, period, overlap, "x")- down, y_quilt = _quilt(across.transpose(1, 0, 2), period, overlap, "y", cyclic=True)- tile = Image.fromarray(np.ascontiguousarray(down.transpose(1, 0, 2)))- x0, y0 = x_quilt["start"], y_quilt["start"]- report = inspect_tile_xy(tile)- for axis, quilt in (("x", x_quilt), ("y", y_quilt)):- measured = report["axes"][axis]- measured["review_reasons"].extend(quilt["reasons"])- measured["status"] = "needs-review" if measured["review_reasons"] else "pass"- measured.update(search=quilt["search"], quilt_seam=quilt["quilt_seam"])- report["review_reasons"] = [f"{axis}: {reason}" for axis in ("x", "y")- for reason in report["axes"][axis]["review_reasons"]]- report.update({- "status": "needs-review" if report["review_reasons"] else "pass",- "method": "crop-overlap-minimum-error-quilt along x, then along y with a cyclic seam",- "source_size": list(image.size),- "source_crop": [x0, y0, x0 + period + overlap, y0 + period + overlap],- "core_crop": [x0, y0, x0 + period, y0 + period],- "overlap": overlap,})return tile, report-def inspect_tile_xy(image: Image.Image) -> dict[str, Any]:- """Measure both wrap edges of a tile meant to repeat in both directions.-- ``axes`` holds the ``inspect_tile`` report of each axis; ``status`` is- ``needs-review`` when either axis needs review, and every reason is- prefixed with its axis.- """- axes = {axis: inspect_tile(image, axis) for axis in ("x", "y")}- reasons = [f"{axis}: {reason}" for axis in ("x", "y") for reason in axes[axis]["review_reasons"]]- return {- "schema_version": 1, "axis": "xy", "size": list(image.size),- "status": "needs-review" if reasons else "pass",- "requires_visual_review": True, "assessment": _ASSESSMENT,- "review_reasons": reasons, "axes": axes,- }--def _same_file(a: Path, b: Path) -> bool:"""One path, or one file by identity (`runio.same_folder`): the PNG and its report may both be new paths."""return a == b or same_folder(a, b)@@ -411,10 +303,8 @@ def _publish(def add_arguments(parser: argparse.ArgumentParser) -> None:parser.add_argument("--source", required=True, type=Path, help="independent single-frame PNG")parser.add_argument("--out", required=True, type=Path, help="output PNG; cannot overwrite the source")- parser.add_argument("--period", required=True, type=int,- help="tile length in pixels along --axis (with xy: the side of the square tile)")- parser.add_argument("--axis", choices=("x", "y", "xy"), default="x",- help="repeat direction; xy makes one tile seamless both ways and measures both joins")+ parser.add_argument("--period", required=True, type=int, help="tile length in pixels along --axis")+ parser.add_argument("--axis", choices=("x", "y"), default="x")parser.add_argument("--overlap", type=int, default=32,help="1 <= overlap < period; source must contain period + overlap pixels")parser.add_argument("--report", type=Path, help="JSON report (default: <out-stem>.report.json)")diff --git a/sprite_gen/cli.py b/sprite_gen/cli.pyindex 4e843a7..d1558d8 100644--- a/sprite_gen/cli.py+++ b/sprite_gen/cli.py@@ -8,14 +8,12 @@ from pathlib import Pathfrom typing import Callablefrom sprite_gen import _modules, gen-from sprite_gen.audio import soundfrom sprite_gen.background import tilefrom sprite_gen.curate import anchorfrom sprite_gen.compose import compose_atlas, compose_cycle, compose_gif, export_aseprite, export_pngs-from sprite_gen.compose import game_packfrom sprite_gen.qa import correction_loop, inspect, preview, score, motionfrom sprite_gen.qa import handed as handed_check-from sprite_gen.frames import cutout, extract, slice_sheet, ui_kit, unpack_atlas+from sprite_gen.frames import cutout, extract, slice_sheet, unpack_atlasfrom sprite_gen.gen import gen_set, logo, pixel_draw, prepare, videofrom sprite_gen.video import batch as video_batchfrom sprite_gen.video import canvas as video_canvas@@ -218,8 +216,6 @@ def _add_correction_loop(p: argparse.ArgumentParser) -> None:COMMANDS: dict[str, tuple[str, Callable[[argparse.ArgumentParser], None], Callable[..., int]]] = {- "game-pack": ("Resize finished assets into game atlases with playback policies.", game_pack.add_arguments, game_pack.run),- "sound": ("Generate a named game sound or instrumental music with browser audio exports.", sound.add_arguments, sound.run),"background-tile": ("Quilt a repeating RGBA background and measure its join.", tile.add_arguments, tile.run),"shadow": ("Project silhouette shadows from any supported asset.", shadow.add_arguments, shadow.run),"inspect-motion": ("Measure asset timing and contact evidence without changing animation.", motion.add_arguments, motion.run),@@ -281,11 +277,6 @@ COMMANDS: dict[str, tuple[str, Callable[[argparse.ArgumentParser], None], Callab_add_slice_sheet,slice_sheet.run,),- "ui-kit": (- "Split a UI kit sheet drawn on the fixed layout into nine-slice elements with measured insets.",- ui_kit.add_arguments,- ui_kit.run,- ),"gen": ("Generate one image via a provider (codex image_gen / grok Imagine on a subscription login first (an API key only without one, billed per call and said), or openai Images API for servers/SaaS, billed per call) into a verified PNG.",_add_gen,diff --git a/sprite_gen/compose/game_pack.py b/sprite_gen/compose/game_pack.pydeleted file mode 100644index e4d7850..0000000--- a/sprite_gen/compose/game_pack.py+++ /dev/null@@ -1,572 +0,0 @@-# SPDX-License-Identifier: Apache-2.0-"""Resize finished assets and publish an immutable game atlas pack.--Request version 2 adds painted scene art (docs/game-pack.md "Version 2"): single images with-anchor and footprint, repeating tiles as their own files, and a UI kit of nine-slice elements-and icons. A version 1 request is packed exactly as before.-"""-from __future__ import annotations--import argparse-from io import BytesIO-import json-import math-import os-from pathlib import Path-import re-import shutil-import tempfile--from PIL import Image--from sprite_gen.audio.manifest import load as load_sound-from sprite_gen.audio.playback import player as audio_player-from sprite_gen.frames.ui_kit import (REPORT_KIND as UI_KIT_KIND, SIDES, STRETCHES, content_rect, element_path,- measure_insets)-from sprite_gen._deps import np-from sprite_gen.spec.assets import finite, load_asset, load_asset_states-from sprite_gen.spec.runio import inside_folder, same_folder-from sprite_gen.util.resample import resize_cell-from sprite_gen.util.console import utf8_streams--MAX_PAGE_SIZE = 4096-MAX_BYTES = 50_000_000-SCENE_SECTIONS = ("images", "tiles", "ui")-# A "base" footprint counts pixels at least this opaque (docs/game-pack.md "Version 2 request").-FOOTPRINT_ALPHA = 128---def _integer(value, name, *, maximum=None):- number = finite(value, name, positive=True)- if number != int(number) or maximum is not None and number > maximum:- raise ValueError(f"{name} must be an integer between 1 and {maximum or 'its limit'}")- return int(number)---def _name(value):- if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9_.-]+", value):- raise ValueError("asset id and state must use letters, digits, underscore, dot or dash")- return value---def _policy(sequence, entry):- count = len(sequence.frames)- metadata = sequence.metadata- result = {}- for key, default in (("loop", True), ("hold_last", False), ("end_frame", count - 1),- ("blend", "normal"), ("events", []), ("direction", None)):- result[key] = entry.get(key, metadata.get(key, default))- for key in ("loop", "hold_last"):- if type(result[key]) is not bool:- raise ValueError(f"{key} must be a bool")- if result["blend"] not in ("normal", "add"):- raise ValueError("blend must be normal or add")- if type(result["end_frame"]) is not int or not 0 <= result["end_frame"] < count:- raise ValueError("end_frame must index a playback frame (zero-based)")- if result["direction"] is not None and not isinstance(result["direction"], str):- raise ValueError("direction must be a string or null")- if not isinstance(result["events"], list):- raise ValueError("events must be a list")- for event in result["events"]:- if (not isinstance(event, dict) or type(event.get("frame")) is not int- or not 0 <= event["frame"] < count or not isinstance(event.get("name"), str) or not event["name"]):- raise ValueError("each event needs a zero-based playback frame and a name")- result["durations_ms"] = [duration * 1000 for duration in sequence.durations]- return result---def _display(sequence, entry):- display = entry.get("display")- if not isinstance(display, dict) or len(display) != 1 or not set(display) <= {"width", "height", "body_height"}:- raise ValueError("display requires exactly one of width, height or body_height")- dimension, value = next(iter(display.items()))- target = _integer(value, f"display {dimension}")- width, height = sequence.size- if dimension == "body_height":- reference = finite(entry.get("source_body_height", sequence.metadata.get("body_h")),- "source_body_height (required when the asset has no body_h)", positive=True)- else:- reference = width if dimension == "width" else height- scale = target / reference- size = (max(1, round(width * scale)), max(1, round(height * scale)))- anchor = [sequence.anchor[0] * size[0] / width, sequence.anchor[1] * size[1] / height]- sampling = entry.get("resample", "nearest" if sequence.metadata.get("frame_variant") == "pixel" else "lanczos")- if sampling not in ("nearest", "lanczos"):- raise ValueError("resample must be nearest or lanczos")- return size, anchor, sampling---def _version(request):- if not isinstance(request, dict) or type(request.get("version")) is not int or request["version"] not in (1, 2):- raise ValueError("game pack request version must be 1 or 2")- if request["version"] == 1 and any(key in request for key in SCENE_SECTIONS):- raise ValueError("images, tiles and ui need request version 2")- return request["version"]---def _cell(image, size, sampling):- return image.resize(size, Image.Resampling.NEAREST) if sampling == "nearest" else resize_cell(image, size)---def _prepare(request, base, page_size):- entries = request.get("assets", [])- if not isinstance(entries, list):- raise ValueError("assets must be a list")- ids, animations, frames, sources = set(), {}, [], set()- for entry in entries:- if not isinstance(entry, dict):- raise ValueError("each asset must be an object")- asset_id = _name(entry.get("id"))- if asset_id in ids:- raise ValueError(f"duplicate asset id: {asset_id}")- ids.add(asset_id)- if not isinstance(entry.get("source"), str) or not entry["source"]:- raise ValueError("each asset requires a source path")- sequences = load_asset_states(base / entry["source"], state=entry.get("state"), fps=entry.get("fps"), anchor=entry.get("anchor"))- if len(sequences) > 1 and "direction" in entry:- raise ValueError("direction override requires one animation; select a source state")- for state, sequence in sequences.items():- key = asset_id if state is None else f"{asset_id}/{_name(state)}"- size, anchor, sampling = _display(sequence, entry)- # One extruded pixel on each edge keeps filtered textures from bleeding.- if max(size) + 2 > page_size:- raise ValueError(f"{key}: frame {size} plus padding exceeds page size {page_size}")- animation = _policy(sequence, entry)- animation.update(anchor=anchor, size={"w": size[0], "h": size[1]}, frames=[])- for index, image in enumerate(sequence.frames):- name = f"{key}/{index:06d}"- animation["frames"].append(name)- frames.append((name, _cell(image, size, sampling), anchor))- animations[key] = animation- sources.update(sequence.source_files)- return dict(sorted(animations.items())), sorted(frames, key=lambda f: f[0]), sources---def _entries(owner, key, allowed):- """A version 2 list section: objects with a unique id, a source path and only the documented keys."""- entries = owner.get(key, [])- if not isinstance(entries, list):- raise ValueError(f"{key} must be a list")- ids = set()- for entry in entries:- if not isinstance(entry, dict):- raise ValueError(f"each {key} entry must be an object")- unknown = sorted(set(entry) - allowed)- if unknown:- raise ValueError(f"unknown {key} key(s): {', '.join(unknown)}")- ident = _name(entry.get("id"))- if ident in ids:- raise ValueError(f"duplicate {key} id: {ident}")- ids.add(ident)- if not isinstance(entry.get("source"), str) or not entry["source"]:- raise ValueError(f"each {key} entry requires a source path")- return entries---def _still(path, key, anchor=None):- sequence = load_asset(path, anchor=anchor)- if len(sequence.frames) != 1:- raise ValueError(f"{key}: needs exactly one frame, the source has {len(sequence.frames)}")- return sequence---def _fixed_display(entry, key):- display = entry.get("display")- if not isinstance(display, dict) or len(display) != 1 or not set(display) <= {"width", "height"}:- raise ValueError(f"{key}: display requires exactly one of width or height")---def _fits(key, size, page_size):- if max(size) + 2 > page_size:- raise ValueError(f"{key}: frame {size} plus padding exceeds page size {page_size}")---def _footprint(entry, image, size, key):- value = entry.get("footprint")- if value is None:- return None- width, height = image.size- if value == "base":- opaque = np.asarray(image.getchannel("A")) >= FOOTPRINT_ALPHA- rows = np.flatnonzero(opaque.any(axis=1))- if not rows.size:- raise ValueError(f"{key}: no pixel reaches alpha {FOOTPRINT_ALPHA}, so the footprint has no base")- bottom = int(rows[-1]) + 1- top = bottom - max(1, math.ceil((bottom - int(rows[0])) / 5))- band = opaque[top:bottom]- cols, band_rows = np.flatnonzero(band.any(axis=0)), np.flatnonzero(band.any(axis=1))- x0, x1 = int(cols[0]), int(cols[-1]) + 1- y0, y1 = top + int(band_rows[0]), top + int(band_rows[-1]) + 1- elif isinstance(value, dict) and set(value) == {"x", "y", "w", "h"} and all(type(v) is int for v in value.values()):- x0, y0 = value["x"], value["y"]- x1, y1 = x0 + value["w"], y0 + value["h"]- if value["w"] < 1 or value["h"] < 1 or x0 < 0 or y0 < 0 or x1 > width or y1 > height:- raise ValueError(f"{key}: footprint must be a nonempty rectangle inside the {width}x{height} source")- else:- raise ValueError(f'{key}: footprint must be "base" or integer {{x, y, w, h}} in source pixels')- # outward to whole stored pixels: left and top down, right and bottom up, inside the frame- fx0, fy0 = x0 * size[0] // width, y0 * size[1] // height- fx1, fy1 = min(size[0], -(-x1 * size[0] // width)), min(size[1], -(-y1 * size[1] // height))- return {"x": fx0, "y": fy0, "w": max(1, fx1 - fx0), "h": max(1, fy1 - fy0)}---def _scaled_up(value, scale):- return math.ceil(round(value * scale, 9))---def _sides(record, field, key):- sides = record.get(field)- if not isinstance(sides, dict) or set(sides) != set(SIDES) or any(type(sides[s]) is not int or sides[s] < 0 for s in SIDES):- raise ValueError(f"{key}: {field} needs non-negative integer left, right, top and bottom")- return sides---def _ends_kept(cell, insets, width):- """``cell`` as a three-slice drawn ``width`` wide: its two end slices as they are, its middle columns- repeated or dropped (nearest), never blended."""- if cell.width == width:- return cell- left, right = insets["left"], insets["right"]- stored = Image.new("RGBA", (width, cell.height), (0, 0, 0, 0))- stored.paste(cell.crop((0, 0, left, cell.height)), (0, 0))- middle = cell.crop((left, 0, cell.width - right, cell.height))- stored.paste(middle.resize((width - left - right, cell.height), Image.Resampling.NEAREST), (left, 0))- stored.paste(cell.crop((cell.width - right, 0, cell.width, cell.height)), (width - right, 0))- return stored---def _fill(name, record, image, frame, page_size):- """A fill stored at its frame's content rectangle (docs/game-pack.md "Version 2 manifest"): resized by the- one factor that makes it as tall as the rectangle, then drawn as wide as it with its ends kept."""- key = f"ui/{_name(name)}"- rect = content_rect(frame)- factor = rect["h"] / image.height- cell = resize_cell(image, (max(1, round(image.width * factor)), rect["h"]))- insets = {side: _scaled_up(record["insets"][side], factor) for side in SIDES}- measured, _notes = measure_insets(cell, "x")- insets = {side: max(insets[side], measured[side]) for side in SIDES}- if insets["left"] + insets["right"] >= min(cell.width, rect["w"]):- raise ValueError(f"{key}: scaled to the height of {record['inside']['element']}'s content area, its fixed "- "ends are wider than that area")- padding = {side: _scaled_up(record["padding"][side], factor) for side in SIDES}- if padding["left"] + padding["right"] >= rect["w"] or padding["top"] + padding["bottom"] >= rect["h"]:- raise ValueError(f"{key}: in its frame's content area the padding leaves no content area")- size = (rect["w"], rect["h"])- _fits(key, size, page_size)- entry = {"frame": key, "size": {"w": size[0], "h": size[1]}, "stretch": "x", "insets": insets,- "padding": padding, "inside": {"element": record["inside"]["element"], "rect": rect}}- return entry, (key, _ends_kept(cell, insets, size[0]), (size[0] / 2, size[1] / 2))---def _ui_kit(path, scale, page_size):- """Nine-slice entries and atlas frames from a `ui-kit` report (docs/ui-kit.md "Report")."""- report = json.loads(path.read_text(encoding="utf-8"))- if not isinstance(report, dict) or report.get("kind") != UI_KIT_KIND or report.get("version") != 1:- raise ValueError(f"ui.kit must be a version 1 ui-kit report ({UI_KIT_KIND}): {path.name}")- elements = report.get("elements")- if not isinstance(elements, dict) or not elements:- raise ValueError("ui-kit report lists no elements")- entries, frames, sources, fills = {}, [], {path}, []- for name, record in elements.items():- key = f"ui/{_name(name)}"- if not isinstance(record, dict) or record.get("stretch") not in STRETCHES:- raise ValueError(f"{key}: stretch must be one of {', '.join(STRETCHES)}")- stretch = record["stretch"]- insets, padding = _sides(record, "insets", key), _sides(record, "padding", key)- fixed = {"x": ("top", "bottom"), "none": SIDES}.get(stretch, ())- if any(insets[side] for side in fixed):- raise ValueError(f"{key}: stretch {stretch} needs {', '.join(fixed)} insets of 0")- if not isinstance(record.get("file"), str) or not record["file"]:- raise ValueError(f"{key}: the report names no file")- sequence = _still(element_path(path, record["file"]), key)- image = sequence.frames[0]- if record.get("size") != {"w": image.width, "h": image.height}:- raise ValueError(f"{key}: the report's size does not match {record['file']}")- sources.update(sequence.source_files)- if "inside" in record:- # a fill takes its size from its frame's stored content area, so it is packed after every frame- inside = record["inside"]- if not isinstance(inside, dict) or not isinstance(inside.get("element"), str):- raise ValueError(f"{key}: inside must name the element the fill goes in")- if stretch != "x":- raise ValueError(f"{key}: a fill stretches in width only (stretch x), not {stretch}")- fills.append((name, record, image))- continue- size = (max(1, round(image.width * scale)), max(1, round(image.height * scale)))- _fits(key, size, page_size)- cell = image if size == image.size else resize_cell(image, size)- insets = {side: _scaled_up(insets[side], scale) for side in SIDES}- if cell is not image:- # Resampling spreads an ornament's edge a little past its scaled place; the stored pixels are- # measured the way `ui-kit` measured the source, and the larger inset of the two is kept.- measured, _notes = measure_insets(cell, stretch)- insets = {side: max(insets[side], measured[side]) for side in SIDES}- padding = {side: _scaled_up(padding[side], scale) for side in SIDES}- if (stretch != "none" and insets["left"] + insets["right"] >= size[0]) or (- stretch == "xy" and insets["top"] + insets["bottom"] >= size[1]):- raise ValueError(f"{key}: at ui scale {scale} the insets leave no stretchable middle")- if padding["left"] + padding["right"] >= size[0] or padding["top"] + padding["bottom"] >= size[1]:- raise ValueError(f"{key}: at ui scale {scale} the padding leaves no content area")- frames.append((key, cell, (size[0] / 2, size[1] / 2)))- entries[name] = {"frame": key, "size": {"w": size[0], "h": size[1]}, "stretch": stretch,- "insets": insets, "padding": padding}- frame_names = set(entries)- for name, record, image in fills:- target = record["inside"]["element"]- if target not in frame_names:- raise ValueError(f"ui/{_name(name)}: inside names {target}, which is not a frame of this report")- entries[name], frame = _fill(name, record, image, entries[target], page_size)- frames.append(frame)- return entries, frames, sources---def _encode_image(image, fmt):- buffer = BytesIO()- if fmt == "PNG":- image.save(buffer, format="PNG", compress_level=9)- else:- image.save(buffer, format="WEBP", lossless=True, exact=True, method=6)- return buffer.getvalue()---def _prepare_scene(request, base, page_size):- """The version 2 sections: manifest entries, atlas frames, tile files and the sources they read."""- frames, files, sources = [], {}, set()- images = {}- for entry in _entries(request, "images", {"id", "source", "display", "resample", "anchor", "footprint"}):- key = f"image/{entry['id']}"- sequence = _still(base / entry["source"], key, anchor=entry.get("anchor"))- _fixed_display(entry, key)- size, anchor, sampling = _display(sequence, entry)- _fits(key, size, page_size)- frames.append((key, _cell(sequence.frames[0], size, sampling), anchor))- images[entry["id"]] = {"frame": key, "size": {"w": size[0], "h": size[1]}, "anchor": anchor,- "footprint": _footprint(entry, sequence.frames[0], size, key)}- sources.update(sequence.source_files)- tiles = {}- for entry in _entries(request, "tiles", {"id", "source", "display"}):- key = f"tile/{entry['id']}"- sequence = _still(base / entry["source"], key)- _fixed_display(entry, key)- image = sequence.frames[0]- dimension, value = next(iter(entry["display"].items()))- target = _integer(value, f"display {dimension}")- scale = target / (image.width if dimension == "width" else image.height)- png, webp = f"tile-{entry['id']}.png", f"tile-{entry['id']}.webp"- files[png], files[webp] = _encode_image(image, "PNG"), _encode_image(image, "WEBP")- tiles[entry["id"]] = {"image": png, "webp": webp, "size": {"w": image.width, "h": image.height},- "display_size": {"w": max(1, round(image.width * scale)),- "h": max(1, round(image.height * scale))}}- sources.update(sequence.source_files)- nine_slice, icons = {}, {}- ui = request.get("ui")- if ui is not None:- if not isinstance(ui, dict):- raise ValueError("ui must be an object")- unknown = sorted(set(ui) - {"kit", "scale", "icons"})- if unknown:- raise ValueError(f"unknown ui key(s): {', '.join(unknown)}")- scale = finite(ui.get("scale", 1), "ui scale", positive=True)- if "kit" in ui:- if not isinstance(ui["kit"], str) or not ui["kit"]:- raise ValueError("ui.kit must be the path of a ui-kit report")- nine_slice, kit_frames, kit_sources = _ui_kit((base / ui["kit"]).resolve(), scale, page_size)- frames += kit_frames- sources |= kit_sources- for entry in _entries(ui, "icons", {"id", "source", "display", "resample"}):- key = f"icon/{entry['id']}"- sequence = _still(base / entry["source"], key)- _fixed_display(entry, key)- size, _anchor, sampling = _display(sequence, entry)- _fits(key, size, page_size)- frames.append((key, _cell(sequence.frames[0], size, sampling), (size[0] / 2, size[1] / 2)))- icons[entry["id"]] = {"frame": key, "size": {"w": size[0], "h": size[1]}}- sources.update(sequence.source_files)- sections = {"images": dict(sorted(images.items())), "tiles": dict(sorted(tiles.items())),- "ui": {"nine_slice": dict(sorted(nine_slice.items())), "icons": dict(sorted(icons.items()))}}- return sections, frames, files, sources---def _layout(frames, limit):- """Deterministic shelf placement; playback order is independent of texture position."""- pages, placed = [], []- x = y = row_height = width = height = 0- for name, image, anchor in frames:- w, h = image.width + 2, image.height + 2- if x + w > limit:- x, y, row_height = 0, y + row_height, 0- if y + h > limit:- pages.append((width, height, placed))- placed = []- x = y = row_height = width = height = 0- placed.append((name, image, anchor, x + 1, y + 1))- x += w- row_height = max(row_height, h)- width, height = max(width, x), max(height, y + h)- pages.append((width, height, placed))- return pages---def _paste_extruded(sheet, image, x, y):- w, h = image.size- sheet.paste(image, (x, y))- sheet.paste(image.crop((0, 0, w, 1)), (x, y - 1))- sheet.paste(image.crop((0, h - 1, w, h)), (x, y + h))- sheet.paste(image.crop((0, 0, 1, h)), (x - 1, y))- sheet.paste(image.crop((w - 1, 0, w, h)), (x + w, y))- for dx, sx in ((-1, 0), (w, w - 1)):- for dy, sy in ((-1, 0), (h, h - 1)):- sheet.putpixel((x + dx, y + dy), image.getpixel((sx, sy)))---def _encode(pages, animations, max_bytes, sections=None, files=None):- """Pages, then any version 2 files, then the manifest; ``sections`` makes it a version 2 manifest."""- payloads, textures = {}, []- total = 0- for index, (width, height, placed) in enumerate(pages):- sheet = Image.new("RGBA", (width, height))- records = {}- for name, image, anchor, x, y in placed:- _paste_extruded(sheet, image, x, y)- size = {"w": image.width, "h": image.height}- records[name] = {"frame": {"x": x, "y": y, **size}, "rotated": False, "trimmed": False,- "spriteSourceSize": {"x": 0, "y": 0, **size}, "sourceSize": size,- "pivot": {"x": anchor[0]/image.width, "y": anchor[1]/image.height}}- png_name, webp_name = f"atlas-{index:03d}.png", f"atlas-{index:03d}.webp"- for name, fmt, options in ((png_name, "PNG", {"compress_level": 9}),- (webp_name, "WEBP", {"lossless": True, "exact": True, "method": 6})):- buffer = BytesIO()- sheet.save(buffer, format=fmt, **options)- payloads[name] = buffer.getvalue()- total += len(payloads[name])- if total > max_bytes:- raise ValueError(f"game pack exceeds {max_bytes} bytes (50 MB maximum)")- textures.append({"image": png_name, "webp": webp_name, "frames": records,- "meta": {"image": png_name, "format": "RGBA8888", "size": {"w": width, "h": height}, "scale": "1"}})- for name, data in (files or {}).items():- payloads[name] = data- total += len(data)- if total > max_bytes:- raise ValueError(f"game pack exceeds {max_bytes} bytes (50 MB maximum)")- result = {"kind": "sprite-gen-game-pack", "version": 1, "textures": textures, "animations": animations}- if sections is not None:- result["version"] = 2- result.update(sections)- payloads["game-pack.json"] = (json.dumps(result, ensure_ascii=False, separators=(",", ":"), allow_nan=False) + "\n").encode()- if total + len(payloads["game-pack.json"]) > max_bytes:- raise ValueError(f"game pack exceeds {max_bytes} bytes (50 MB maximum, including its manifest)")- return result, payloads---def _publish(out_dir, payloads):- """One atomic directory rename; concurrent publishers cannot interleave packs."""- def identical():- return (out_dir.is_dir() and {p.name for p in out_dir.iterdir()} == set(payloads)- and all((out_dir / name).is_file() and (out_dir / name).read_bytes() == data- for name, data in payloads.items()))-- if out_dir.exists():- if identical():- return- raise ValueError("output directory already exists with different content; use a new directory")- out_dir.parent.mkdir(parents=True, exist_ok=True)- stage = Path(tempfile.mkdtemp(prefix=f".{out_dir.name}-", dir=out_dir.parent))- try:- for name, data in payloads.items():- with (stage / name).open("wb") as handle:- handle.write(data)- handle.flush()- os.fsync(handle.fileno())- try:- stage.rename(out_dir)- except OSError:- if not identical():- raise- finally:- if stage.exists():- shutil.rmtree(stage)---def pack(request: Path, out_dir: Path, *, page_size=MAX_PAGE_SIZE, max_bytes=MAX_BYTES):- page_size = _integer(page_size, "page size", maximum=MAX_PAGE_SIZE)- max_bytes = _integer(max_bytes, "max bytes", maximum=MAX_BYTES)- request, out_dir = Path(request).expanduser().resolve(), Path(out_dir).expanduser().resolve()- document = json.loads(request.read_text(encoding="utf-8"))- version = _version(document)- animations, frames, sources = _prepare(document, request.parent, page_size)- # `files` is the audio loop's name below; the version 2 tile files must not share it.- sections = tile_files = None- if version == 2:- sections, scene_frames, tile_files, scene_sources = _prepare_scene(document, request.parent, page_size)- frames = sorted(frames + scene_frames, key=lambda f: f[0])- sources |= scene_sources- names = [name for name, _image, _anchor in frames]- if len(set(names)) != len(names):- raise ValueError("two atlas frames share a name; rename an asset or scene entry")- audio_entries = document.get("audio", [])- if not isinstance(audio_entries, list):- raise ValueError("audio must be a list")- audio, audio_payloads = {}, {}- for entry in audio_entries:- if not isinstance(entry, dict):- raise ValueError("each audio entry must be an object")- asset_id = _name(entry.get("id"))- if asset_id in audio:- raise ValueError(f"duplicate audio id: {asset_id}")- if not isinstance(entry.get("source"), str) or not entry["source"]:- raise ValueError("each audio entry requires a source path")- remaining = max_bytes - sum(map(len, audio_payloads.values()))- record, files, paths = load_sound(request.parent / entry["source"], remaining)- for fmt, data in files.items():- name = f"audio-{asset_id}.{fmt}"- record["files"][fmt]["path"] = name- audio_payloads[name] = data- audio[asset_id] = record- sources.update(paths)- if not frames and not tile_files and not audio:- raise ValueError("game pack request declares nothing to pack: give it an asset, a scene entry or a sound")- if any(same_folder(path, out_dir) or inside_folder(path, out_dir) for path in sources | {request}):- raise ValueError("output directory must not contain any source file")- result, payloads = _encode(_layout(frames, page_size) if frames else [], animations, max_bytes, sections, tile_files)- if audio:- helper, module = audio_player()- audio_payloads[helper["path"]] = module- for record in audio.values():- record["player"] = helper- result["audio"] = dict(sorted(audio.items()))- payloads.update(audio_payloads)- payloads["game-pack.json"] = (json.dumps(result, ensure_ascii=False, separators=(",", ":"), allow_nan=False) + "\n").encode()- if sum(map(len, payloads.values())) > max_bytes:- raise ValueError(f"game pack exceeds {max_bytes} bytes (including audio)")- _publish(out_dir, payloads)- return result---def add_arguments(parser):- parser.epilog = "events[].frame and end_frame are zero-based indices in output playback order."- parser.add_argument("--request", type=Path, required=True, help="JSON result list with display sizes")- parser.add_argument("--out-dir", type=Path, required=True, help="new directory for the immutable pack")- parser.add_argument("--page-size", type=int, default=MAX_PAGE_SIZE)- parser.add_argument("--max-bytes", type=int, default=MAX_BYTES)---def run(**kwargs):- try:- result = pack(kwargs["request"], kwargs["out_dir"], page_size=kwargs.get("page_size", MAX_PAGE_SIZE),- max_bytes=kwargs.get("max_bytes", MAX_BYTES))- except (ValueError, OSError) as exc:- raise SystemExit(f"game-pack: {exc}") from exc- print(json.dumps({"ok": True, "manifest": str(Path(kwargs["out_dir"]) / "game-pack.json"),- "pages": len(result["textures"]), "animations": len(result["animations"])}))- return 0---def main():- utf8_streams()- parser = argparse.ArgumentParser(description=__doc__)- add_arguments(parser)- return run(**vars(parser.parse_args()))---if __name__ == "__main__":- raise SystemExit(main())diff --git a/sprite_gen/frames/alpha_floor.py b/sprite_gen/frames/alpha_floor.pyindex 385edc9..334d9f9 100644--- a/sprite_gen/frames/alpha_floor.py+++ b/sprite_gen/frames/alpha_floor.py@@ -6,8 +6,8 @@ pixel within ``edge`` pixels of a solid pixel (8-connected: diagonals count) belobject's anti-aliased edge and is kept as it is. Every other faint pixel is haze and becomes``(0, 0, 0, 0)``. Nothing is blended or resampled: a pixel is kept byte for byte or cleared.-Shared by `slice-sheet --alpha-floor` and `ui-kit` (docs/ui-kit.md "Alpha cleanup"). The report-measures what changed instead of asserting it.+Used by `slice-sheet --alpha-floor` (docs/sheet-slicing.md "Alpha cleanup"). The report measures+what changed instead of asserting it."""from __future__ import annotationsdiff --git a/sprite_gen/frames/ui_kit.py b/sprite_gen/frames/ui_kit.pydeleted file mode 100644index 0909aeb..0000000--- a/sprite_gen/frames/ui_kit.py+++ /dev/null@@ -1,1338 +0,0 @@-# SPDX-License-Identifier: Apache-2.0-"""Split a transparent UI kit sheet drawn on the fixed layout into nine-slice elements.--docs/ui-kit.md is the contract. One table (`LAYOUT`) is the layout: `gen --layout-guide ui-kit`-draws it (`draw_guide`) and says it (`guide_text`), and the splitter cuts along it. A sheet's shape-says which part of the table it holds (`SHEETS`): a square sheet the seven frames, a 2:3 sheet the-same frames at the same places and the fills, slot, badge, pips and joystick below them. The sheet's-alpha haze is cleared first (`alpha_floor.clear_haze`). The drawing is then read once, exactly-(`_judge`): the readings of its parts under the drifts the cut considers that keep the parts-clearest of their boxes' edges, and the cut is the one reading within 1 px of the least, or the-sheet is refused (`_decide`). Each element's insets and content padding are measured on its own-pixels; a fill is fitted to its bar frame's content area. The frames are required; an optional-element whose box is empty is left out and named under `missing`. A drawing that drifted further-than a cut accepts, an empty frame box, a drawing that fits the layout as well in two ways, a box-whose parts are centred outside it, or a drawing that lies on the layout under no drift refuses the-sheet (`Refusal`): no element is cut under a name the drawing does not give it. The-report names each element PNG by its path from the report's own directory (`report_file`,-`element_path`). A kit is written whole into a new or empty output directory (`_write_kit`): staged-in a hidden directory beside it and renamed into place in one step. That rename, or with the report-outside the directory the link that names the report, publishes the kit: a run that fails or is-interrupted before it leaves nothing, one after it the whole kit, and a killed run, or one-interrupted again while it cleans up, never part of one. A directory that holds anything is refused.-"""--from __future__ import annotations--import argparse-import contextlib-import heapq-import io-import itertools-import json-import math-import os-import secrets-import shutil-from dataclasses import dataclass-from pathlib import Path-from typing import Any, Callable--from PIL import Image, ImageDraw--from sprite_gen._deps import np-from sprite_gen.frames.alpha_floor import clear_haze-from sprite_gen.spec.runio import inside_folder, same_folder-from sprite_gen.util.console import utf8_streams--REFERENCE = 1024-GAP = 48-MIN_PART = 16-MARGIN = 2-# Padding: the interior runs on while each step to the next pixel stays small and the pixel stays near-# the centre, so a smooth gradient face is interior and a border's sharp edge ends it.-PADDING_STEP = 16-PADDING_SPAN = 96-# A round part whose cut is more than this opaque outside the ellipse its bounding box holds was drawn on a-# square plate, not as a circle (docs/ui-kit.md "Layout").-ROUND_CORNER_FILL = 0.25-# Reading the drawing (docs/ui-kit.md "Reading the drawing"). The drift a cut accepts: along each axis a scale within-# DRIFT_SCALE of 1 and an offset within DRIFT_OFFSET px at 1024. The cut considers the drifts within that range and-# DRIFT_MARGIN of it beyond either end (a scale from 0.875 to 1.125, an offset of at most 120 px at 1024), so that a-# drawing drawn at the edge of the range is read under its own drift and a reading just beyond it is still a rival. A-# part keeps clear of its box's edges, as the guide asks, when it lies CLEARANCE px inside them, and two readings whose-# costs differ by no more than TIE px fit the drawing equally well. A least-squares fit is taken from FIT_MIN_BOXES or-# more boxes that hold parts.-DRIFT_SCALE = 0.1-DRIFT_OFFSET = 2 * GAP-DRIFT_MARGIN = 0.25-FIT_MIN_BOXES = 3-CLEARANCE = 1.0-TIE = 1.0-# The search (`_judge`) solves a span of drifts whole once its undecided parts can be read in at most LEAF_WAYS ways, or-# once it moves no box more than LEAF_WIDTH px. Its work bound is SEARCH_NODES spans, well above what drawn sheets need:-# past it, a sheet every reading of which is proven to cost more than TIE is refused as off the layout.-LEAF_WAYS = 48-LEAF_WIDTH = 1e-3-SEARCH_NODES = 6000-GUIDE_BACKGROUND = (0xF6, 0xF6, 0xF6)-GUIDE_BOX = (0x2F, 0x80, 0xED)-STRETCHES = ("xy", "x", "none")-SIDES = ("left", "right", "top", "bottom")-REPORT_KIND = "sprite-gen-ui-kit"-# A kit's staging directory takes the output directory's name with one rename. POSIX rename(2) takes the name of an-# absent or empty directory and fails on any other; Windows takes no existing directory's name, so an empty output-# directory is removed just before the rename there (Python docs, os.rename).-RENAME_ONTO_EMPTY_DIR = os.name != "nt"---@dataclass(frozen=True)-class Slot:- name: str- box: tuple[int, int, int, int]- stretch: str- where: str- what: str- # Padding is measured only for an element that holds content (text, digits, an icon, a bar's fill);- # the others get 0 on every side, as insets are 0 along an axis the element keeps.- content: bool = True- # A fill: the bar frame whose content area it fills (docs/ui-kit.md "Fills").- inside: str | None = None- # A round part: the guide draws a circle in its box, and a cut with filled corners is flagged.- round: bool = False- # An optional element: when its box is empty the kit is made without it and the report names it under- # `missing`; an empty box of a required element refuses the sheet (docs/ui-kit.md "Missing elements").- optional: bool = False---LAYOUT = (- Slot("panel", (48, 48, 576, 400), "xy", "the large box at the top left",- "a large ornate panel frame with an empty centre"),- Slot("button", (672, 48, 304, 128), "xy", "the upper box at the top right",- "a wide button in its normal state"),- Slot("button_pressed", (672, 224, 304, 128), "xy", "the box below it",- "the same button pressed in"),- Slot("card", (704, 400, 272, 576), "xy", "the tall box at the right",- "a tall card frame with an empty centre"),- Slot("hp_bar_frame", (48, 496, 608, 112), "x", "the long box at the left below the panel",- "an empty horizontal health bar frame"),- Slot("xp_bar_frame", (48, 656, 608, 112), "x", "the long box below it",- "an empty horizontal experience bar frame"),- Slot("timer_badge", (48, 816, 160, 160), "none", "the small square box at the bottom left",- "a small round badge with an empty centre"),- # The band below the square, on the 2:3 sheet only.- Slot("hp_bar_fill", (48, 1024, 608, 64), "x", "the long thin box at the top left of the band",- "the health bar's fill alone, a bare strip of colour with no frame, rim or end pieces around it",- content=False, inside="hp_bar_frame", optional=True),- Slot("xp_bar_fill", (48, 1136, 608, 64), "x", "the long thin box below it",- "the experience bar's fill alone, the same kind of bare strip in its own colour", content=False,- inside="xp_bar_frame", optional=True),- Slot("slot", (48, 1248, 192, 192), "xy", "the square box below them at the left",- "a square item slot frame with an empty centre", optional=True),- Slot("badge", (288, 1248, 176, 112), "xy", "the small wide box to its right",- "a small counter plate with an empty centre", optional=True),- Slot("pip_on", (512, 1248, 96, 96), "none", "the small circle to the right of that",- "a small round indicator dot, lit", content=False, round=True, optional=True),- Slot("pip_off", (512, 1392, 96, 96), "none", "the small circle below it",- "the same dot unlit", content=False, round=True, optional=True),- Slot("joystick_base", (704, 1024, 272, 272), "none", "the large circle at the right of the band",- "a round touch joystick base", content=False, round=True, optional=True),- Slot("joystick_knob", (768, 1344, 144, 144), "none", "the smaller circle below it",- "the joystick's round knob", content=False, round=True, optional=True),-)-FRAME_COUNT = 7-# Sheet shape -> (the size the layout's boxes are given at, the slots it holds). The 2:3 sheet keeps the-# square's seven boxes where they are and adds the band below them, so a square sheet cuts as it always has.-SHEETS = {- "square": ((REFERENCE, REFERENCE), LAYOUT[:FRAME_COUNT]),- "tall": ((REFERENCE, REFERENCE * 3 // 2), LAYOUT),-}---def sheet_layout(size: tuple[int, int]) -> tuple[tuple[int, int], tuple[Slot, ...]]:- """The reference size and the slots of a sheet of ``size``: square, or 2:3, each within 1 %."""- width, height = size- for (ref_w, ref_h), slots in SHEETS.values():- if abs(width * ref_h - height * ref_w) <= 0.01 * max(width * ref_h, height * ref_w):- return (ref_w, ref_h), slots- raise ValueError(f"a UI kit sheet must be square (1:1, the frames) or 2:3 (the whole kit); "- f"this one is {width}x{height}")---def boxes(size: tuple[int, int]) -> dict[str, tuple[int, int, int, int]]:- """The boxes a sheet of ``size`` holds, as (x, y, w, h) in its pixels, in layout order."""- (ref_w, ref_h), slots = sheet_layout(size)- width, height = size- sx, sy = width / ref_w, height / ref_h- return {slot.name: (round(slot.box[0] * sx), round(slot.box[1] * sy),- round(slot.box[2] * sx), round(slot.box[3] * sy)) for slot in slots}---def _rect(x: int, y: int, w: int, h: int) -> dict[str, int]:- return {"x": int(x), "y": int(y), "w": int(w), "h": int(h)}---def _element_png(name: str) -> str:- """The file name of an element's PNG in the output directory."""- return f"{name}.png"---def _places(slots: tuple[Slot, ...]) -> str:- return "; ".join(f"in {slot.where}, {slot.what}" for slot in slots)---def guide_text(size: tuple[int, int] = (REFERENCE, REFERENCE)) -> str:- """The prompt's half of the guide for a sheet of ``size``: what to draw in each box and how, in layout order."""- _, slots = sheet_layout(size)- if len(slots) == FRAME_COUNT:- return (- "Layout: the last attached image is a layout guide, not part of the artwork. It shows "- f"{len(slots)} blue boxes on a grey sheet. Draw exactly one user interface element inside each box, "- "filling most of its box without touching the box's edges, and leave everything outside the boxes "- f"empty and transparent: {_places(slots)}. Every frame, button and bar has straight, even edges "- "between its corners, so it can be stretched along them: put ornaments only in the corners, and on "- "the bars only at their two ends. Leave every centre empty: no text, no letters, no numbers, no icons "- "and no fill inside the bars. Do not reproduce the layout guide itself: no boxes, guide lines, guide "- "colors or the guide's grey background may appear in the output."- )- frames, band = slots[:FRAME_COUNT], slots[FRAME_COUNT:]- return (- "Layout: the last attached image is a layout guide, not part of the artwork. It shows "- f"{len(slots)} blue boxes and circles on a grey sheet: {len(frames)} in the square at the top and "- f"{len(band)} in the band below it. Draw exactly one user interface element inside each box and circle, "- "filling most of it without touching its edges, and leave everything outside them empty and transparent. "- "In the square "- f"at the top: {_places(frames)}. In the band below it: {_places(band)}. Every frame, button, bar, fill, "- "slot and plate has straight, even edges between its corners, so it can be stretched along them: put "- "ornaments only in the corners, and on the bars and the fills only at their two ends. Each fill is one "- "solid strip with no frame of its own, the same colour all along its length (it may shade from its top "- "edge to its bottom edge), with no marks, segments or highlights along it. Leave the centre of every "- "frame, button, bar frame, slot and plate empty: no text, no letters, no numbers, no icons and no fill "- "inside the bar frames. The two dots, the joystick base and the knob are circles drawn on the guide's "- "circles and seen straight from the front, with nothing square around them: no plate, tile or backing, "- "so the corners around each circle stay empty and transparent; the two dots are the same size. Do not "- "reproduce the layout guide itself: no boxes, circles, guide lines, guide colors or the guide's grey "- "background may appear in the output."- )---def draw_guide(path: Path, size: tuple[int, int] = (REFERENCE, REFERENCE)) -> dict[str, Any]:- """Draw the layout guide at ``path`` and answer its cell: the kind, the size and every box."""- width, height = size- image = Image.new("RGB", (width, height), GUIDE_BACKGROUND)- draw = ImageDraw.Draw(image)- line = max(2, round(3 * width / REFERENCE))- scaled = boxes(size)- shapes = {slot.name: draw.ellipse if slot.round else draw.rectangle for slot in LAYOUT}- for name, (x, y, w, h) in scaled.items():- shapes[name]((x, y, x + w - 1, y + h - 1), outline=GUIDE_BOX, width=line)- Path(path).parent.mkdir(parents=True, exist_ok=True)- image.save(path)- return {"kind": "ui-kit", "width": width, "height": height,- "boxes": {name: _rect(*box) for name, box in scaled.items()}}---def _premultiplied(image: Image.Image) -> Any:- pixels = np.asarray(image.convert("RGBA")).astype(np.float32)- pixels[..., :3] *= pixels[..., 3:] / 255- return pixels---def _stretch_band(pixels: Any) -> tuple[int, int, list[str]]:- """Fixed slices before and after the stretch band along dimension 1 (docs/ui-kit.md "Insets")."""- height, width, _ = pixels.shape- lo = int(width * 0.4)- hi = max(int(width * 0.6), lo + 1)- reference = np.median(pixels[:, lo:hi], axis=1)- error = np.abs(pixels - reference[:, None, :]).max(axis=-1)- spread = error[:, lo:hi].max(axis=1)- plain = ~(error > (2 * spread + 8)[:, None]).any(axis=0)- start = lo- while start > 0 and plain[start - 1]:- start -= 1- end = hi- while end < width and plain[end]:- end += 1- notes = []- if spread.max() > max(64.0, 4 * float(np.median(spread))):- notes.append("the middle of the element is not uniform (an ornament in the middle of an edge?); "- "stretching would smear it")- if (start == lo and lo > 0) or (end == hi and hi < width):- notes.append("an ornament reaches the middle fifth of the element; the insets may not cover it")- before = min(start + MARGIN, lo) if start > 0 else 0- after = min(width - end + MARGIN, width - hi) if end < width else 0- return before, after, notes---def measure_insets(image: Image.Image, stretch: str) -> tuple[dict[str, int], list[str]]:- """Nine-slice insets in the element's pixels, measured along the axes ``stretch`` allows, and review notes."""- if stretch not in STRETCHES:- raise ValueError(f"stretch must be one of {', '.join(STRETCHES)}")- pixels = _premultiplied(image)- insets = {"left": 0, "right": 0, "top": 0, "bottom": 0}- notes: list[str] = []- if stretch in ("xy", "x"):- insets["left"], insets["right"], found = _stretch_band(pixels)- notes += [f"x: {note}" for note in found]- if stretch == "xy":- insets["top"], insets["bottom"], found = _stretch_band(pixels.transpose(1, 0, 2))- notes += [f"y: {note}" for note in found]- return insets, notes---def _interior_run(line: Any, centre: Any, middle: int) -> tuple[int, int]:- near = np.abs(line - centre).max(axis=-1) <= PADDING_SPAN- smooth = np.abs(np.diff(line, axis=0)).max(axis=-1) <= PADDING_STEP- if not near[middle]:- return middle, middle + 1- start, end = middle, middle + 1- while start > 0 and near[start - 1] and smooth[start - 1]:- start -= 1- while end < len(near) and near[end] and smooth[end - 1]:- end += 1- return start, end---def measure_padding(image: Image.Image) -> tuple[dict[str, int], list[str]]:- """Distances from each edge to the element's empty interior (docs/ui-kit.md "Padding"), and review notes."""- pixels = _premultiplied(image)- height, width, _ = pixels.shape- cy, cx = height // 2, width // 2- rows, cols = slice(max(0, cy - 2), cy + 3), slice(max(0, cx - 2), cx + 3)- centre = np.median(pixels[rows, cols].reshape(-1, 4), axis=0)- across, down = np.median(pixels[rows], axis=0), np.median(pixels[:, cols], axis=1)- x0, x1 = _interior_run(across, centre, cx)- y0, y1 = _interior_run(down, centre, cy)- interior_values = np.concatenate((across[x0:x1], down[y0:y1]))- low, high = interior_values.min(axis=0) - PADDING_STEP, interior_values.max(axis=0) + PADDING_STEP-- def interior(x: int, y: int) -> bool:- return bool(((pixels[y, x] >= low) & (pixels[y, x] <= high)).all())-- shrink = 0- while True:- left, top, right, bottom = x0 + shrink, y0 + shrink, x1 - 1 - shrink, y1 - 1 - shrink- if left >= right or top >= bottom:- left, right = min(left, cx), max(right, cx)- top, bottom = min(top, cy), max(bottom, cy)- break- if all(interior(x, y) for x, y in ((left, top), (right, top), (left, bottom), (right, bottom))):- break- shrink += 1- padding = {"left": min(left + MARGIN, cx), "right": min(width - 1 - right + MARGIN, width - 1 - cx),- "top": min(top + MARGIN, cy), "bottom": min(height - 1 - bottom + MARGIN, height - 1 - cy)}- notes = []- if 4 * (width - padding["left"] - padding["right"]) < width or 4 * (height - padding["top"] - padding["bottom"]) < height:- notes.append("the content area is less than a quarter of the element; its centre is probably not empty")- return padding, notes---def measure_round(image: Image.Image) -> list[str]:- """Review notes for a round part: its cut's corners, outside the ellipse its bounding box holds, are empty."""- alpha = np.asarray(image.convert("RGBA"))[..., 3]- height, width = alpha.shape- yy, xx = np.indices((height, width))- outside = ((xx + 0.5 - width / 2) / (width / 2)) ** 2 + ((yy + 0.5 - height / 2) / (height / 2)) ** 2 > 1- if outside.any() and (alpha[outside] >= 128).mean() > ROUND_CORNER_FILL:- return ["its corners are filled: it was drawn on a square plate or backing, not as a circle; regenerate it"]- return []---def _runs(mask: Any) -> list[tuple[int, int, int]]:- runs = []- for y in np.flatnonzero(mask.any(axis=1)):- edges = np.diff(np.concatenate(([0], mask[y].astype(np.int8), [0])))- for x0, x1 in zip(np.flatnonzero(edges == 1), np.flatnonzero(edges == -1)):- runs.append((int(y), int(x0), int(x1)))- return runs---def _parts(mask: Any) -> list[dict[str, Any]]:- """8-connected parts of ``mask``: their runs, pixel count, bounding box and centroid."""- runs = _runs(mask)- parent = list(range(len(runs)))-- def find(index: int) -> int:- while parent[index] != index:- parent[index] = parent[parent[index]]- index = parent[index]- return index-- previous: list[int] = []- current: list[int] = []- row = None- for index, (y, x0, x1) in enumerate(runs):- if y != row:- previous = current if row == y - 1 else []- current, row = [], y- for other in previous:- _, ox0, ox1 = runs[other]- if ox0 <= x1 and x0 <= ox1: # touching rows; one column apart counts (diagonal)- parent[find(other)] = find(index)- current.append(index)- groups: dict[int, list[int]] = {}- for index in range(len(runs)):- groups.setdefault(find(index), []).append(index)- parts = []- for members in groups.values():- spans = [runs[i] for i in members]- count = sum(x1 - x0 for _, x0, x1 in spans)- sum_x = sum((x0 + x1 - 1) * (x1 - x0) / 2 for _, x0, x1 in spans)- sum_y = sum(y * (x1 - x0) for y, x0, x1 in spans)- x_min, x_max = min(x0 for _, x0, _ in spans), max(x1 for _, _, x1 in spans)- y_min, y_max = min(y for y, _, _ in spans), max(y for y, _, _ in spans) + 1- parts.append({"runs": spans, "pixels": count, "centroid": (sum_x / count, sum_y / count),- "bbox": (x_min, y_min, x_max, y_max)})- parts.sort(key=lambda part: (part["bbox"][1], part["bbox"][0]))- return parts---def _bbox(parts: list[dict[str, Any]]) -> tuple[int, int, int, int]:- """The bounding box (x0, y0, x1, y1) of ``parts``."""- return (min(part["bbox"][0] for part in parts), min(part["bbox"][1] for part in parts),- max(part["bbox"][2] for part in parts), max(part["bbox"][3] for part in parts))---def _off_centre(assigned: dict[str, list[dict[str, Any]]],- scaled: dict[str, tuple[float, float, float, float]]) -> list[str]:- """The boxes, in layout order, whose parts are centred outside the box: in the gap beside it or further, where the- drawing does not say which element they are."""- off = []- for name, parts in assigned.items():- if parts:- x, y, w, h = scaled[name]- x0, y0, x1, y1 = _bbox(parts)- if not (x <= (x0 + x1) / 2 <= x + w and y <= (y0 + y1) / 2 <= y + h):- off.append(name)- return off---def _fit(assigned: dict[str, list[dict[str, Any]]],- scaled: dict[str, tuple[float, float, float, float]]) -> tuple[float, float, float, float] | None:- """The drift (sx, tx, sy, ty) that moves the layout's box centres closest (least squares) to the centres of what- each box holds; None from fewer than FIT_MIN_BOXES boxes that hold parts."""- centres, drawn = [], []- for name, parts in assigned.items():- if parts:- x, y, w, h = scaled[name]- x0, y0, x1, y1 = _bbox(parts)- centres.append((x + w / 2, y + h / 2))- drawn.append(((x0 + x1) / 2, (y0 + y1) / 2))- if len(centres) < FIT_MIN_BOXES:- return None- centres_array, drawn_array = np.asarray(centres), np.asarray(drawn)- fit: list[float] = []- for axis in (0, 1):- box, held = centres_array[:, axis], drawn_array[:, axis]- if np.ptp(box) < 1: # every box centred on one line along this axis: an offset alone- fit += [1.0, float(np.mean(held - box))]- else:- scale, offset = np.polyfit(box, held, 1)- fit += [float(scale), float(offset)]- sx, tx, sy, ty = fit- return sx, tx, sy, ty---def _drift_limits(unit: float) -> tuple[float, float]:- """How far the scale of a drift the cut considers may lie from 1, and its offset from 0, along each axis (``unit``- sheet pixels to a layout pixel at 1024): the range a cut accepts and DRIFT_MARGIN of it beyond either end."""- return DRIFT_SCALE * (1 + DRIFT_MARGIN), DRIFT_OFFSET * unit * (1 + DRIFT_MARGIN)---def _considered(drift: tuple[float, float, float, float], unit: float) -> bool:- """Whether the cut considers ``drift`` (`_drift_limits`)."""- scale, offset = _drift_limits(unit)- sx, tx, sy, ty = drift- return max(abs(sx - 1), abs(sy - 1)) <= scale and max(abs(tx), abs(ty)) <= offset---@dataclass(frozen=True)-class Reading:- """A reading of the drawing (docs/ui-kit.md "Reading the drawing"). ``drift`` (sx, tx, sy, ty) moves each layout- box (x, y, w, h) to (x sx + tx, y sy + ty, w sx, h sy). ``boxes`` names the box each part goes to (None for a part- in no box), in the order of the parts read. ``cost``, in sheet pixels, is the least cost of a reading that puts the- parts so; ``drift`` reads the drawing so, at that cost to within a millionth of a pixel."""-- drift: tuple[float, float, float, float]- boxes: tuple[str | None, ...]- cost: float---@dataclass(frozen=True)-class Judgment:- """What the cut's search found in a drawing (`_judge`): the ``parts`` read; the least cost of any reading the cut- considers (``least``) and of one whose every required box holds a part (``least_valid``), exact when the search- ran to its end and otherwise proven lower bounds; the readings the cut is decided among (``candidates``), cheapest- first (for a drawing the search stopped on as ambiguous, those it had found); when the search stopped at its work- bound, the cost every reading is proven to exceed (``proven``); and the spans of drifts it took (``nodes``)."""-- parts: list[dict[str, Any]]- least: float- least_valid: float- candidates: tuple[Reading, ...]- proven: float | None- nodes: int- drawing: _Drawing---class Refusal(ValueError):- """A sheet `split_ui_kit` refuses (docs/ui-kit.md "Reading the drawing"): its message, its ``reason``- (``drifted``, ``required``, ``ambiguous``, ``off-centre`` or ``off-layout``), the ``parts`` read and the ``least``- cost of a reading (`Judgment`); a drawing that fits the layout in two ways also gives the two readings- (``witnesses``)."""-- def __init__(self, message: str, reason: str, judgment: Judgment, witnesses: tuple[Reading, ...] = ()) -> None:- super().__init__(message)- self.reason = reason- self.parts = judgment.parts- self.least = judgment.least- self.witnesses = witnesses---Row = tuple[float, float, float] # (a, b, c): a s + b t <= c, a half-plane of the drifts (s, t) along one axis-Span = tuple[float, float, float, float] # (s0, s1, t0, t1): the drifts along one axis, s0 <= s <= s1, t0 <= t <= t1---class _Axis:- """The layout's boxes and the parts along one axis: each box's edges (``e0``, ``e1``) and its edges widened by the- reach (``lo``, ``hi``), as a row of one value a box; each part's centroid (``c``) and its bounding box's edges- (``p0``, ``p1``, exclusive), as a column of one value a part."""-- def __init__(self, low: Any, high: Any, reach: float, centre: Any, first: Any, last: Any) -> None:- self.e0, self.e1 = low[None, :], high[None, :]- self.lo, self.hi = self.e0 - reach, self.e1 + reach- self.c, self.p0, self.p1 = centre[:, None], first[:, None], last[:, None]- self.extent = float(self.hi.max(initial=1.0))-- def held_at(self, s: float, t: float) -> Any:- """[part, box]: the box, moved by (s, t) and widened, holds the part's centroid (its low edge in, its high edge- out, as `_parts` gives a bounding box)."""- return (self.lo * s + t <= self.c) & (self.c < self.hi * s + t)-- def short_at(self, s: float, t: float) -> Any:- """[part, box]: how far the part's two sides fall short of lying CLEARANCE inside the box moved by (s, t)."""- return (np.maximum(0, self.e0 * s + t + CLEARANCE - self.p0)- + np.maximum(0, self.p1 - (self.e1 * s + t) + CLEARANCE))-- def status(self, span: Span, rows: Any) -> tuple[Any, Any]:- """[part, box] for the parts ``rows`` (with ends one a span, [span, part, box]): the widened box holds the- centroid at every drift of ``span``, and at none. Every box lies more than the reach in from the sheet's edges,- so its widened edges are positive: least at (s0, t0) and greatest at (s1, t1)."""- s0, s1, t0, t1 = span- c = self.c[rows]- return ((self.lo * s1 + t1 <= c) & (c < self.hi * s0 + t0),- (c < self.lo * s0 + t0) | (c >= self.hi * s1 + t1))-- def least_short(self, span: Span, rows: Any, boxes: Any = None) -> Any:- """A lower bound, over the drifts of ``span``, of `short_at` (each side at its own corner): [part, box] for the- parts ``rows``, or, given each one's box (``boxes``), [part]; with ends one a span, a span axis first."""- s0, s1, t0, t1 = span- if boxes is None:- e0, e1, p0, p1 = self.e0, self.e1, self.p0[rows], self.p1[rows]- else:- e0, e1, p0, p1 = self.e0[0, boxes], self.e1[0, boxes], self.p0[rows, 0], self.p1[rows, 0]- return np.maximum(0, e0 * s0 + t0 + CLEARANCE - p0) + np.maximum(0, p1 - (e1 * s1 + t1) + CLEARANCE)-- def hinges(self, parts: Any, boxes: Any) -> Any:- """The rows (a, b, c) whose max(0, a s + b t + c) are the shortfalls of the sides of ``parts`` in ``boxes``."""- n = len(parts)- out = np.empty((2 * n, 3))- out[:n, 0], out[:n, 1], out[:n, 2] = self.e0[0, boxes], 1.0, CLEARANCE - self.p0[parts, 0]- out[n:, 0], out[n:, 1], out[n:, 2] = -self.e1[0, boxes], -1.0, self.p1[parts, 0] + CLEARANCE- return out-- def within(self, part: int, box: int) -> list[Row]:- """The rows that keep the part's centroid in the widened box: both edges in, so that at an edge both readings- are admitted, each at the cost it reaches beside the edge."""- c = float(self.c[part, 0])- return [(float(self.lo[0, box]), 1.0, c), (-float(self.hi[0, box]), -1.0, -c)]-- def beside(self, part: int, box: int, span: Span) -> list[Row]:- """The rows, one a way, that keep the part's centroid out of the widened box at some drift of ``span``: below- its low edge, or at or past its high edge."""- s0, s1, t0, t1 = span- c, lo, hi = float(self.c[part, 0]), float(self.lo[0, box]), float(self.hi[0, box])- return ([(-lo, -1.0, -c)] if lo * s1 + t1 >= c else []) + ([(hi, 1.0, c)] if hi * s0 + t0 <= c else [])---def _least_on_axis(span: Span, rows: list[Row], hinges: Any) -> tuple[float, tuple[float, float] | None]:- """The least, over the drifts (s, t) of ``span`` that keep every row of ``rows``, of the sum over the rows (a, b,- c) of ``hinges`` of max(0, a s + b t + c), and a drift that reaches it; (inf, None) when no drift keeps the rows.- The sum is convex and linear between the lines on which a row binds or a hinge turns, so it is least where two of- them cross. A hinge that does not turn within ``span`` is linear there and draws no line."""- s0, s1, t0, t1 = span- bounds = np.array([(-1.0, 0.0, -s0), (1.0, 0.0, s1), (0.0, -1.0, -t0), (0.0, 1.0, t1), *rows])- at = hinges[:, :1] * np.array([s0, s0, s1, s1]) + hinges[:, 1:2] * np.array([t0, t1, t0, t1]) + hinges[:, 2:]- rising = at.min(axis=1, initial=np.inf) >= 0- turning = hinges[~rising & (at.max(axis=1, initial=-np.inf) > 0)]- linear = hinges[rising].sum(axis=0)- lines = np.concatenate((bounds, turning * (1, 1, -1)))- a, b, c = lines.T- i, j = np.triu_indices(len(lines), 1)- det = a[i] * b[j] - a[j] * b[i]- crossing = np.abs(det) > 1e-12- i, j, det = i[crossing], j[crossing], det[crossing]- s, t = (c[i] * b[j] - c[j] * b[i]) / det, (a[i] * c[j] - a[j] * c[i]) / det- kept = (bounds[:, :1] * s + bounds[:, 1:2] * t <= bounds[:, 2:] + 1e-9 * (1 + np.abs(bounds[:, 2:]))).all(axis=0)- if not kept.any():- return math.inf, None- s, t = s[kept], t[kept]- value = linear[0] * s + linear[1] * t + linear[2]- if len(turning):- value = value + np.maximum(0, turning[:, :1] * s + turning[:, 1:2] * t + turning[:, 2:]).sum(axis=0)- k = int(np.argmin(value))- return max(0.0, float(value[k])), (float(s[k]), float(t[k]))---def _middle(span: Span, rows: list[Row]) -> tuple[float, float] | None:- """The mean of the corners of the drifts of ``span`` that keep every row: inside them all when they leave room."""- s0, s1, t0, t1 = span- lines = np.array([(-1.0, 0.0, -s0), (1.0, 0.0, s1), (0.0, -1.0, -t0), (0.0, 1.0, t1), *rows])- a, b, c = lines.T- i, j = np.triu_indices(len(lines), 1)- det = a[i] * b[j] - a[j] * b[i]- crossing = np.abs(det) > 1e-12- i, j, det = i[crossing], j[crossing], det[crossing]- s, t = (c[i] * b[j] - c[j] * b[i]) / det, (a[i] * c[j] - a[j] * c[i]) / det- kept = (lines[:, :1] * s + lines[:, 1:2] * t <= lines[:, 2:] + 1e-9 * (1 + np.abs(lines[:, 2:]))).all(axis=0)- return (float(s[kept].mean()), float(t[kept].mean())) if kept.any() else None---def _room(span: Span, rows: list[Row]) -> bool:- """Whether the drifts of ``span`` that keep ``rows`` leave room: one drift keeps every row with a margin. The rows'- edges are taken closed so that a reading's least cost is reached, but a box's high edge, and its low edge for a part- kept out of it, are open: rows that leave room only on an edge, such as a part kept out of two widened boxes that- touch, give a reading no drift reads."""- middle = _middle(span, rows)- if middle is None:- return False- if not rows:- return True- a, b, c = np.array(rows).T- return bool((c - a * middle[0] - b * middle[1]).min() > 1e-9)---class _Drawing:- """The parts and the layout's boxes of a sheet, as arrays: the reading at a drift, and the bounds the search takes- over a box of drifts (``span``: sx0, sx1, tx0, tx1, sy0, sy1, ty0, ty1)."""-- def __init__(self, parts: list[dict[str, Any]], size: tuple[int, int]) -> None:- layout = boxes(size)- _, slots = sheet_layout(size)- self.parts, self.layout, self.names = parts, layout, list(layout)- self.required = frozenset(index for index, slot in enumerate(slots) if not slot.optional)- self.unit = size[0] / REFERENCE- reach = GAP / 2 * self.unit- box = np.asarray(list(layout.values()), dtype=float)- centroid = np.asarray([part["centroid"] for part in parts], dtype=float).reshape(-1, 2)- self.bbox = bbox = np.asarray([part["bbox"] for part in parts], dtype=float).reshape(-1, 4)- self.x = _Axis(box[:, 0], box[:, 0] + box[:, 2], reach, centroid[:, 0], bbox[:, 0], bbox[:, 2])- self.y = _Axis(box[:, 1], box[:, 1] + box[:, 3], reach, centroid[:, 1], bbox[:, 1], bbox[:, 3])- # A part in no box costs about the least a part of its size costs against a box whose widened box does not- # hold its centroid: the same under every drift, so it never pulls the reading, and more for a larger part, so- # that leaving a large element that overflows its box out of every box never costs less than keeping it.- self.loose = reach + CLEARANCE + np.minimum(bbox[:, 2] - bbox[:, 0], bbox[:, 3] - bbox[:, 1]) / 2- # Widened boxes overlap only where rounding a sheet's boxes narrowed a gap; a part in both goes to the first.- overlap = ((self.x.lo.T < self.x.hi) & (self.x.lo < self.x.hi.T)- & (self.y.lo.T < self.y.hi) & (self.y.lo < self.y.hi.T))- self.earlier = np.triu(overlap, 1) # [box, later box]-- def read(self, drift: tuple[float, float, float, float]) -> tuple[float, tuple[int, ...]]:- """The reading at ``drift``: its cost, and each part's box (its index in layout order, -1 for none)."""- sx, tx, sy, ty = drift- held = self.x.held_at(sx, tx) & self.y.held_at(sy, ty)- placed = held.any(axis=1)- key = np.where(placed, held.argmax(axis=1), -1)- short = self.x.short_at(sx, tx) + self.y.short_at(sy, ty)- inside = np.take_along_axis(short, np.maximum(key, 0)[:, None], axis=1)[:, 0]- return float(np.where(placed, inside, self.loose).sum()), tuple(key.tolist())-- def valid(self, key: tuple[int, ...]) -> bool:- """Whether every required box holds a part."""- return self.required <= set(key)-- def named(self, key: tuple[int, ...]) -> tuple[str | None, ...]:- """Each part's box by name, None for none."""- return tuple(self.names[box] if box >= 0 else None for box in key)-- def assigned(self, key: tuple[int, ...]) -> dict[str, list[dict[str, Any]]]:- """The parts by box, in layout order."""- assigned: dict[str, list[dict[str, Any]]] = {name: [] for name in self.names}- for part, box in zip(self.parts, key):- if box >= 0:- assigned[self.names[box]].append(part)- return assigned-- def bound(self, spans: list[tuple[float, ...]], open_: Any, fixed: Any) -> tuple[Any, dict[str, Any]]:- """For each span of ``spans``, a lower bound of the cost of every reading at its drifts, and what the span- decides of the parts still open (``open_``; ``fixed`` gives every other part's box, -1 for none and -2 for an- open part), one row a span. For each open part, the least it can cost (``least``): in a box that may hold its- centroid somewhere in the span, each of its sides at its own corner, or in no box when no box holds it- everywhere (``free``). A box after one that holds it everywhere never holds it. Several spans are bounded in- one pass over the arrays."""- ends = np.asarray(spans, dtype=float)[:, :, None, None] # [span, end, part, box]- sx, sy = tuple(ends[:, k] for k in range(4)), tuple(ends[:, k] for k in range(4, 8))- inx, outx = self.x.status(sx, open_)- iny, outy = self.y.status(sy, open_)- held = inx & iny- may = ~(outx | outy) & ~((np.cumsum(held, axis=-1) - held) > 0)- free = ~held.any(axis=-1)- short = self.x.least_short(sx, open_) + self.y.least_short(sy, open_)- least = np.where(may, short, np.inf).min(axis=-1, initial=np.inf)- least = np.where(free, np.minimum(least, self.loose[open_]), least)- placed = np.flatnonzero(fixed >= 0)- settled = ((self.x.least_short(sx, placed, fixed[placed]) + self.y.least_short(sy, placed, fixed[placed]))- .sum(axis=(-2, -1)) + self.loose[fixed == -1].sum())- return least.sum(axis=-1) + settled, {"inx": inx, "iny": iny, "may": may, "free": free, "short": short,- "least": least}-- def count(self, span: tuple[float, ...], parts: Any, rows: Any, info: dict[str, Any]) -> float:- """How many ways the span may read the undecided ``parts`` (``rows`` of the open parts `bound` gave ``info``- of): the product of the lengths of their `outcomes`, counted without listing them."""- may, free = info["may"][rows], info["free"][rows]- out = np.zeros(may.shape) # [part, box]: the ways its centroid lies out of the widened box- for axis, side, inside in ((self.x, span[:4], info["inx"][rows]), (self.y, span[4:], info["iny"][rows])):- s0, s1, t0, t1 = side- c = axis.c[parts]- out += ~inside * ((axis.lo * s1 + t1 >= c).astype(float) + (axis.hi * s0 + t0 <= c))- loose = np.where(may, out, 1.0).prod(axis=1)- if self.earlier.any():- held = (np.where(may[:, :, None] & self.earlier[None], out[:, :, None], 1.0).prod(axis=1) * may).sum(axis=1)- else:- held = may.sum(axis=1)- return float(np.prod(held + np.where(free, loose, 0.0)))-- def outcomes(self, span: tuple[float, ...], part: int, row: int,- info: dict[str, Any]) -> list[tuple[int, list[Row], list[Row]]]:- """The ways the span may read an undecided part (``row`` of the open parts `bound` gave ``info`` of): its box- (-1 for none) and the rows along x and along y that read it so. A part in a box is out of every earlier box- whose widened box overlaps it; a part in no box is out of every box that may hold it, along x or along y."""- sx, sy = span[:4], span[4:]- may = info["may"][row]-- def apart(others: Any) -> list[tuple[list[Row], list[Row]]]:- """The ways the centroid lies out of each widened box of ``others``: along x or along y, at an edge each."""- choices = [[("x", way) for way in (self.x.beside(part, box, sx) if not info["inx"][row, box] else [])]- + [("y", way) for way in (self.y.beside(part, box, sy) if not info["iny"][row, box] else [])]- for box in others]- return [([way for axis, way in term if axis == "x"], [way for axis, way in term if axis == "y"])- for term in itertools.product(*choices)]-- ways = []- for box in map(int, np.flatnonzero(may)):- rx = [] if info["inx"][row, box] else self.x.within(part, box)- ry = [] if info["iny"][row, box] else self.y.within(part, box)- for ex, ey in apart(np.flatnonzero(self.earlier[:box, box] & may[:box])):- ways.append((box, rx + ex, ry + ey))- if info["free"][row]:- ways += [(-1, ex, ey) for ex, ey in apart(np.flatnonzero(may))]- return ways---def _split(span: tuple[float, ...], drawing: _Drawing) -> tuple[tuple[float, ...], tuple[float, ...], float]:- """The two halves of ``span`` across its widest side, measured in how far it moves the boxes, and that width."""- sx0, sx1, tx0, tx1, sy0, sy1, ty0, ty1 = span- widths = [(sx1 - sx0) * drawing.x.extent, tx1 - tx0, (sy1 - sy0) * drawing.y.extent, ty1 - ty0]- side = int(np.argmax(widths))- middle = (span[2 * side] + span[2 * side + 1]) / 2- low, high = list(span), list(span)- low[2 * side + 1], high[2 * side] = middle, middle- return tuple(low), tuple(high), max(widths)---class _Search:- """The exact search for the least-cost readings of a drawing (`_judge`): best-first branch and bound over spans of- drifts."""-- def __init__(self, drawing: _Drawing) -> None:- self.drawing = drawing- scale, offset = _drift_limits(drawing.unit)- self.region = (1 - scale, 1 + scale, -offset, offset) * 2- self.best = math.inf # the least cost found- self.exact = math.inf # the least cost of a span solved whole- # Every reading found within 2 TIE of the least cost, by its key (each part's box): its least cost, a drift- # that reaches it, and how it was solved (the spans and rows along x and y; None for a reading at one drift).- self.found: dict[tuple[int, ...], tuple[float, tuple[float, float, float, float], Any]] = {}- self.close: set[tuple[int, ...]] = set() # readings that hold every required box, at a cost of TIE or less- self.nodes = 0-- def note(self, key: tuple[int, ...], cost: float, drift: tuple[float, float, float, float],- solved: Any = None) -> None:- self.best = min(self.best, cost)- if cost <= self.best + 2 * TIE and cost < self.found.get(key, (math.inf,))[0]:- self.found[key] = (cost, drift, solved)- if cost <= TIE and self.drawing.valid(key):- self.close.add(key)-- def read(self, drift: tuple[float, float, float, float]) -> None:- cost, key = self.drawing.read(drift)- self.note(key, cost, drift)-- def solve(self, span: tuple[float, ...], fixed: Any, undecided: Any,- ways: list[list[tuple[int, list[Row], list[Row]]]], floors: Any, rest: float) -> None:- """Every reading of a span solved whole: for each way of reading its undecided parts whose bound may still come- within 2 TIE of the least cost, its least cost along each axis (`_least_on_axis`). A way whose rows leave no- room (`_room`) is read at no drift and is not a reading."""- drawing = self.drawing- sx, sy = span[:4], span[4:]- least: dict[Any, tuple[float, Any]] = {}- for choice in itertools.product(*ways):- if rest + sum(floor[box] for floor, (box, _, _) in zip(floors, choice)) > self.best + 2 * TIE:- continue- key = fixed.copy()- rows_x: list[Row] = []- rows_y: list[Row] = []- for part, (box, rx, ry) in zip(undecided, choice):- key[part] = box- rows_x += rx- rows_y += ry- placed = np.flatnonzero(key >= 0)- places = key.tobytes()- point = []- cost = float(drawing.loose[key < 0].sum())- for axis, side, rows in ((drawing.x, sx, rows_x), (drawing.y, sy, rows_y)):- memo = (axis is drawing.x, places, tuple(rows))- if memo not in least:- least[memo] = _least_on_axis(side, rows, axis.hinges(placed, key[placed]))- value, at = least[memo]- if at is None:- break- cost += value- point += at- else:- # a way that could change what the search keeps must be one some drift reads- if cost <= self.best + 2 * TIE and not (_room(sx, rows_x) and _room(sy, rows_y)):- continue- self.exact = min(self.exact, cost)- self.note(tuple(key.tolist()), cost, tuple(point), (sx, rows_x, sy, rows_y))-- def run(self) -> Judgment:- drawing = self.drawing- count = len(drawing.parts)- region = self.region- for drift in ((1.0, 0.0, 1.0, 0.0), _centre(region)):- self.read(drift)- open_, fixed = np.arange(count), np.full(count, -2)- tick = itertools.count()- heap = [(float(drawing.bound([region], open_, fixed)[0][0]), 0, next(tick), region, open_, fixed)]- proven = None- while heap and len(self.close) < 2:- floor = min(heap[0][0], self.exact)- if self.nodes >= SEARCH_NODES and floor > TIE:- proven = floor # every reading costs more than TIE: the drawing does not lie on the layout- break- bound, depth, _, span, open_, fixed = heapq.heappop(heap)- if bound > self.best + 2 * TIE:- break- self.nodes += 1- bounds, info = drawing.bound([span], open_, fixed)- bound, info = float(bounds[0]), {name: value[0] for name, value in info.items()}- may, free = info["may"], info["free"]- number = may.sum(axis=1)- decided = (number == 0) | ((number == 1) & ~free)- fixed = fixed.copy()- fixed[open_[decided]] = np.where(number[decided] == 0, -1, may[decided].argmax(axis=1))- rows = np.flatnonzero(~decided)- undecided = open_[rows]- low, high, width = _split(span, drawing)- if drawing.count(span, undecided, rows, info) <= LEAF_WAYS or width < LEAF_WIDTH:- ways = [drawing.outcomes(span, int(part), int(row), info) for part, row in zip(undecided, rows)]- # the bound of each way of reading a part: its least in each box, or in none- floors = [{**dict(zip(map(int, np.flatnonzero(may[row])), info["short"][row, may[row]].tolist())),- -1: float(drawing.loose[part])} for part, row in zip(undecided, rows)]- self.solve(span, fixed, undecided, ways, floors, bound - float(info["least"][rows].sum()))- continue- self.read(_centre(span))- for half, half_bound in zip((low, high), drawing.bound([low, high], undecided, fixed)[0].tolist()):- if half_bound <= self.best + 2 * TIE:- heapq.heappush(heap, (half_bound, depth - 1, next(tick), half, undecided, fixed))- lower = min(heap[0][0] if heap else math.inf, self.exact, self.best)- return self.judgment(proven, lower)-- def judgment(self, proven: float | None, lower: float) -> Judgment:- """The judgment of what the search found (`Judgment`)."""- drawing = self.drawing- if proven is not None:- return Judgment(drawing.parts, proven, proven, (), proven, self.nodes, drawing)- found = {key: entry for key, entry in self.found.items() if entry[0] <= self.best + 2 * TIE}- if len(self.close) > 1:- # stopped early: two readings that hold every required box cost TIE or less, so both lie within TIE of- # the least cost of such a reading, which lies within TIE of the least cost, and neither is drifted- least = least_valid = lower- picked = sorted(self.close)- else:- least = self.best- least_valid = min((entry[0] for key, entry in found.items() if drawing.valid(key)), default=math.inf)- whole = least_valid <= least + TIE # the readings that hold every required box are the candidates- tier = least_valid if whole else least- picked = [key for key, entry in found.items()- if entry[0] <= tier + TIE and (drawing.valid(key) or not whole)]- picked.sort(key=lambda key: (found[key][0], key))- candidates = tuple(Reading(self.inside(key, *found[key][1:]), drawing.named(key), found[key][0])- for key in picked)- return Judgment(drawing.parts, least, least_valid, candidates, None, self.nodes, drawing)-- def inside(self, key: tuple[int, ...], drift: tuple[float, float, float, float],- solved: Any) -> tuple[float, float, float, float]:- """A drift that reads the drawing as ``key`` says at its least cost, to within a millionth of a pixel. A span- solved whole reaches its least cost at a corner, which may lie on the edge of a widened box, where the drawing- reads otherwise: the corner is moved toward the middle of the drifts the reading's rows keep, by the smallest- step that reads it so."""- if solved is None or self.drawing.read(drift)[1] == key:- return drift- sx, rows_x, sy, rows_y = solved- middle_x, middle_y = _middle(sx, rows_x), _middle(sy, rows_y)- if middle_x is None or middle_y is None:- return drift- start = np.asarray(drift)- towards = np.array((*middle_x, *middle_y)) - start- for step in 10.0 ** np.arange(-12, -2):- sx_, tx_, sy_, ty_ = (float(value) for value in start + step * towards)- if self.drawing.read((sx_, tx_, sy_, ty_))[1] == key:- return sx_, tx_, sy_, ty_- return drift---def _centre(span: tuple[float, ...]) -> tuple[float, float, float, float]:- sx0, sx1, tx0, tx1, sy0, sy1, ty0, ty1 = span- return (sx0 + sx1) / 2, (tx0 + tx1) / 2, (sy0 + sy1) / 2, (ty0 + ty1) / 2---def _judge(parts: list[dict[str, Any]], size: tuple[int, int]) -> Judgment:- """Search the drawing for its least-cost readings (docs/ui-kit.md "Reading the drawing"). A reading at a drift puts- each part in the first box, in layout order, whose box moved by the drift and widened by half the gap holds its- centroid, or in none. Its cost adds, for each part in a box, how far each of its sides falls short of lying- CLEARANCE px inside the moved box, and for each part in no box `_Drawing.loose`. The search is exact: no grid, no- sampling. It is best-first branch and bound over the drifts the cut considers: a span of drifts is bounded below by- the least each part can cost in it, split across its widest side, and solved whole once its undecided parts can be- read in at most LEAF_WAYS ways, each then a convex piecewise-linear cost along each axis, least at a corner. A span- bounded above the least cost found plus 2 TIE is dropped: the readings the cut is decided among lie within it. The- search stops early once it has found two readings that hold every required box at a cost of TIE or less (the cut- then refuses the drawing as ambiguous, whatever else there is to find), and after SEARCH_NODES spans once every- reading is proven to cost more than TIE."""- return _Search(_Drawing(parts, size)).run()---def _drifted(drift: tuple[float, float, float, float], unit: float) -> str:- sx, tx, sy, ty = drift- return (f"the drawing drifted further from the layout than a cut accepts: fitted to it, the layout is scaled "- f"{sx:.3f} along x and {sy:.3f} along y and offset {tx:.1f}, {ty:.1f} px, where a cut accepts a scale "- f"from {1 - DRIFT_SCALE:g} to {1 + DRIFT_SCALE:g} and an offset of at most {DRIFT_OFFSET * unit:g} px "- "along each axis; generate the sheet again")---def _centred(drawing: _Drawing, key: tuple[int, ...], cost: float) -> tuple[float, float, float, float] | None:- """A drift whose cost is within TIE of ``cost``, that keeps the parts ``key`` places in their widened boxes and puts- the centre of each box's parts' bounding box inside the moved box; None when there is none."""- scale, offset = _drift_limits(drawing.unit)- held = np.asarray(key, dtype=int)- placed = np.flatnonzero(held >= 0)- found = []- for axis, index in ((drawing.x, 0), (drawing.y, 1)):- rows = [row for part in placed for row in axis.within(int(part), int(held[part]))]- for box in sorted(set(held[placed].tolist())):- members = np.flatnonzero(held == box)- middle = float(drawing.bbox[members, index].min() + drawing.bbox[members, index + 2].max()) / 2- rows += [(float(axis.e0[0, box]), 1.0, middle), (-float(axis.e1[0, box]), -1.0, -middle)]- found.append(_least_on_axis((1 - scale, 1 + scale, -offset, offset), rows, axis.hinges(placed, held[placed])))- (vx, px), (vy, py) = found- if px is None or py is None or vx + vy + float(drawing.loose[held < 0].sum()) > cost + TIE:- return None- return px[0], px[1], py[0], py[1]---def _decide(judgment: Judgment) -> Reading:- """The cut: the one candidate, at the drift its report gives; or the refusal the judgment calls for, in the order- docs/ui-kit.md "Reading the drawing" gives. The report's drift is the first of the layout's own boxes, the- least-squares fit of the cut's assignment (`_fit`), the centring drift and the cut's least-cost drift that reads- the cut at a cost within TIE of its own."""- drawing = judgment.drawing- if judgment.proven is not None:- raise Refusal("the drawing does not lie on the layout under any drift a cut accepts: every reading leaves its "- f"parts at least {math.floor(judgment.proven)} px across their boxes' edges or in no box; "- "generate the sheet again", "off-layout", judgment)- candidates = judgment.candidates- keys = [tuple(drawing.names.index(name) if name is not None else -1 for name in reading.boxes)- for reading in candidates]- first = candidates[0]- if first.cost > TIE:- fit = _fit(drawing.assigned(keys[0]), dict(drawing.layout))- if fit is not None and not _considered(fit, drawing.unit) and drawing.read(fit)[0] < first.cost - TIE:- raise Refusal(_drifted(fit, drawing.unit), "drifted", judgment)- if not drawing.valid(keys[0]):- empty = [drawing.names[box] for box in sorted(drawing.required) if all(box not in key for key in keys)]- if empty:- holds = "its box holds" if len(empty) == 1 else "their boxes hold"- raise Refusal(f"{', '.join(empty)}: {holds} no element; generate the sheet again", "required", judgment)- if len(candidates) > 1:- one, other = keys[0], keys[1]- changed = [drawing.names[box] for box in sorted(- {box for pair in zip(one, other) if pair[0] != pair[1] for box in pair} - {-1})]- single = len(changed) == 1- one_or_more = ("this element", "element it is") if single else ("these elements", "elements they are")- raise Refusal(f"{', '.join(changed)}: under another drift the cut accepts, the drawing fits the layout at "- f"least as well (to within {TIE:g} px) with {one_or_more[0]} named differently, so it does not "- f"say which {one_or_more[1]}; generate the sheet again", "ambiguous", judgment,- (candidates[0], candidates[1]))- cut, key = first, keys[0]- assigned = drawing.assigned(key)- centred = _centred(drawing, key, cut.cost)- if centred is None:- sx, tx, sy, ty = cut.drift- moved = {name: (x * sx + tx, y * sy + ty, w * sx, h * sy) for name, (x, y, w, h) in drawing.layout.items()}- off = _off_centre(assigned, moved)- if off:- holds = ("its box holds a part centred outside it (in the gap beside it or further, so the drawing does "- "not say which element it is)" if len(off) == 1 else- "their boxes hold parts centred outside them (in the gap beside them or further, so the drawing "- "does not say which elements they are)")- raise Refusal(f"{', '.join(off)}: {holds}; generate the sheet again", "off-centre", judgment)- centred = cut.drift- for drift in ((1.0, 0.0, 1.0, 0.0), _fit(assigned, dict(drawing.layout)), centred, cut.drift):- if drift is not None:- cost, read = drawing.read(drift)- if read == key and cost <= cut.cost + TIE:- return Reading(drift, cut.boxes, cost)- return cut---def _sheet_parts(image: Image.Image, alpha_floor: int, alpha_edge: int) -> tuple[Any, Any, list[dict[str, Any]], int]:- """The sheet's pixels after the alpha cleanup, the cleanup's report, the parts of MIN_PART px or more, and how many- smaller parts were dropped."""- rgba = image.convert("RGBA")- sheet_layout(rgba.size)- cleanup = None- if alpha_floor:- rgba, cleanup = clear_haze(rgba, floor=alpha_floor, edge=alpha_edge)- pixels = np.asarray(rgba)- every = _parts(pixels[..., 3] > 0)- kept = [part for part in every if part["pixels"] >= MIN_PART]- return pixels, cleanup, kept, len(every) - len(kept)---def _read(image: Image.Image, *, alpha_floor: int = 64, alpha_edge: int = 2) -> Judgment:- """The judgment `split_ui_kit` decides the sheet by: its least costs and the readings it is decided among."""- _, _, kept, _ = _sheet_parts(image, alpha_floor, alpha_edge)- return _judge(kept, image.size)---def split_ui_kit(image: Image.Image, *, alpha_floor: int = 64,- alpha_edge: int = 2) -> tuple[dict[str, Image.Image], dict[str, Any]]:- """Cut ``image`` along the layout: element images by name, and the report as written to its default- place, ``<out-dir>/ui-kit.json`` (each ``file`` is ``<element>.png``), without the sheet path. A `Refusal`- for a sheet the cut refuses."""- width, height = image.size- _, slots = sheet_layout((width, height))- pixels, cleanup, kept, dropped = _sheet_parts(image, alpha_floor, alpha_edge)- cut = _decide(_judge(kept, (width, height)))- sx, tx, sy, ty = cut.drift- scaled = {name: (x * sx + tx, y * sy + ty, w * sx, h * sy) for name, (x, y, w, h) in boxes((width, height)).items()}- assigned: dict[str, list[dict[str, Any]]] = {name: [] for name in scaled}- loose = []- for part, name in zip(kept, cut.boxes):- (assigned[name] if name is not None else loose).append(part)- unassigned, reasons = [], []- for part in loose:- x0, y0, x1, y1 = part["bbox"]- unassigned.append({"rect": _rect(x0, y0, x1 - x0, y1 - y0), "pixels": part["pixels"]})- reasons.append(f"a part of {part['pixels']} pixels at ({x0}, {y0}) lies in no box")- missing = [slot.name for slot in slots if not assigned[slot.name]]- elements: dict[str, Image.Image] = {}- records: dict[str, Any] = {}- for slot in slots:- parts = assigned[slot.name]- if not parts:- continue- x0, y0, x1, y1 = _bbox(parts)- cut_pixels = np.zeros((y1 - y0, x1 - x0, 4), dtype=np.uint8)- for part in parts:- for y, a, b in part["runs"]:- cut_pixels[y - y0, a - x0:b - x0] = pixels[y, a:b]- element = Image.fromarray(cut_pixels)- insets, inset_notes = measure_insets(element, slot.stretch)- padding, padding_notes = measure_padding(element) if slot.content else (dict.fromkeys(SIDES, 0), [])- round_notes = measure_round(element) if slot.round else []- reasons += [f"{slot.name}: {note}" for note in inset_notes + padding_notes + round_notes]- elements[slot.name] = element- records[slot.name] = {- "file": _element_png(slot.name),- "box": _rect(*(round(value) for value in scaled[slot.name])),- "rect": _rect(x0, y0, x1 - x0, y1 - y0),- "size": {"w": x1 - x0, "h": y1 - y0},- "stretch": slot.stretch,- "insets": insets,- "padding": padding,- "parts": len(parts),- }- for slot in slots:- if slot.inside is not None and slot.name in records:- records[slot.name]["inside"], note = fit_inside(records[slot.name], records[slot.inside], slot.inside)- reasons += [f"{slot.name}: {note}"] if note else []- report: dict[str, Any] = {- "kind": REPORT_KIND,- "version": 1,- "sheet_size": [width, height],- "status": "needs-review" if reasons else "pass",- "review_reasons": reasons,- "alpha_cleanup": cleanup,- "dropped_parts": dropped,- "unassigned": unassigned,- }- # a layout with optional elements always says which are missing; a square sheet's elements are all required- if any(slot.optional for slot in slots):- report["missing"] = missing- if cut.drift != (1.0, 0.0, 1.0, 0.0):- # `+ 0.0`: an offset that rounds to zero is written 0.0, never -0.0- report["layout_fit"] = {"scale": {"x": round(sx, 4), "y": round(sy, 4)},- "offset": {"x": round(tx, 1) + 0.0, "y": round(ty, 1) + 0.0}}- report["elements"] = records- return elements, report---def content_rect(record: dict[str, Any]) -> dict[str, int]:- """The content rectangle of an element record (its size less its padding), from its top-left corner."""- pad, size = record["padding"], record["size"]- return _rect(pad["left"], pad["top"], size["w"] - pad["left"] - pad["right"],- size["h"] - pad["top"] - pad["bottom"])---def fit_inside(fill: dict[str, Any], frame: dict[str, Any], name: str) -> tuple[dict[str, Any], str | None]:- """A fill's ``inside``: the frame it fills, that frame's content rectangle and the factor that makes the- fill exactly as tall as it (docs/ui-kit.md "Fills"), and a review note when its fixed ends would not fit."""- rect = content_rect(frame)- scale = rect["h"] / fill["size"]["h"]- note = None- if (fill["insets"]["left"] + fill["insets"]["right"]) * scale >= rect["w"]:- note = (f"scaled to the height of {name}'s content area, its fixed ends are wider than that area; "- "a full bar would overflow it")- return {"element": name, "rect": rect, "scale": round(scale, 6)}, note---def report_file(report: Path, png: Path) -> str:- """The ``file`` a report at ``report`` gives ``png``: its path from the report's directory, ``/``-separated."""- return Path(os.path.relpath(png, Path(report).parent)).as_posix()---def element_path(report: Path, file: str) -> Path:- """The element PNG that the ``file`` of a report at ``report`` names."""- return Path(report).parent / file---def _taken(out_dir: Path) -> str | None:- """What keeps a kit out of ``out_dir``, said of it, or None when it is absent or an empty directory."""- if not os.path.lexists(out_dir):- return None- if not out_dir.is_dir():- return "is a file"- with os.scandir(out_dir) as entries:- held = sorted(entry.name for entry in entries)- if not held:- return None- return f"holds {held[0]}" + (f" and {len(held) - 1} more" if len(held) > 1 else "")---def _make_new(path: Path, make: Callable[[Path], object], remove: Callable[[Path], object],- made: list[tuple[Callable[[Path], object], Path]]) -> None:- """``make(path)`` for a path that must be new. ``(remove, path)`` goes on ``made`` just before the call, so that a- run interrupted right after it still removes what it made, and comes back off when the path existed: what another- process made is not this run's to remove."""- made.append((remove, path))- try:- make(path)- except FileExistsError:- made.pop()- raise---def _make_dirs(directory: Path, made: list[tuple[Callable[[Path], object], Path]]) -> None:- """Create ``directory`` and its missing parents, putting each one this run creates on ``made`` (`_make_new`)."""- missing = []- while not os.path.lexists(directory):- missing.append(directory)- directory = directory.parent- for path in reversed(missing):- try:- _make_new(path, os.mkdir, os.rmdir, made) # removed only while empty: never what another process put there- except FileExistsError:- continue # another process made it---def _write_new(path: Path, data: bytes) -> None:- fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0), 0o666)- with os.fdopen(fd, "wb") as handle:- handle.write(data)- handle.flush()- os.fsync(handle.fileno())---def _linked(report: Path, temp: Path) -> bool:- """Whether ``report`` is this run's ``temp`` file under its own name. When that cannot be read and the report- exists, it may be."""- try:- return os.path.samestat(os.lstat(report), os.lstat(temp))- except OSError:- return os.path.lexists(report)---def _rename_in(staging: Path, out_dir: Path, given_empty: bool) -> None:- """Give ``staging`` the name ``out_dir``, removing an empty ``out_dir`` first where a rename cannot take its name.- A ValueError when another run's kit took the name first. Its try statement is kept out of `_write_kit`'s, which- holds none (see there)."""- try:- if given_empty and not RENAME_ONTO_EMPTY_DIR:- os.rmdir(out_dir)- os.rename(staging, out_dir)- except OSError as exc:- taken = os.path.lexists(staging) and _taken(out_dir) # only when the rename did not happen- if taken:- raise ValueError(f"--out-dir {out_dir} was filled while this kit was cut: it {taken}; "- "nothing was written") from exc- raise---def _link_report(temp: Path, report: Path) -> None:- """Give the finished ``temp`` its own name, ``report``; a ValueError when another run's report took it first.- Its try statement is kept out of `_write_kit`'s, as `_rename_in`'s is."""- try:- os.link(temp, report)- except FileExistsError as exc:- raise ValueError(f"--report {report} appeared while this kit was cut; nothing was written") from exc---def _write_kit(out_dir: Path, files: dict[str, bytes], report: Path | None, report_data: bytes) -> None:- """Publish a kit whole into ``out_dir``, absent or empty. ``files`` (paths inside it) are written into a hidden- staging directory beside it, which then takes its name with one rename. A ``report`` outside it is written to a- hidden temp file beside it and linked to its own name after the rename; the link fails when that name exists, so- no run replaces another's report.-- One step publishes the kit: the rename, or with a report outside, the link. Before it, a run that fails or is- interrupted removes everything it made (the kit it renamed in, the directories it created, its staging directory- and temp file) and puts back an empty out-dir it was given; from it on, it removes nothing but its temp file.-- Python can raise an interrupt at any instruction: a signal's handler, or a tracer's, runs between any two. So the- one ``except`` below covers every instruction from the first name the run creates to the end of the publish, and- no try statement is nested in its own: a nested ``try:`` line compiles to an instruction that no handler covers,- so an exception raised there would leave without the clean-up. The rename's and the link's own try statements are- in `_rename_in` and `_link_report`, whose exceptions reach this handler at their call. No step is recorded after- its call: ``renaming`` and ``linking`` are set before theirs and the filesystem says whether it happened, and- each name the run creates goes on ``made`` before the call that creates it.-- A killed run, or one interrupted again while it removes what it made, leaves no part of a kit under the out-dir's- name: at most its hidden staging directory or temp file beside them and the directories it created, or, stopped- between the rename and the link, the whole kit without its report."""- given_empty = out_dir.is_dir()- tag = secrets.token_hex(6)- staging = out_dir.parent / f".{out_dir.name}.ui-kit-{tag}"- temp = None if report is None else report.parent / f".{report.name}.{tag}.tmp"- made: list[tuple[Callable[[Path], object], Path]] = []- renaming = linking = False- try:- _make_dirs(out_dir.parent, made)- _make_new(staging, os.mkdir, lambda path: shutil.rmtree(path, ignore_errors=True), made)- for name, data in files.items():- target = staging / name- if target.parent != staging: # a report in a directory of its own inside the out-dir- target.parent.mkdir(parents=True, exist_ok=True)- _write_new(target, data)- if temp is not None:- _make_dirs(temp.parent, made)- _make_new(temp, lambda path: _write_new(path, report_data), os.unlink, made)- renaming = True- _rename_in(staging, out_dir, given_empty)- if temp is not None:- linking = True- _link_report(temp, report)- with contextlib.suppress(OSError):- os.unlink(temp) # published: the temp is a second name of the report- except BaseException:- renamed = renaming and not os.path.lexists(staging) # the staging directory took the out-dir's name- published = renamed if temp is None else linking and _linked(report, temp)- if published:- if temp is not None:- with contextlib.suppress(OSError):- os.unlink(temp)- raise- if renamed:- with contextlib.suppress(OSError):- os.rename(out_dir, staging)- if given_empty and not os.path.lexists(out_dir):- with contextlib.suppress(OSError):- os.mkdir(out_dir)- for remove, path in reversed(made):- with contextlib.suppress(OSError):- remove(path)- raise---def _publish(*, sheet: Path, out_dir: Path, alpha_floor: int = 64, alpha_edge: int = 2,- report: Path | None = None) -> int:- sheet = Path(sheet).expanduser().resolve()- out_dir = Path(out_dir).expanduser().resolve()- report_path = Path(report).expanduser().resolve() if report is not None else out_dir / "ui-kit.json"- if not sheet.is_file():- raise ValueError(f"sheet is not a file: {sheet}")- if inside_folder(sheet, out_dir) or same_folder(report_path, sheet):- raise ValueError("the output directory must not hold the sheet; choose a new directory")- if report_path.suffix.lower() != ".json":- raise ValueError("--report must be a .json path")- taken = _taken(out_dir)- if taken:- raise ValueError(f"--out-dir {out_dir} {taken}; a kit is written whole into a new or empty directory")- inside = report_path.is_relative_to(out_dir)- if not inside and os.path.lexists(report_path):- raise ValueError(f"--report {report_path} already exists; a report outside --out-dir is written to a new path")- with Image.open(sheet) as image:- if image.format != "PNG" or getattr(image, "n_frames", 1) != 1:- raise ValueError("--sheet must be a single-frame PNG")- elements, measured = split_ui_kit(image, alpha_floor=alpha_floor, alpha_edge=alpha_edge)- written = {"kind": measured["kind"], "version": measured["version"], "sheet": str(sheet)}- written.update((key, value) for key, value in measured.items() if key not in written)- # wherever --report puts the report, each `file` leads from it to the PNG written in out_dir- written["elements"] = {name: {**record, "file": report_file(report_path, out_dir / record["file"])}- for name, record in measured["elements"].items()}- files: dict[str, bytes] = {}- for name, element in elements.items():- png = io.BytesIO()- element.save(png, format="PNG")- files[measured["elements"][name]["file"]] = png.getvalue()- report_data = (json.dumps(written, indent=2, allow_nan=False) + "\n").encode("utf-8")- if inside:- files[report_path.relative_to(out_dir).as_posix()] = report_data- _write_kit(out_dir, files, None if inside else report_path, report_data)- missing = written.get("missing") or []- left_out = f"; missing, left out of the kit: {', '.join(missing)}" if missing else ""- print(f"ui-kit: {written['status']} — {len(elements)} elements in {out_dir} (report: {report_path}){left_out}")- return 0---def add_arguments(parser: argparse.ArgumentParser) -> None:- parser.add_argument("--sheet", required=True, type=Path,- help="transparent square or 2:3 PNG drawn with `gen --layout-guide ui-kit`")- parser.add_argument("--out-dir", required=True, type=Path,- help="a new or empty directory for <element>.png and ui-kit.json; "- "one that holds anything is refused")- parser.add_argument("--alpha-floor", type=int, default=64,- help="alpha haze cleanup floor, 1..255 (0 turns the cleanup off)")- parser.add_argument("--alpha-edge", type=int, default=2,- help="faint pixels this close to a solid pixel are its edge and are kept")- parser.add_argument("--report", type=Path,- help="JSON report (default: <out-dir>/ui-kit.json), a new path when outside --out-dir; "- "its element paths are relative to it")---def run(**kwargs: Any) -> int:- try:- return _publish(**kwargs)- except (OSError, ValueError, TypeError) as exc:- raise SystemExit(f"ui-kit: {exc}") from exc---def main(argv: list[str] | None = None) -> int:- utf8_streams()- parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])- add_arguments(parser)- return run(**vars(parser.parse_args(argv)))---if __name__ == "__main__":- raise SystemExit(main())diff --git a/sprite_gen/gen/__init__.py b/sprite_gen/gen/__init__.pyindex 7de9127..e7b314c 100644--- a/sprite_gen/gen/__init__.py+++ b/sprite_gen/gen/__init__.py@@ -31,7 +31,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] [--layout-guide [figure|ui-kit]]+ [--resolution 1k|1.5k|2k] [--layout-guide [figure]][--report REPORT.json] [--keep-session]"""@@ -122,10 +122,8 @@ CODEX_UNAVAILABLE_DEFAULT = CODEX_UNAVAILABLE_ASK# in-place motion to bob into; a box alone is read loosely, the lines set the scale.LAYOUT_GUIDE_LONG_EDGE = 1024LAYOUT_GUIDE_NAME = "layout-guide.png"-# `--layout-guide ui-kit` attaches the UI kit layout instead (`sprite_gen.frames.ui_kit`, docs/ui-kit.md):-# one box per element, the boxes `ui-kit` later cuts along; square for the frames, 2:3 for the whole kit.-# The bare flag is the figure guide.-LAYOUT_GUIDE_KINDS = ("figure", "ui-kit")+# The bare flag is the figure guide, the one kind there is.+LAYOUT_GUIDE_KINDS = ("figure",)CROWN_LINE = "#ff7a00"CROWN_MARK = "#ffb15c"FLOOR_LINE = "#00a7a7"@@ -218,19 +216,6 @@ def layout_guide_kind(value: bool | str | None) -> str | None:return str(value)-def ui_kit_guide_size(aspect_ratio: str | None) -> tuple[int, int]:- """The UI kit guide is square (the frames) or 2:3 (the whole kit): the sheet shapes `ui-kit` cuts along."""- from sprite_gen.frames import ui_kit-- width, height = layout_guide_size(aspect_ratio)- try:- ui_kit.sheet_layout((width, height))- except ValueError:- raise SystemExit("gen: the ui-kit layout guide is square (1:1, the frames) or 2:3 (the whole kit); "- f"use --aspect-ratio 1:1 or 2:3 (got {aspect_ratio})") from None- return width, height--def _make_provider(name: str, *, keep_session: bool):if name == PROVIDER_CODEX:return CodexProvider(keep_session=keep_session)@@ -460,10 +445,8 @@ def generate_image() -> GenResult:"""Generate one image and return a GenResult. Raises SystemExit on any failure.- `layout_guide`: "figure" (or True) attaches the one-slot figure guide, "ui-kit" the UI kit layout."""+ `layout_guide`: "figure" (or True) attaches the one-slot figure guide."""guide_kind = layout_guide_kind(layout_guide)- if guide_kind == "ui-kit":- ui_kit_guide_size(aspect_ratio)if decontam not in extract_mod.DECONTAM_MODES:raise SystemExit(f"gen: unknown --decontam {decontam!r}; expected off|auto|palette")if decontam == extract_mod.PALETTE and not transparent:@@ -498,8 +481,7 @@ def generate_image(# takes the outline and light fills with it (2026-10-04). A key the prompt already names stays.parts = still_prompt(prompt, view=view, facing=facing, handed=handed, body_plan=body_plan, refs=bool(refs),key=chroma_key if strategy_source == STRATEGY_SOURCE_REFS else None,- layout=layout_guide_cell(aspect_ratio) if guide_kind == "figure" else None,- ui_kit_guide=ui_kit_guide_size(aspect_ratio) if guide_kind == "ui-kit" else None)+ layout=layout_guide_cell(aspect_ratio) if guide_kind == "figure" else None)prompt = parts.textfor line in prompt_parts.note_lines(parts):print(f"[gen] {line}", file=sys.stderr)@@ -525,12 +507,7 @@ def generate_image(attached = list(refs)if guide_kind:guide = workdir / LAYOUT_GUIDE_NAME- if guide_kind == "ui-kit":- from sprite_gen.frames import ui_kit-- guide_cell = ui_kit.draw_guide(guide, ui_kit_guide_size(aspect_ratio))- else:- guide_cell = draw_layout_guide(guide, aspect_ratio)+ guide_cell = draw_layout_guide(guide, aspect_ratio)# Last, so "the last attached image" in the prompt is the guide whatever the caller attached.attached.append(guide)request = GenRequest(@@ -676,8 +653,7 @@ def _check_view(view: str | None, facing: str | None, facing_fix: str, handed: ldef still_prompt(prompt: str, *, view: str | None = None, facing: str | None = None,handed: list[handed_mod.Handed] | None = None, body_plan: list[Body] | None = None,refs: bool = False, key: str | None = None,- layout: dict[str, Any] | None = None,- ui_kit_guide: tuple[int, int] | None = None) -> prompt_parts.Prompt:+ layout: dict[str, Any] | None = None) -> prompt_parts.Prompt:"""The prompt a still is drawn from: the caller's text, then the engine's pieces (`prompt_parts.Prompt.add`;without `handed` or `body_plan`, 2.22.0's prompt to the byte). In order:@@ -688,8 +664,7 @@ def still_prompt(prompt: str, *, view: str | None = None, facing: str | None = N- with `refs` and a `facing`: the turn over the reference (`facing.prompt_suffix`);- `key` (green / magenta, a ref run `auto` planned to key): the key background line, unless the promptnames a key background already;- - `layout` (the `--layout-guide` cell): where the guide's lines are; `ui_kit_guide`- (`--layout-guide ui-kit`, the guide's size): what to draw in each box of the UI kit layout.+ - `layout` (the `--layout-guide` cell): where the guide's lines are."""figures = body_mod.figures(body_plan)parts = prompt_parts.Prompt(prompt, caller=f"{prompt} {figures}" if figures else None)@@ -707,10 +682,6 @@ def still_prompt(prompt: str, *, view: str | None = None, facing: str | None = Nparts.add("key-background", chroma_mod.KEY_BACKGROUND_TEXT[key], key=key)if layout is not None:parts.add("layout", layout_guide_text(layout))- if ui_kit_guide is not None:- from sprite_gen.frames import ui_kit-- parts.add("layout", ui_kit.guide_text(ui_kit_guide))return parts@@ -854,9 +825,7 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:"attach a layout guide after any --ref. Bare or `figure`: a one-slot guide (frame, inner safe ""area at the row guide's 9.4 %% margin, center line) asking for the whole subject inside the ""safe area, with room above the head and below the feet; drawn for --aspect-ratio, square "- "without one. `ui-kit`: the UI kit layout, one box per element, for `sprite-gen ui-kit`: square "- "(--aspect-ratio 1:1 or none) for the frames, 2:3 for the whole kit with bar fills, slot, badge, "- "pips and joystick"+ "without one"),)parser.add_argument("--white-check", type=Path, help="write a white-composite check image")diff --git a/sprite_gen/gen/address.py b/sprite_gen/gen/address.pyindex 7ba8149..7ed3431 100644--- a/sprite_gen/gen/address.py+++ b/sprite_gen/gen/address.py@@ -1,7 +1,7 @@# SPDX-License-Identifier: Apache-2.0"""Where each provider sprite-gen calls is: its address, read from the environment at every call.-sprite-gen calls four providers over HTTP itself, with no SDK: OpenAI, xAI, Anthropic and ElevenLabs. Each has one+sprite-gen calls three providers over HTTP itself, with no SDK: OpenAI, xAI and Anthropic. Each has onebase address, the documented API root with its version path, and one environment variable that replaces it,`SPRITE_GEN_<PROVIDER>_BASE_URL`. Unset, empty or blank is the documented address, so nothing changes for anyone whosets none. The variable is read when a request is made, never at import, so a process that sets it after importing@@ -15,9 +15,9 @@ that forwards the provider's API forwards it too. Without the variable it is fetEvery direct provider call builds its URL here (docs/gen.md "Provider addresses" lists them):`openai_provider` (images, vision), `xai` callers `grok_provider` (images), `facing_vision.grok_inspect` (vision)-and `video` (generations, extensions, edits, polls, the clip's download), `anthropic_api` (messages, batches, the-results file) and `sprite_gen.audio.provider` (sound). The subscription logins (`codex`, `claude`) are the binaries'-own network and do not read these variables; `SPRITE_GEN_LOGINS=off` turns them off (`base.logins_on`).+and `video` (generations, extensions, edits, polls, the clip's download), and `anthropic_api` (messages, batches, the+results file). The subscription logins (`codex`, `claude`) are the binaries' own network and do not read these+variables; `SPRITE_GEN_LOGINS=off` turns them off (`base.logins_on`)."""from __future__ import annotations@@ -34,16 +34,15 @@ class Provider:default: str # the documented API root, version path included-# The four providers' names, each written once: the keys every caller and every table of them (`retry`,+# The three providers' names, each written once: the keys every caller and every table of them (`retry`,# `workflow.capabilities`) names a provider by. A host, not an image provider: `OPENAI` is the API sprite-gen calls,# `base.PROVIDER_OPENAI` the image provider that calls it, two names that happen to be spelled alike.-OPENAI, XAI, ANTHROPIC, ELEVENLABS = "openai", "xai", "anthropic", "elevenlabs"+OPENAI, XAI, ANTHROPIC = "openai", "xai", "anthropic"PROVIDERS = {provider.name: provider for provider in (Provider(OPENAI, "SPRITE_GEN_OPENAI_BASE_URL", "https://api.openai.com/v1"),Provider(XAI, "SPRITE_GEN_XAI_BASE_URL", "https://api.x.ai/v1"),Provider(ANTHROPIC, "SPRITE_GEN_ANTHROPIC_BASE_URL", "https://api.anthropic.com/v1"),- Provider(ELEVENLABS, "SPRITE_GEN_ELEVENLABS_BASE_URL", "https://api.elevenlabs.io/v1"),)}FETCH_PATH = "/sprite-gen/fetch"diff --git a/sprite_gen/gen/retry.py b/sprite_gen/gen/retry.pyindex 6504544..3a550c4 100644--- a/sprite_gen/gen/retry.py+++ b/sprite_gen/gen/retry.py@@ -68,18 +68,13 @@ UNTAKEN: dict[str, frozenset[int]] = {address.ANTHROPIC: frozenset({429, 500, 529}),address.OPENAI: frozenset({429, 503}),address.XAI: frozenset({429}),- address.ELEVENLABS: frozenset({429}),}ACT_FIRST: dict[str, frozenset[str]] = {address.ANTHROPIC: frozenset({"enforced_spend_limit_reached"}),address.OPENAI: frozenset({"credit_balance_exhausted", "organization_spend_limit_exceeded","project_spend_limit_exceeded", "organization_usage_limit_exceeded", "insufficient_quota"}),address.XAI: frozenset(),- address.ELEVENLABS: frozenset(),}-# ElevenLabs documents only these two 429 codes as requests it could not process.-# https://elevenlabs.io/docs/help-center/technical/api-error-code-429 (2026-10-13).-ELEVENLABS_BUSY = ("system_busy", "too_many_concurrent_requests")GET_AGAIN = frozenset({429, 500, 502, 503, 504, 529})Sleep = Callable[[float], None]@@ -113,10 +108,6 @@ def _act_first(provider: str, body: Any) -> bool:def again_after(provider: str, method: str, status: int, body: Any, headers: Any, failures: int) -> float | None:"""Seconds to wait before sending the request again after its `failures`-th failed answer in a row,or None when it is not sent again (the rule in the module docstring)."""- if provider == address.ELEVENLABS and method != "GET":- detail = body.get("detail") if isinstance(body, dict) else None- if not isinstance(detail, dict) or detail.get("status") not in ELEVENLABS_BUSY:- return Noneif failures > ASKS_AGAIN:return Noneif method == "GET":diff --git a/sprite_gen/spec/assets.py b/sprite_gen/spec/assets.pyindex 981bdd6..b3cadb2 100644--- a/sprite_gen/spec/assets.py+++ b/sprite_gen/spec/assets.py@@ -226,26 +226,6 @@ def load_asset(source: Path, *, state=None, fps=None, anchor=None) -> FrameSequereturn _load_asset(source, _Snapshot(), state=state, fps=fps, anchor=anchor)-def load_asset_states(source: Path, *, state=None, fps=None, anchor=None) -> dict[str | None, FrameSequence]:- """Read every declared state from one snapshot; never discover frames by filename sort."""- source = Path(source).expanduser().resolve()- snapshot = _Snapshot()- states = [state]- if state is None and source.suffix.lower() == ".json":- data = snapshot.json(source)- if not isinstance(data, dict):- raise ValueError("asset descriptor must be an object")- if "frame_layout" in data:- states = list(data["frame_layout"]["rows"])- elif data.get("kind") == SET_SHEET_KIND:- states = [row["code"] for row in data["rows"]]- elif isinstance(data.get("rows"), list) and "cell" in data:- states = data["rows"]- if not states or len(set(states)) != len(states):- raise ValueError("asset states must be nonempty and unique")- return {key: _load_asset(source, snapshot, state=key, fps=fps, anchor=anchor) for key in states}--PLAYBACK_FIELDS = ("loop", "hold_last", "end_frame", "events", "blend", "direction", "body_h", "frame_variant")diff --git a/sprite_gen/workflow/capabilities.py b/sprite_gen/workflow/capabilities.pyindex bbd360d..d56d704 100644--- a/sprite_gen/workflow/capabilities.py+++ b/sprite_gen/workflow/capabilities.py@@ -15,7 +15,6 @@ from importlib.metadata import PackageNotFoundError, version as package_versionfrom pathlib import PurePathfrom typing import Any-from sprite_gen.audio import provider as sound_providerfrom sprite_gen.gen import address, anthropic_api, openai_provider, xaifrom sprite_gen.gen.base import LOGINS_ENVfrom sprite_gen.util.console import utf8_streams@@ -31,7 +30,6 @@ PROVIDER_CALLS: dict[str, tuple[str, ...]] = {"gen-set": (address.OPENAI, address.XAI),"logo": (address.OPENAI, address.XAI),"pixel-draw": (address.ANTHROPIC,),- "sound": (address.ELEVENLABS,),"curation": (address.XAI,),"video": (address.XAI,),"video-extend": (address.XAI,),@@ -42,7 +40,7 @@ PROVIDER_CALLS: dict[str, tuple[str, ...]] = {# Verbs that call a provider and buy nothing: `video-resume` polls and downloads a clip an earlier run bought.NO_PURCHASE = frozenset({"video-resume"})KEY_ENVS = {address.OPENAI: openai_provider.AUTH_ENV, address.XAI: xai.AUTH_ENV,- address.ANTHROPIC: anthropic_api.AUTH_ENV, address.ELEVENLABS: sound_provider.AUTH_ENV}+ address.ANTHROPIC: anthropic_api.AUTH_ENV}# Argument types by name; any other is its parsing function's name without `_` and `parse_` (`_parse_grid`: grid).TYPES = {str: None, int: "int", float: "float"}diff --git a/tests/audio/prepare_playback_fixture.py b/tests/audio/prepare_playback_fixture.pydeleted file mode 100644index 1065e3e..0000000--- a/tests/audio/prepare_playback_fixture.py+++ /dev/null@@ -1,33 +0,0 @@-# SPDX-License-Identifier: Apache-2.0-"""Create one synthetic encoded bundle for render_playback.mjs; no provider calls."""-import json-from pathlib import Path-import sys-import wave--import numpy as np--from sprite_gen.audio import playback, processing---def prepare(directory):- directory = Path(directory)- directory.mkdir(parents=True)- source = directory/'source.wav'- frames = 144003 # fractional destination frame at 44.1 kHz- t = np.arange(frames)/48000- samples = np.stack([.1*np.sin(2*np.pi*317*t+.5), .3*np.cos(2*np.pi*73*t)], axis=1)- with wave.open(str(source), 'wb') as stream:- stream.setnchannels(2)- stream.setsampwidth(2)- stream.setframerate(48000)- stream.writeframes((samples*32767).astype('<i2').tobytes())- details = processing.export(source, directory, target_lufs=-20, loop=True, crossfade=.25)- manifest = {'kind':'sprite-gen-sound', 'version':playback.VERSION, 'audio_kind':'bgm',- 'event':'synthetic.loop', 'loop':True, 'target_lufs':-20, **details}- (directory/'sound.json').write_text(json.dumps(manifest, indent=2)+'\n')- return manifest---if __name__ == '__main__':- prepare(sys.argv[1])diff --git a/tests/audio/render_playback.mjs b/tests/audio/render_playback.mjsdeleted file mode 100644index beaa79b..0000000--- a/tests/audio/render_playback.mjs+++ /dev/null@@ -1,279 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// node tests/audio/render_playback.mjs <cases.json> <output-dir> [chromium,webkit]-// PLAYWRIGHT_MODULE may name an installed Playwright entry point.-// PLAYWRIGHT_CHROMIUM_EXECUTABLE explicitly selects an installed Chromium browser.-import assert from 'node:assert/strict';-import { readFile, mkdir, writeFile } from 'node:fs/promises';-import { createHash } from 'node:crypto';-import { dirname, resolve } from 'node:path';-const { chromium, webkit } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright');-const [caseFile, outputDir, engineList = 'chromium,webkit'] = process.argv.slice(2);-const engines = engineList.split(',');-assert.ok(engines.length && new Set(engines).size===engines.length &&- engines.every(name=>['chromium','webkit'].includes(name)), 'select chromium, webkit, or both');-const cases = JSON.parse(await readFile(caseFile, 'utf8'));-await mkdir(outputDir, { recursive: true });-const modulePath = resolve('sprite_gen/audio/sprite-gen-audio-v2.mjs');-const moduleBytes = await readFile(modulePath);-const digest = createHash('sha256').update(moduleBytes).digest('hex');-const reports = [];-const report = { module_sha256:digest, engines,- chromium_executable:process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE || 'bundled', reports };-for (const name of engines) {- const engine = { chromium, webkit }[name];- const browser = await engine.launch({ headless: true,- ...(name==='chromium' && process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE ?- {executablePath:process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE} : {}) });- try {- const page = await browser.newPage();- await page.goto('about:blank');- for (const rate of [44100, 48000]) {- const synthetic = await page.evaluate(async ({ code, rate }) => {- const { prepareAudioBuffer, createAudioSource } = await import(code);- const check = (ok, message) => { if (!ok) throw new Error(message); };- // Non-zero origin and a frame count whose independent rounding differs.- const meta = { version: 2, sample_rate: 48000, start_frame: 13,- end_frame: 144019, overlap_frames: 12010 };- const first = Math.floor(meta.start_frame * rate / 48000);- const n = Math.floor(meta.end_frame*rate/48000)-first;- const length = Math.round((meta.end_frame-meta.start_frame-meta.overlap_frames)*rate/48000);- const count = n-length;- if (rate===44100) check(n-Math.round(meta.overlap_frames*rate/48000)!==length, 'rounding counterexample missing');- const input = new AudioBuffer({ sampleRate: rate, length: first+n, numberOfChannels: 2 });- for (let c=0;c<2;c++) {- const x=input.getChannelData(c);- for (let i=0;i<x.length;i++) x[i]=.2*Math.cos(2*Math.PI*(c ? 73 : 1000)*i/rate)+.1*i/x.length;- }- // Exercise both integer and fractional resampled lengths through the- // real decoder and the public source factory, for one-shots and loops.- const resampling=[];- for (const waveFrames of [48000, 144003]) {- const wave=new ArrayBuffer(44+waveFrames*2), view=new DataView(wave);- const ascii=(offset,text)=>{for(let i=0;i<text.length;i++) view.setUint8(offset+i,text.charCodeAt(i));};- ascii(0,'RIFF'); view.setUint32(4,36+waveFrames*2,true); ascii(8,'WAVE');- ascii(12,'fmt '); view.setUint32(16,16,true); view.setUint16(20,1,true);- view.setUint16(22,1,true); view.setUint32(24,48000,true); view.setUint32(28,96000,true);- view.setUint16(32,2,true); view.setUint16(34,16,true); ascii(36,'data');- view.setUint32(40,waveFrames*2,true);- for(let i=0;i<waveFrames;i++) view.setInt16(44+2*i,Math.round(5000*Math.sin(2*Math.PI*317*i/48000)),true);- const waveDecoded=await new OfflineAudioContext(1,1,rate).decodeAudioData(wave);- const waveMeta={version:2,sample_rate:48000,start_frame:0,end_frame:waveFrames,overlap_frames:12000};- const completeFrames=Math.floor(waveFrames*rate/48000);- for (const loop of [false, true]) {- const coordinates={...waveMeta,overlap_frames:loop ? 12000 : 0};- // The decoder exercises its own rounding. Constructed buffers also- // enforce the one-frame tolerance and reject two missing frames.- for (const delta of [null, -1, 0, 7, -2]) {- const raw=delta===null ? waveDecoded : new AudioBuffer({sampleRate:rate,- length:completeFrames+delta,numberOfChannels:1});- if (delta!==null) raw.copyToChannel(waveDecoded.getChannelData(0).subarray(0,raw.length),0);- const expected=loop ? Math.round((waveFrames-12000)*rate/48000) : Math.min(completeFrames,raw.length);- const context=new OfflineAudioContext(1,expected*2,rate);- if (delta===-2) {- let error;- try { createAudioSource(context,raw,{loop,playback:coordinates}); } catch (caught) { error=caught; }- check(error instanceof RangeError && /playback interval/.test(error.message),'two missing frames must be an interval error');- continue;- }- const prepared=prepareAudioBuffer(raw,coordinates);- const node=createAudioSource(context,raw,{loop,playback:coordinates});- check(prepared.length===expected,'resampled playback duration changed');- check(node.loop===loop && node.loopEnd===expected/rate,'source interval is wrong');- if (!loop) check(prepared.getChannelData(0).every((v,i)=>v===raw.getChannelData(0)[i]),'one-shot samples changed');- node.connect(context.destination); node.start();- const rendered=(await context.startRendering()).getChannelData(0), samples=prepared.getChannelData(0);- let renderError=0;- for(let i=0;i<rendered.length;i++) renderError=Math.max(renderError,Math.abs(rendered[i]-(loop ? samples[i%expected] : (i<expected ? samples[i] : 0))));- check(renderError<1e-7,'resampled source rendering changed');- if (loop) {- const overlap=Math.min(completeFrames,raw.length)-expected, x=raw.getChannelData(0);- check((rendered[expected]-rendered[expected-1])-(x[overlap]-x[overlap-1])===0,'resampled wrap error');- const join=expected-overlap;- check((samples[join]-samples[join-1])-(x[expected]-x[expected-1])===0,'resampled join error');- }- resampling.push({source_frames:waveFrames,complete_frames:completeFrames,- decoded_frames:raw.length,delta,loop,length:prepared.length,render_error:renderError});- }- }- }- for (const overlap of [0, 1]) {- const coordinates=overlap ? {version:2,sample_rate:rate,start_frame:0,end_frame:12,overlap_frames:2}- : {version:2,sample_rate:rate*2,start_frame:0,end_frame:24,overlap_frames:2};- const raw=new AudioBuffer({sampleRate:rate,length:11,numberOfChannels:1});- let error;- try { createAudioSource(new OfflineAudioContext(1,12,rate),raw,{loop:true,playback:coordinates}); }- catch (caught) { error=caught; }- check(error instanceof RangeError && /overlap too short after decoder one-frame shortfall/.test(error.message),- `mapped overlap ${overlap} must be an explicit shortfall error`);- }- const minimumRateInput=new AudioBuffer({sampleRate:8000,length:7999,numberOfChannels:1});- for(let i=0;i<minimumRateInput.length;i++) minimumRateInput.getChannelData(0)[i]=.1*Math.sin(i/5);- const minimumRateMeta={version:2,sample_rate:48000,start_frame:0,end_frame:48005,overlap_frames:21};- const minimumRateBuffer=prepareAudioBuffer(minimumRateInput,minimumRateMeta);- check(minimumRateBuffer.length===7997,'minimum supported rate lost the declared loop length');- check(minimumRateBuffer.getChannelData(0).every(Number.isFinite),'minimum overlap generated nonfinite samples');- const before = input.getChannelData(0).slice();- const out = prepareAudioBuffer(input, meta);- check(out.length === length, 'one-frame rounding drift');- check(prepareAudioBuffer(input, meta) === out, 'decoded input was prepared twice');- check(prepareAudioBuffer(out, meta) === out, 'prepared output was crossfaded twice');- check(input.getChannelData(0).every((v,i)=>v===before[i]), 'decoded source mutated');- for (let c=0;c<2;c++) {- const x=input.getChannelData(c), y=out.getChannelData(c);- const expected=x[first+count]-x[first+count-1];- check((y[0]-y.at(-1))-expected === 0, 'added wrap error');- const middle=n-2*count;- check((y[middle]-y[middle-1])-(x[first+n-count]-x[first+n-count-1])===0, 'added join error');- // The detector must reject an artificial discontinuity, even though- // a high-frequency signal's normal adjacent difference is allowed.- const control=y.slice(); control[0]+=.125;- check(Math.abs((control[0]-control.at(-1))-expected)>.12, 'broken negative control');- }- let rejected=false;- try { prepareAudioBuffer(out, { ...meta, overlap_frames: 12011 }); } catch { rejected=true; }- check(rejected, 'changed metadata reused prepared audio');- const ctx=new OfflineAudioContext(2, length*3, rate);- const source=createAudioSource(ctx,input,{loop:true,playback:meta});- check(source.buffer.length===out.length+1 && source.loop && source.loopStart===0 && source.loopEnd===out.duration, 'source bypasses preparation');- check(createAudioSource(ctx,out,{loop:true,playback:meta}).buffer===source.buffer, 'guarded playback buffer was rebuilt');- for(let c=0;c<2;c++) {- const data=source.buffer.getChannelData(c);- check(data[length]===out.getChannelData(c)[0], 'missing cyclic interpolation sample');- check(data.subarray(0,length).every((v,i)=>v===out.getChannelData(c)[i]), 'guard changed the prepared samples');- }- source.connect(ctx.destination); source.start();- const rendered=await ctx.startRendering();- let maxError=0;- for(let c=0;c<2;c++) for(let i=0;i<rendered.length;i++) {- maxError=Math.max(maxError,Math.abs(rendered.getChannelData(c)[i]-out.getChannelData(c)[i%length]));- }- check(maxError<1e-7, 'rendered looping differs from prepared buffer');- // Choose synthetic lengths on both sides of the duration round-trip.- const roundTrips=[];- for(const direction of [-1,1]) {- let frames=rate;- while(frames<2*rate && Math.sign((frames/rate)*rate-frames)!==direction) frames++;- check(frames<2*rate, 'duration round-trip counterexample missing');- const raw=new AudioBuffer({sampleRate:rate,length:frames+128,numberOfChannels:1});- const data=raw.getChannelData(0);- for(let i=0;i<data.length;i++) data[i]=.2*Math.cos(2*Math.PI*317*i/rate)+.1;- const coordinates={version:2,sample_rate:rate,start_frame:0,end_frame:raw.length,overlap_frames:128};- const prepared=prepareAudioBuffer(raw,coordinates);- const renderContext=new OfflineAudioContext(1,frames*4,rate);- const node=createAudioSource(renderContext,raw,{loop:true,playback:coordinates});- node.connect(renderContext.destination);node.start();- const samples=(await renderContext.startRendering()).getChannelData(0);- const baseline=data[128]-data[127];- for(let lap=1;lap<4;lap++) {- const at=lap*frames;- check((samples[at]-samples[at-1])-baseline===0, 'duration round-trip changed the rendered seam');- }- let error=0;- for(let i=0;i<samples.length;i++) error=Math.max(error,Math.abs(samples[i]-prepared.getChannelData(0)[i%frames]));- check(error<1e-7, 'duration round-trip changed the loop samples');- roundTrips.push({frames,duration_frames:(frames/rate)*rate,render_error:error});- }- const corrupted = new AudioBuffer({ sampleRate:rate, length, numberOfChannels:2 });- for(let c=0;c<2;c++) {- corrupted.copyToChannel(out.getChannelData(c),c);- corrupted.getChannelData(c)[0]+=.125;- }- const controlContext=new OfflineAudioContext(2,length*3,rate);- const controlSource=controlContext.createBufferSource();- controlSource.buffer=corrupted; controlSource.loop=true;- controlSource.loopStart=0; controlSource.loopEnd=corrupted.duration;- controlSource.connect(controlContext.destination); controlSource.start();- const controlRender=await controlContext.startRendering();- let controlError=0, controls=0;- for(let c=0;c<2;c++) {- const x=input.getChannelData(c), r=controlRender.getChannelData(c);- const baseline=x[first+count]-x[first+count-1];- for(let lap=1;lap<3;lap++) {- const at=lap*length, error=Math.abs((r[at]-r[at-1])-baseline);- controlError=Math.max(controlError,error);- if(error>.12) controls++;- }- }- check(controls===4, 'rendered discontinuity control escaped detection');- return { length, count, duration_round_trips:roundTrips, added_wrap_error:0, added_join_error:0,- controls_detected:controls, control_added_wrap_error:controlError, render_error:maxError,- resampling };- }, { code: `data:text/javascript;base64,${moduleBytes.toString('base64')}`, rate });- reports.push({ browser:name, browser_version:browser.version(), rate, synthetic });- for (const item of cases) {- const manifestPath = resolve(dirname(caseFile), item.manifest);- const pack = JSON.parse(await readFile(manifestPath,'utf8'));- const record = item.id ? pack.audio[item.id] : pack;- const shipped = record.player ? await readFile(resolve(dirname(manifestPath), record.player.path)) : moduleBytes;- assert.equal(createHash('sha256').update(shipped).digest('hex'), digest);- if (record.player) assert.equal(record.player.sha256, digest);- for (const fmt of ['ogg','m4a']) {- const bytes = await readFile(resolve(dirname(manifestPath),record.files[fmt].path));- assert.equal(createHash('sha256').update(bytes).digest('hex'),record.files[fmt].sha256);- const result = await page.evaluate(async ({code,encoded,record,rate}) => {- const { prepareAudioBuffer, createAudioSource } = await import(code);- const data=Uint8Array.from(atob(encoded),c=>c.charCodeAt(0));- const decoder=new OfflineAudioContext(2,1,rate);- const decoded=await decoder.decodeAudioData(data.buffer);- const buffer=prepareAudioBuffer(decoded,record.playback);- const m=record.playback, map=f=>f*decoded.sampleRate/m.sample_rate;- const first=Math.floor(map(m.start_frame)), last=Math.floor(map(m.end_frame));- if (decoded.length<last-1) throw new Error('decoded interval is more than one frame short');- const n=Math.min(last,decoded.length)-first;- const length=m.overlap_frames ? Math.round(map(m.end_frame-m.start_frame-m.overlap_frames)) : n, count=n-length;- if (buffer.length!==length) throw new Error('wrong prepared duration');- const context=new OfflineAudioContext(buffer.numberOfChannels,length*3,rate);- const source=createAudioSource(context,decoded,record);- source.connect(context.destination); source.start();- const rendered=await context.startRendering();- let wrap=0, join=0, renderError=0, controls=0;- for (let c=0;c<buffer.numberOfChannels;c++) {- const x=decoded.getChannelData(c), y=buffer.getChannelData(c), r=rendered.getChannelData(c);- if (record.loop) {- const baseline=x[first+count]-x[first+count-1];- for(let lap=1;lap<3;lap++) {- const at=lap*length;- wrap=Math.max(wrap,Math.abs((r[at]-r[at-1])-baseline));- if(Math.abs((r[at]+.125-r[at-1])-baseline)>.12) controls++;- }- const at=n-2*count;- join=Math.max(join,Math.abs((y[at]-y[at-1])-(x[first+n-count]-x[first+n-count-1])));- }- for(let i=0;i<r.length;i++) {- const expected=record.loop ? y[i%length] : (i<length ? y[i] : 0);- renderError=Math.max(renderError,Math.abs(r[i]-expected));- }- }- const pcmFrames=record.loop ? rendered.length : buffer.length;- const interleaved=new Float32Array(pcmFrames*rendered.numberOfChannels);- for(let i=0;i<pcmFrames;i++) for(let c=0;c<rendered.numberOfChannels;c++)- interleaved[i*rendered.numberOfChannels+c]=rendered.getChannelData(c)[i];- const u8=new Uint8Array(interleaved.buffer);- let binary=''; for(let i=0;i<u8.length;i+=16384) binary+=String.fromCharCode(...u8.subarray(i,i+16384));- return { decoded_frames:decoded.length, length, overlap:count, channels:rendered.numberOfChannels,- added_wrap_error:wrap, added_join_error:join, render_error:renderError, controls_detected:controls,- pcm:btoa(binary) };- },{code:`data:text/javascript;base64,${shipped.toString('base64')}`,encoded:bytes.toString('base64'),record,rate});- assert.equal(result.added_wrap_error,0);- assert.equal(result.added_join_error,0);- assert.ok(result.render_error<1e-7);- if(record.loop) assert.equal(result.controls_detected,result.channels*2);- const pcmName=`${item.name}-${name}-${rate}-${fmt}.f32`;- await writeFile(resolve(outputDir,pcmName),Buffer.from(result.pcm,'base64'));- delete result.pcm;- reports.push({ name:item.name,browser:name,rate,fmt,loop:record.loop,target_lufs:record.target_lufs,pcm:pcmName,...result });- await writeFile(resolve(outputDir,'render.json'),JSON.stringify(report,null,2));- }- }- }- } finally { await browser.close(); }-}-for (const item of cases) for (const rate of [44100,48000]) {- const rows=reports.filter(row=>row.name===item.name && row.rate===rate);- assert.equal(rows.length,engines.length*2, 'both codecs must render in every selected engine');- if(rows[0].loop) assert.equal(new Set(rows.map(row=>row.length)).size,1, 'engine or codec changed the loop length');- else assert.ok(Math.max(...rows.map(row=>row.length))-Math.min(...rows.map(row=>row.length))<=1,- 'one-shot lengths differ by more than the single-frame decode tolerance');-}-await writeFile(resolve(outputDir,'render.json'),JSON.stringify(report,null,2));-console.log(JSON.stringify({passed:reports.length,module_sha256:digest}));diff --git a/tests/audio/test_sound.py b/tests/audio/test_sound.pydeleted file mode 100644index 33a526c..0000000--- a/tests/audio/test_sound.py+++ /dev/null@@ -1,467 +0,0 @@-# SPDX-License-Identifier: Apache-2.0-from concurrent.futures import ThreadPoolExecutor-import io-import http.client-import json-import re-import subprocess-import threading-import urllib.error-import wave--import numpy as np-import pytest--from sprite_gen.audio import cache, provider, processing, sound-from sprite_gen.audio.manifest import load as load_sound-from sprite_gen.gen import retry--[email protected](autouse=True)-def fake_credential(monkeypatch):- monkeypatch.setenv('ELEVENLABS_API_KEY', 'synthetic-key')---def wav_bytes(seconds=3):- t = np.arange(round(seconds * 48000)) / 48000- x = .08 * np.sin(2 * np.pi * 321.3 * t)- x[100:110] = .95 # sparse peak: gain alone would clip- data = io.BytesIO()- with wave.open(data, 'wb') as f:- f.setnchannels(1)- f.setsampwidth(2)- f.setframerate(48000)- f.writeframes((x * 32767).astype('<i2').tobytes())- return data.getvalue()---def stereo_wav(x, rate=48000):- data = io.BytesIO()- with wave.open(data, 'wb') as f:- f.setnchannels(2)- f.setsampwidth(2)- f.setframerate(rate)- f.writeframes((np.clip(x, -1, 1) * 32767).astype('<i2').tobytes())- return data.getvalue()---def hit(seconds, body_hz, body_tau, sweep, knock_hz, knock_tau, knock_gain, noise_tau, noise_gain, smooth, stereo, seed):- """A synthetic hit: a pitch-dropping body, a knock and a noise burst decaying from one onset."""- t = np.arange(round(seconds * 48000)) / 48000- body = np.sin(2*np.pi*np.cumsum(body_hz*(1 + sweep*np.exp(-t/.03)))/48000) * np.exp(-t/body_tau)- knock = knock_gain * np.sin(2*np.pi*knock_hz*t) * np.exp(-t/knock_tau)- noise = np.random.default_rng(seed).standard_normal((len(t), 2))- noise[:, 1] = (1-stereo)*noise[:, 0] + stereo*noise[:, 1]- if smooth > 1:- noise = np.stack([np.convolve(n, np.ones(smooth)/smooth, 'same') for n in noise.T], axis=1) * np.sqrt(smooth)- x = .25 * ((body + knock)[:, None] + noise*(noise_gain*np.exp(-t/noise_tau))[:, None])- x[:16] *= np.linspace(0, 1, 16)[:, None]- return stereo_wav(x)---HITS = {- # A thud whose AAC reconstruction overshoots the limited PCM peak by several dB.- 'thud': dict(seconds=.6, body_hz=77.19, body_tau=.1322, sweep=.3641, knock_hz=704.9, knock_tau=.03642,- knock_gain=.8461, noise_tau=.04146, noise_gain=.881, smooth=2, stereo=.7, seed=634996),- # A few milliseconds of energy: at the -2 dBTP limiter ceiling it cannot reach -18 LUFS.- 'click': dict(seconds=.5, body_hz=900, body_tau=.003, sweep=0, knock_hz=2500, knock_tau=.002,- knock_gain=.5, noise_tau=.002, noise_gain=1, smooth=1, stereo=0, seed=7),- # FFmpeg 5.1's loudnorm first pass measures its output for this hit at -inf LUFS (7.1's does not).- 'unanalysable': dict(seconds=.6, body_hz=55.03, body_tau=.09572, sweep=2.822, knock_hz=692.4, knock_tau=.01984,- knock_gain=.2113, noise_tau=.01464, noise_gain=.8967, smooth=1, stereo=.3, seed=212970),-}---def bundle(tmp_path, monkeypatch, name, seconds):- monkeypatch.setattr(provider, 'generate', lambda req: (hit(**HITS[name]), {}))- return sound.generate(kind='sfx', prompt='synthetic hit', duration=seconds, event='hit',- cache_dir=tmp_path/'cache', out_dir=tmp_path/'out')--[email protected]('name', HITS)-def test_short_hits_pass_the_one_loudness_rule(tmp_path, monkeypatch, name):- result = bundle(tmp_path, monkeypatch, name, HITS[name]['seconds'])- level = result['normalization']- goal = processing.loudness_goal(-18, level['pcm_lufs'], level['pcm_true_peak_dbtp'])- if name == 'click':- assert level['pcm_true_peak_dbtp'] >= -2.2 and goal == level['pcm_lufs'] < -19- else:- assert goal == -18- for file in result['files'].values():- assert processing.meets(file['lufs'], file['true_peak_dbfs'], goal)- assert file['true_peak_dbfs'] <= -1- load_sound(tmp_path/'out'/'sound.json', 50_000_000)---def test_a_clip_loudnorm_cannot_analyse_is_normalized_by_the_limiter(tmp_path, monkeypatch):- analyse = processing._loudnorm- monkeypatch.setattr(processing, '_loudnorm', lambda *a: {**analyse(*a), 'target_offset': float('inf')})- source = tmp_path/'source.wav'- source.write_bytes(hit(**HITS['unanalysable']))- _, level, _ = processing.normalize(processing.decode(source), -18, False)- assert level['method'] == 'limiter' and abs(level['pcm_lufs'] + 18) <= .2---def test_a_bundle_is_refused_when_its_files_miss_the_rule(tmp_path, monkeypatch):- bundle(tmp_path, monkeypatch, 'click', .5)- path = tmp_path/'out'/'sound.json'- original = json.loads(path.read_text())- headroom = json.loads(path.read_text())- headroom['normalization']['pcm_true_peak_dbtp'] = -8 # quiet with headroom: the goal is the target- hot = json.loads(path.read_text())- hot['files']['m4a']['true_peak_dbfs'] = -.5- old = json.loads(path.read_text())- del old['normalization']- relabeled = json.loads(path.read_text())- relabeled['recipe']['processing_version'] = 3 # version 3 had no peak-limited goal; its files measure against -18- recipe2 = json.loads(path.read_text())- recipe2['recipe']['processing_version'] = 2- for manifest, refusal in ((headroom, 'does not match'), (hot, 'invalid audio true peak'), (old, 'version 4'),- (relabeled, 'does not match'), (recipe2, 'version 3 or 4')):- path.write_text(json.dumps(manifest))- with pytest.raises(ValueError, match=refusal):- load_sound(path, 50_000_000)- path.write_text(json.dumps(original))- load_sound(path, 50_000_000)---def test_the_rule_needs_a_peak_reason_and_never_relaxes_the_peak():- assert processing.loudness_goal(-18, -24, -8) == -18 # quiet with headroom- assert processing.loudness_goal(-18, -18.1, -2) == -18 # normalized to the target- assert processing.loudness_goal(-18, -24, -2.1) == -24 # peak-limited- assert processing.meets(-24.3, -1.9, -24) and not processing.meets(-25.2, -1.9, -24)- assert not processing.meets(-24, -.5, -24) and not processing.meets(-18, -.9, -18)- assert not processing.meets(float('-inf'), -50, -18)---def test_export_refuses_a_quiet_file_with_headroom_and_a_hot_peak(tmp_path, monkeypatch):- # One file that fails meets() is enough: every failure reaches the same raise, and- # the quiet-with-headroom and hot-peak conditions are pinned on meets() itself in- # test_the_rule_needs_a_peak_reason_and_never_relaxes_the_peak.- t = np.arange(48000) / 48000- pcm = np.stack([np.sin(2*np.pi*440*t)]*2, axis=1) * .1365- pcm[24000:24048] = .94 # about -18 LUFS with a -0.5 dBTP spike- stats = processing.measure(pcm)- record = {'pcm_lufs': stats['lufs'], 'pcm_true_peak_dbtp': stats['true_peak']}- decode = processing.decode- monkeypatch.setattr(processing, 'decode', lambda path: pcm.copy() if path.name == 'source' else decode(path))- monkeypatch.setattr(processing, 'normalize', lambda samples, target, loop: (samples, record, stats))- monkeypatch.setattr(processing, 'limit_gain', lambda samples, *a: samples) # no correction can rescue it- with pytest.raises(ValueError, match='ogg failed loudness/peak check') as refusal:- processing.export(tmp_path/'source', tmp_path, target_lufs=-18, loop=False, crossfade=0)- lufs, peak = map(float, re.search(r'\(([-\d.]+) LUFS, ([-\d.]+) dBTP', str(refusal.value)).groups())- assert abs(lufs + 18) <= 1 and peak > -1--[email protected]('seconds', [0, .3])-def test_silent_or_unmeasurable_audio_is_refused(tmp_path, seconds):- source = tmp_path/'source.wav'- t = np.arange(round(seconds*48000) or 48000) / 48000- source.write_bytes(stereo_wav(np.stack([np.sin(2*np.pi*440*t)*(seconds > 0)*.5]*2, axis=1)))- with pytest.raises(ValueError, match='silent or unmeasurable'): # 0.3 s is shorter than one 400 ms block- processing.export(source, tmp_path, target_lufs=-18, loop=False, crossfade=0)---def test_formats_are_measured_over_their_pcm_frames_and_blocks(tmp_path, monkeypatch):- frames, at = 28800, (6000, 17000)- x = np.zeros((frames, 2))- k = np.arange(-64, 65)- for frame in at:- x[frame-64:frame+65] += (.5*np.sinc(k/2.5)*np.hanning(len(k)))[:, None]- source = tmp_path/'source.wav'- source.write_bytes(stereo_wav(x))- measure, seen, pcm = processing.measure, [], {}- def spy(samples, gate=None):- seen.append((samples.copy(), gate))- return measure(samples, gate)- def settled(samples, target, loop):- pcm.update(measure(samples))- return samples, {'pcm_lufs': pcm['lufs'], 'pcm_true_peak_dbtp': pcm['true_peak']}, pcm- monkeypatch.setattr(processing, 'measure', spy)- monkeypatch.setattr(processing, 'normalize', settled)- target = measure(processing.decode(source))['lufs'] # two clicks; their own loudness is the goal- result = processing.export(source, tmp_path, target_lufs=target, loop=False, crossfade=0)- assert {file['encode_passes'] for file in result['files'].values()} == {1} and len(seen) == 2- for samples, gate in seen:- assert gate is pcm['gate'] and len(samples) == frames- peaks = [int(np.argmax(np.abs(samples[f-1000:f+1000, 0]))) + f - 1000 for f in at]- assert all(abs(p - f) <= 2 for p, f in zip(peaks, at)), peaks---def test_a_block_at_the_relative_gate_cannot_move_a_file_by_whole_lu():- t = np.arange(28800) / 48000- level = np.where(t < .1, 1, np.where(t < .5, .107, .0333)) # the last block sits 0.2 dB under the gate- pcm = np.stack([np.sin(2*np.pi*1000*t)*level*.3]*2, axis=1)- codec = pcm * np.where(t < .5, 1, 2.5)[:, None] # a change in the last 100 ms lifts it over the gate- reference = processing.measure(pcm)- assert abs(processing.measure(codec)['lufs'] - reference['lufs']) > 1- assert abs(processing.measure(codec, reference['gate'])['lufs'] - reference['lufs']) < .05---def test_provider_contract_and_safe_retry(monkeypatch, capsys):- requests = []- class Answer:- status = 200- headers = {'character-cost': '120', 'request-id': 'req-synthetic'}- def __enter__(self): return self- def __exit__(self, *args): pass- def read(self): return b'audio'- def send(req, **kw):- requests.append(req)- if len(requests) == 1:- raise urllib.error.HTTPError(req.full_url, 429, 'busy', {'retry-after':'0'},- io.BytesIO(b'{"detail":{"status":"system_busy","message":"secret-key"}}'))- return Answer()- monkeypatch.setenv('ELEVENLABS_API_KEY', 'secret-key')- monkeypatch.setattr(provider, 'urlopen', send)- monkeypatch.setattr(retry, '_sleep', lambda _: None)- req = provider.request('sfx', 'Impact', 3, True)- audio, meta = provider.generate(req)- assert audio == b'audio' and len(requests) == 2- assert requests[0].full_url.endswith('/sound-generation?output_format=mp3_44100_128')- assert json.loads(requests[0].data) == {'text':'Impact', 'duration_seconds':3.0,- 'loop':True, 'model_id':'eleven_text_to_sound_v2', 'prompt_influence':.3}- assert meta['character_cost'] == 120 and meta['auth_source'] == 'ELEVENLABS_API_KEY'- err = capsys.readouterr().err- assert 'secret-key' not in err- assert '[gen] elevenlabs: running on ELEVENLABS_API_KEY — this is a per-call API charge' in err- monkeypatch.setenv('ELEVENLABS_API_KEY', ' ')- with pytest.raises(ValueError, match='sound: ELEVENLABS_API_KEY is set but empty'):- provider.generate(req)- monkeypatch.delenv('ELEVENLABS_API_KEY')- with pytest.raises(ValueError, match='ELEVENLABS_API_KEY is required for a new sound request'):- provider.generate(req)- bgm = provider.request('bgm', 'Adventure', 8, True)- assert bgm['body'] == {'prompt':'Adventure', 'music_length_ms':8000,- 'model_id':'music_v1', 'force_instrumental':True}--[email protected]('status,body', [(500, {}), (429, {'detail':{'status':'quota_exceeded'}})])-def test_unproven_refusals_are_not_retried(status, body):- assert retry.again_after('elevenlabs', 'POST', status, body, {}, 1) is None--[email protected]('code', ['system_busy', 'too_many_concurrent_requests'])-def test_the_two_documented_busy_codes_are_retried_and_named(code):- body = {'detail': {'status': code}}- assert retry.again_after('elevenlabs', 'POST', 429, body, {}, 1) is not None- assert provider._code(body) == code---def test_cache_serializes_paid_requests_and_survives_uncertain_results(tmp_path):- db = tmp_path / 'cache.sqlite3'- entered, release = threading.Event(), threading.Event()- def make():- entered.set()- assert release.wait(5)- return b'audio', {'request_id':'synthetic'}- with ThreadPoolExecutor(2) as pool:- first = pool.submit(cache.obtain, db, {'a':1}, make)- assert entered.wait(5)- with pytest.raises(ValueError, match='unresolved'):- cache.obtain(db, {'a':1}, make)- release.set()- assert first.result()[0] == b'audio'- assert cache.obtain(db, {'a':1}, lambda: pytest.fail('charged twice'))[2] is True- def broken(): raise OSError('connection closed')- with pytest.raises(OSError): cache.obtain(db, {'a':2}, broken)- with pytest.raises(ValueError, match='unresolved'):- cache.obtain(db, {'a':2}, lambda: pytest.fail('ambiguous POST resent'))---def test_actual_exports_are_normalized_and_reused(tmp_path, monkeypatch):- called = []- monkeypatch.setattr(provider, 'generate', lambda req: (called.append(req) or wav_bytes(), {}))- kw = dict(kind='sfx', prompt='synthetic', duration=3, event='combat.hit',- cache_dir=tmp_path/'cache', out_dir=tmp_path/'out')- first = sound.generate(**kw)- second = sound.generate(**{**kw, 'out_dir':tmp_path/'out2', 'event':'combat.other'})- assert len(called) == 1 and second['cache_hit']- assert first['event'] == 'combat.hit'- for fmt, metadata in first['files'].items():- path = tmp_path/'out'/metadata['path']- assert path.suffix == '.' + fmt and path.stat().st_size > 100- assert abs(metadata['lufs'] - first['target_lufs']) <= 1- assert metadata['true_peak_dbfs'] <= -1- assert abs(metadata['duration_seconds']-3) < .05---def test_processing_failure_reuses_paid_audio(tmp_path, monkeypatch):- called = []- monkeypatch.setattr(provider, 'generate', lambda req: (called.append(req) or wav_bytes(), {}))- original = processing.export- monkeypatch.setattr(processing, 'export', lambda *a, **kw: (_ for _ in ()).throw(ValueError('processing failed')))- kw = dict(kind='sfx', prompt='synthetic', duration=3, event='hit', cache_dir=tmp_path/'cache', out_dir=tmp_path/'out')- with pytest.raises(ValueError, match='processing failed'): sound.generate(**kw)- assert not kw['out_dir'].exists()- monkeypatch.setattr(processing, 'export', original)- assert sound.generate(**kw)['cache_hit'] and len(called) == 1--[email protected]('kind,duration,loop', [('sfx', .5, False), ('bgm', 3, True)])-def test_short_effect_and_loop_encoded_playback(tmp_path, monkeypatch, kind, duration, loop):- monkeypatch.setattr(provider, 'generate', lambda req: (wav_bytes(duration), {}))- result = sound.generate(kind=kind, prompt='synthetic', duration=duration, event='sample',- cache_dir=tmp_path/'cache', out_dir=tmp_path/'out')- assert result['loop'] is loop- meta = result['playback']- assert meta == {'version': 2, 'sample_rate': 48000, 'start_frame': 0,- 'end_frame': round(duration*48000), 'overlap_frames': 12000 if loop else 0}- assert result['duration_seconds'] == (meta['end_frame']-meta['overlap_frames'])/48000- assert 'loop_end_seconds' not in result and 'codec_taper_seconds' not in result- for file in result['files'].values():- assert file['duration_seconds'] >= duration- assert len(processing.decode(tmp_path/'out'/file['path'])) >= meta['end_frame']---def test_preflight_does_not_claim_and_cached_source_works_without_key(tmp_path, monkeypatch):- db = tmp_path/'cache.sqlite3'- def no_key(): raise ValueError('missing key')- with pytest.raises(ValueError, match='missing key'):- cache.obtain(db, {'request':1}, lambda: pytest.fail('must preflight'), prepare=no_key)- assert cache.obtain(db, {'request':1}, lambda: (b'audio', {}))[2] is False- assert cache.obtain(db, {'request':1}, lambda: pytest.fail('cache must suffice'), prepare=no_key)[2] is True---def test_error_body_and_transport_cannot_disclose_key(monkeypatch, capsys):- key = 'secret-api-key-should-never-appear'- monkeypatch.setenv('ELEVENLABS_API_KEY', key)- def refuse(req, **kwargs):- raise urllib.error.HTTPError(req.full_url, 422, key, {}, io.BytesIO(json.dumps({'detail':{'message':key,'status':key}}).encode()))- monkeypatch.setattr(provider, 'urlopen', refuse)- with pytest.raises(ValueError) as err: provider.generate(provider.request('sfx','impact',1,False))- assert key not in str(err.value) + capsys.readouterr().err- def broken(*a, **kw): raise OSError(key)- monkeypatch.setattr(provider, 'urlopen', broken)- with pytest.raises(ValueError) as err: provider.generate(provider.request('sfx','impact',1,False))- assert key not in str(err.value) + capsys.readouterr().err---def test_broken_refusal_body_is_not_retried_or_printed(monkeypatch, capsys):- calls = []- class Broken(io.BytesIO):- def read(self, *args): raise http.client.IncompleteRead(b'secret-key', 100)- def send(req, **kw):- calls.append(req)- raise urllib.error.HTTPError(req.full_url, 429, 'busy', {}, Broken())- monkeypatch.setattr(provider, 'urlopen', send)- with pytest.raises(ValueError, match='unresolved') as err:- provider.generate(provider.request('sfx', 'impact', 1, False))- assert len(calls) == 1 and 'secret-key' not in str(err.value) + capsys.readouterr().err---def test_cli_and_python_entry_publish_the_same_bundle(tmp_path, monkeypatch, capsys):- from sprite_gen.cli import main- monkeypatch.setattr(provider, 'generate', lambda req: (wav_bytes(1), {}))- args = ['sound', '--kind', 'sfx', '--prompt', 'synthetic', '--duration', '1', '--event', 'hit',- '--out-dir', str(tmp_path/'out'), '--cache-dir', str(tmp_path/'cache')]- assert main(args) == 0- monkeypatch.delenv('ELEVENLABS_API_KEY')- assert sound.run(kind='sfx',prompt='synthetic',duration=1,event='hit',out_dir=str(tmp_path/'out'),- cache_dir=tmp_path/'cache') == 0- lines = [json.loads(line) for line in capsys.readouterr().out.splitlines()]- assert lines[1]['cache_hit'] is True- assert lines[0]['manifest'] == lines[1]['manifest']---def test_codec_reconstruction_keeps_a_broadband_transient_below_peak_ceiling(tmp_path, monkeypatch):- t = np.arange(24000)/48000- x = .8*np.sign(np.sin(2*np.pi*2200*t))*np.exp(-t*32)- stream=io.BytesIO()- with wave.open(stream,'wb') as f:- f.setnchannels(1); f.setsampwidth(2); f.setframerate(48000)- f.writeframes((x*32767).astype('<i2').tobytes())- monkeypatch.setattr(provider,'generate',lambda _: (stream.getvalue(), {}))- result=sound.generate(kind='sfx',prompt='synthetic transient',duration=.5,event='hit',- out_dir=tmp_path/'out',cache_dir=tmp_path/'cache')- for file in result['files'].values():- assert file['true_peak_dbfs'] <= -1- assert abs(file['lufs']+18) <= 1---def test_export_keeps_source_frames_until_browser_preparation(tmp_path, monkeypatch):- t = np.arange(48000*3)/48000- x = np.stack([.1*np.sin(2*np.pi*121*t+.5), .4*np.cos(2*np.pi*73*t)], axis=1).astype('<f4')- monkeypatch.setattr(processing, 'decode', lambda path: x.copy())- seen = []- def normalize(samples, target, loop):- seen.append(samples.copy())- return samples, {}, {'lufs': -20, 'true_peak': -2, 'gate': None}- monkeypatch.setattr(processing, 'normalize', normalize)- monkeypatch.setattr(processing, 'measure', lambda *a: {'lufs': -20, 'true_peak': -2, 'gate': None})- processing.export(tmp_path/'source', tmp_path, target_lufs=-20, loop=True, crossfade=.25)- np.testing.assert_array_equal(seen[0], x)--[email protected]('overlap', [20, 21])-def test_export_reserves_overlap_for_minimum_playback_rate(tmp_path, monkeypatch, overlap):- # At 8 kHz, the 20-frame overlap leaves only one blend frame after- # interval quantization, loop rounding and a one-frame decoder shortfall.- monkeypatch.setattr(processing, 'decode', lambda path: np.ones((48005, 2), dtype='<f4'))- def reached_normalization(*args):- raise RuntimeError('normalization reached')- monkeypatch.setattr(processing, 'normalize', reached_normalization)- if overlap == 20:- with pytest.raises(ValueError, match='overlap too short.*8000 Hz'):- processing.export(tmp_path/'source', tmp_path, target_lufs=-20, loop=True, crossfade=overlap/48000)- assert not list(tmp_path.iterdir())- else:- with pytest.raises(RuntimeError, match='normalization reached'):- processing.export(tmp_path/'source', tmp_path, target_lufs=-20, loop=True, crossfade=overlap/48000)--[email protected]('millisecond_timescale', [False, True])-def test_m4a_container_preserves_declared_frames(tmp_path, monkeypatch, millisecond_timescale):- frames = 144003- source = tmp_path/'source.wav'- source.write_bytes(wav_bytes(frames/48000))- if millisecond_timescale:- encode = processing._ffmpeg- def old_timescale(args, data=None):- if str(args[-1]).endswith('.m4a'):- args = [*args[:-1], '-movie_timescale', '1000', args[-1]]- return encode(args, data)- monkeypatch.setattr(processing, '_ffmpeg', old_timescale)- with pytest.raises(ValueError, match='m4a container duration'):- processing.export(source, tmp_path, target_lufs=-20, loop=True, crossfade=.25)- return- result = processing.export(source, tmp_path, target_lufs=-20, loop=True, crossfade=.25)- probe = subprocess.run(['ffprobe', '-v', 'error', '-select_streams', 'a:0',- '-show_entries', 'stream=duration_ts,time_base', '-of', 'json',- str(tmp_path/result['files']['m4a']['path'])],- capture_output=True, check=True)- stream = json.loads(probe.stdout)['streams'][0]- assert stream == {'time_base': '1/48000', 'duration_ts': frames}- assert result['playback']['end_frame'] == frames---def test_missing_ffprobe_preflights_before_generation(tmp_path, monkeypatch):- which = processing.shutil.which- monkeypatch.setattr(processing.shutil, 'which', lambda name: None if name == 'ffprobe' else which(name))- monkeypatch.setattr(provider, 'generate', lambda _: pytest.fail('generation before tool preflight'))- with pytest.raises(ValueError, match='ffprobe is required'):- sound.generate(kind='sfx', prompt='synthetic', duration=3, event='hit',- cache_dir=tmp_path/'cache', out_dir=tmp_path/'out')---def test_old_processed_output_is_rejected_but_raw_cache_survives(tmp_path, monkeypatch):- calls = []- monkeypatch.setattr(provider, 'generate', lambda req: (calls.append(req) or wav_bytes(), {}))- kw = dict(kind='bgm', prompt='synthetic', duration=3, event='music',- cache_dir=tmp_path/'cache', out_dir=tmp_path/'out')- result = sound.generate(**kw)- assert result['version'] == 2- assert result['recipe']['processing_version'] == 4- # One old version is enough: any recipe that differs is refused by the same check.- old = {**result, 'version': 3, 'recipe': {**result['recipe'], 'processing_version': 3}}- (kw['out_dir']/'sound.json').write_text(json.dumps(old))- with pytest.raises(ValueError, match='different sound'):- sound.generate(**kw)- monkeypatch.delenv('ELEVENLABS_API_KEY')- fresh = sound.generate(**{**kw, 'out_dir': tmp_path/'new'})- assert fresh['cache_hit'] and len(calls) == 1diff --git a/tests/background/test_tile_xy.py b/tests/background/test_tile_xy.pydeleted file mode 100644index 43e4dfa..0000000--- a/tests/background/test_tile_xy.py+++ /dev/null@@ -1,133 +0,0 @@-# SPDX-License-Identifier: Apache-2.0-"""`background-tile --axis xy`: one run, seamless on both axes, a report that measures both joins.--Synthetic oracles: a doubly periodic texture (an exact tile exists), textures that can only be-joined on one axis (the report must say which), and the seam search that keeps the first axis's-join when the second axis is quilted.-"""--import json--import numpy as np-import pytest-from PIL import Image--from sprite_gen.background import tile-from sprite_gen.background.tile import inspect_tile, make_tile---def periodic(period=16, width=None, height=None):- width, height = width or 3 * period + 7, height or 3 * period + 5- y, x = np.indices((height, width))- u, v = 2 * np.pi * x / period, 2 * np.pi * y / period- pixels = np.stack((110 + 50 * np.sin(u) + 30 * np.cos(v),- 120 + 40 * np.cos(u + v),- 90 + 35 * np.sin(v) * np.cos(u),- np.full_like(x, 255)), axis=-1)- return Image.fromarray(pixels.round().astype(np.uint8))---def ramp(axis, period=16, size=60):- """Rows (or columns) brighten steadily: periodic along one axis, impossible to wrap along the other."""- y, x = np.indices((size, size))- along = y if axis == "y" else x- pixels = np.stack((40 + 3 * along, 60 + 2 * along, 30 + along, np.full_like(x, 255)), axis=-1)- return Image.fromarray(pixels.astype(np.uint8))---def test_doubly_periodic_source_gives_an_exact_crop_and_both_joins_pass():- source = periodic()- before = source.tobytes()- result, report = make_tile(source, 16, axis="xy", overlap=5)- assert result.size == (16, 16) and result.mode == "RGBA"- x0, y0, x1, y1 = report["core_crop"]- assert (x1 - x0, y1 - y0) == (16, 16)- assert result.tobytes() == source.crop((x0, y0, x1, y1)).tobytes()- assert source.tobytes() == before- assert report["axis"] == "xy"- assert report["status"] == "pass" and report["review_reasons"] == []- assert set(report["axes"]) == {"x", "y"}- for axis in ("x", "y"):- measured = report["axes"][axis]- assert measured["status"] == "pass"- assert measured["edge_color_difference"] == inspect_tile(result, axis)["edge_color_difference"]- assert "quilt_seam" in measured- json.dumps(report, allow_nan=False)--[email protected]("bad", ["x", "y"])-def test_a_join_that_stays_visible_on_one_axis_fails_the_report_and_names_that_axis(bad):- good = "y" if bad == "x" else "x"- _, report = make_tile(ramp(bad), 16, axis="xy", overlap=5)- assert report["status"] == "needs-review"- assert report["axes"][bad]["status"] == "needs-review"- assert report["axes"][good]["status"] == "pass"- assert report["review_reasons"]- assert all(reason.startswith(f"{bad}: ") for reason in report["review_reasons"])--[email protected]("bad", ["x"])-def test_inspection_of_both_axes_catches_a_tile_seamless_on_only_one(bad):- # Periodic along one axis, a hard break along the other: one-axis inspection along the good axis passes.- good = "y" if bad == "x" else "x"- pixels = np.asarray(periodic(16, 16, 16)).copy()- if bad == "x":- pixels[:, 8:, :3] = 255 - pixels[:, 8:, :3]- else:- pixels[8:, :, :3] = 255 - pixels[8:, :, :3]- image = Image.fromarray(pixels)- assert inspect_tile(image, good)["status"] == "pass"- report = tile.inspect_tile_xy(image)- assert report["status"] == "needs-review"- assert report["axes"][bad]["status"] == "needs-review"- assert report["axes"][good]["status"] == "pass"---def test_cyclic_seam_keeps_its_two_ends_within_one_step():- # A zero-error path that drifts from column 0 to column 3: the open search follows it exactly,- # the cyclic one must end within one step of where it starts (rows 0 and -1 are wrap neighbours).- error = np.full((8, 6), 100.0)- path = [0, 0, 1, 1, 2, 2, 3, 3]- for row, col in enumerate(path):- error[row, col] = 0- open_seam, open_score = tile._minimum_seam(error)- assert open_seam.tolist() == path and open_score == 0- seam, score = tile._minimum_seam(error, cyclic=True)- assert abs(int(seam[0]) - int(seam[-1])) <= 1- assert np.all(np.abs(np.diff(seam)) <= 1)- assert score > 0---def test_second_pass_keeps_the_first_axis_join_exact_on_a_texture_with_a_drifting_match():- # Rows repeat every 16 px; columns repeat every 16 px except that the rows' best match drifts- # across x. The y quilt's seam may not differ by more than one step between the last and the- # first column, so the x join (a wrap neighbour pair) stays a source adjacency or one seam step.- rng = np.random.default_rng(7)- base = periodic(16, 60, 60)- pixels = np.asarray(base).astype(np.int16)- pixels[..., :3] += rng.integers(-3, 4, pixels[..., :3].shape)- result, report = make_tile(Image.fromarray(np.clip(pixels, 0, 255).astype(np.uint8)), 16, axis="xy", overlap=6)- seam = report["axes"]["y"]["quilt_seam"]["positions"]- assert len(seam) == 16- assert abs(seam[0] - seam[-1]) <= 1- assert report["axes"]["x"]["status"] == "pass"---def test_xy_needs_the_period_plus_overlap_on_both_axes():- with pytest.raises(ValueError, match="along y"):- make_tile(Image.new("RGBA", (40, 20)), 16, axis="xy", overlap=5)- with pytest.raises(ValueError, match="along x"):- make_tile(Image.new("RGBA", (20, 40)), 16, axis="xy", overlap=5)---def test_cli_accepts_axis_xy(tmp_path):- source = tmp_path / "ground.png"- periodic().save(source)- out = tmp_path / "tile.png"- assert tile.main(["--source", str(source), "--out", str(out), "--period", "16", "--overlap", "5",- "--axis", "xy"]) == 0- report = json.loads((tmp_path / "tile.report.json").read_text())- assert report["axis"] == "xy" and report["status"] == "pass"- assert report["source"] == str(source) and report["output"] == str(out)- with Image.open(out) as image:- assert image.size == (16, 16)diff --git a/tests/compose/test_game_pack.py b/tests/compose/test_game_pack.pydeleted file mode 100644index d3870fd..0000000--- a/tests/compose/test_game_pack.py+++ /dev/null@@ -1,242 +0,0 @@-# SPDX-License-Identifier: Apache-2.0-"""Game-sized exports retain playback order, pivots and policies across pages."""-import json-import subprocess-import sys--import pytest-from PIL import Image--from keyed_figure import colour_outside, figure-from sprite_gen.compose import game_pack-from sprite_gen.util.resample import resize_cell---def write_json(path, data):- path.write_text(json.dumps(data), encoding="utf-8")- return path---def strip(tmp_path):- image = Image.new("RGBA", (36, 20))- for index, color in enumerate(("red", "green", "blue")):- image.paste(Image.new("RGBA", (12, 20), color), (index * 12, 0))- image.save(tmp_path / "walk.strip.png")- return write_json(tmp_path / "walk.strip.json", {- "frames": 3, "w": 12, "h": 20, "delay_ms": 80,- "body_h": 16, "anchor": [4, 18], "loop": False, "hold_last": True,- "end_frame": 2, "events": [{"frame": 1, "name": "impact"}], "blend": "add",- "direction": "NE",- })---def request(tmp_path, entries):- return write_json(tmp_path / "game.json", {"version": 1, "assets": entries})---def pixels(out, result, animation):- frames = {key: (page, value) for page in result["textures"] for key, value in page["frames"].items()}- found = []- for key in result["animations"][animation]["frames"]:- page, record = frames[key]- rect = record["frame"]- with Image.open(out / page["image"]) as im:- found.append(im.crop((rect["x"], rect["y"], rect["x"]+rect["w"], rect["y"]+rect["h"])))- return found--[email protected]("scale,resample", [(0.16, None), (0.5, "lanczos")])-def test_scaled_cutout_carries_no_colour_its_source_did_not_have(tmp_path, scale, resample):- src = figure()- src.save(tmp_path / "hero.png")- entry = {"id": "hero", "source": "hero.png", "display": {"height": round(src.height * scale)}}- if resample is not None:- entry["resample"] = resample- result = game_pack.pack(request(tmp_path, [entry]), tmp_path / "out")- (cell,) = pixels(tmp_path / "out", result, "hero")- assert colour_outside(src, cell) == 0- assert cell.tobytes() == resize_cell(src, cell.size).tobytes()- assert colour_outside(src, src.resize(cell.size, Image.Resampling.LANCZOS)) > 100--[email protected]("pixel_metadata", [False, True])-def test_pixel_resampling_keeps_nearest_samples(tmp_path, pixel_metadata):- src = figure()- src.save(tmp_path / "hero.png")- entry = {"id": "hero", "source": "hero.png", "display": {"height": 90}}- if pixel_metadata:- write_json(tmp_path / "hero.json", {- "frames": 1, "w": src.width, "h": src.height, "delay_ms": 100, "frame_variant": "pixel",- })- entry["source"] = "hero.json"- else:- entry["resample"] = "nearest"- result = game_pack.pack(request(tmp_path, [entry]), tmp_path / "out")- (cell,) = pixels(tmp_path / "out", result, "hero")- assert cell.tobytes() == src.resize(cell.size, Image.Resampling.NEAREST).tobytes()---def test_mixed_export_preserves_timing_order_policy_pivot_and_pixel_colors(tmp_path):- strip(tmp_path)- Image.new("RGBA", (4, 6), (61, 29, 243, 127)).save(tmp_path / "pixel.png")- Image.new("RGBA", (12, 12), "yellow").save(tmp_path / "painting.png")- source = request(tmp_path, [- {"id": "walk", "source": "walk.strip.json", "display": {"body_height": 8}},- {"id": "pixel", "source": "pixel.png", "display": {"height": 3}, "resample": "nearest"},- {"id": "painting", "source": "painting.png", "display": {"width": 6}},- ])- out = tmp_path / "out"- result = game_pack.pack(source, out)- assert json.loads((out / "game-pack.json").read_text()) == result- anim = result["animations"]["walk"]- assert (anim["loop"], anim["hold_last"], anim["end_frame"], anim["blend"], anim["direction"]) == (False, True, 2, "add", "NE")- assert anim["events"] == [{"frame": 1, "name": "impact"}]- assert anim["durations_ms"] == [80, 80, 80]- assert anim["anchor"] == [2, 9]- assert [f.getpixel((1, 1)) for f in pixels(out, result, "walk")] == [(255, 0, 0, 255), (0, 128, 0, 255), (0, 0, 255, 255)]- assert {f.size for f in pixels(out, result, "walk")} == {(6, 10)}- assert pixels(out, result, "pixel")[0].getpixel((0, 0)) == (61, 29, 243, 127)- # The hash fields consumed by Phaser 4.2.1 JSONHash, including normalized pivot.- for page in result["textures"]:- assert isinstance(page["frames"], dict)- with Image.open(out / page["image"]) as png, Image.open(out / page["webp"]) as webp:- assert png.size == webp.size- assert png.convert("RGBA").tobytes() == webp.convert("RGBA").tobytes()- assert max(png.size) <= 4096- for value in page["frames"].values():- box, size = value["frame"], value["sourceSize"]- assert value["rotated"] is False and value["trimmed"] is False- assert value["spriteSourceSize"] == {"x": 0, "y": 0, **size}- assert 0 <= box["x"] <= png.width - box["w"]- assert 0 <= box["y"] <= png.height - box["h"]- frame = next(v for p in result["textures"] for k, v in p["frames"].items() if k == anim["frames"][0])- assert frame["pivot"] == {"x": 1/3, "y": 0.9}---def test_direction_sheet_uses_declared_row_positions_and_lengths(tmp_path):- sheet = Image.new("RGBA", (18, 16))- colors = {"N": ["red", "green", "blue"], "S": ["yellow", "purple"]}- for row, code in enumerate(("S", "N")):- for col, color in enumerate(colors[code]):- sheet.paste(Image.new("RGBA", (6, 8), color), (col * 6, row * 8))- sheet.save(tmp_path / "set.png")- write_json(tmp_path / "set.json", {- "kind": "sprite-gen-video-set-sheet", "schema": 1, "sheet": "set.png",- "columns": 3, "cell_w": 6, "cell_h": 8, "anchor": [2, 7], "order": ["N", "S"],- "rows": [{"code": "N", "row": 1, "frames": 3, "delay_ms": 75, "body_h": 6},- {"code": "S", "row": 0, "frames": 2, "delay_ms": 120, "body_h": 6}],- })- source = request(tmp_path, [{"id": "walk", "source": "set.json", "display": {"body_height": 3}}])- out = tmp_path / "out"- result = game_pack.pack(source, out)- assert list(result["animations"]) == ["walk/N", "walk/S"]- for code in ("N", "S"):- anim = result["animations"][f"walk/{code}"]- assert anim["direction"] == code- assert anim["loop"] is True and anim["hold_last"] is False- assert anim["anchor"] == [1, 3.5]- expected = [Image.new("RGBA", (1, 1), c).getpixel((0, 0)) for c in colors[code]]- assert [f.getpixel((1, 1)) for f in pixels(out, result, f"walk/{code}")] == expected-- for direction in ("E", None):- entry = {"id": "walk", "source": "set.json", "display": {"body_height": 3}, "direction": direction}- overridden = request(tmp_path, [entry])- with pytest.raises(ValueError, match="direction.*state"):- game_pack.pack(overridden, tmp_path / "ambiguous")- assert not (tmp_path / "ambiguous").exists()- entry["state"] = "N"- selected = game_pack.pack(request(tmp_path, [entry]), tmp_path / f"selected-{direction}")- assert list(selected["animations"]) == ["walk/N"]- assert selected["animations"]["walk/N"]["direction"] == direction---def test_runtime_atlas_repeated_rectangles_and_variable_durations(tmp_path):- strip(tmp_path)- rects = [{"x": i * 12, "y": 0, "w": 12, "h": 20} for i in (2, 0, 2, 1)]- write_json(tmp_path / "atlas.json", {- "sprite_sheet_alpha": "walk.strip.png", "frame_layout": {"rows": {"hit": rects}},- "animation": {"rows": {"hit": {"durations_ms": [40, 160, 90, 100], "loop": False,- "hold_last": True, "anchor": [5, 19], "events": [{"frame": 2, "name": "hit"}], "end_frame": 3}}},- })- src = request(tmp_path, [{"id": "actor", "source": "atlas.json", "display": {"height": 10}, "resample": "nearest"}])- result = game_pack.pack(src, tmp_path / "out")- anim = result["animations"]["actor/hit"]- assert anim["durations_ms"] == [40, 160, 90, 100]- assert anim["anchor"] == [2.5, 9.5]- assert anim["events"][0]["frame"] == 2- assert [im.getpixel((0, 0)) for im in pixels(tmp_path / "out", result, "actor/hit")] == [(0, 0, 255, 255), (255, 0, 0, 255), (0, 0, 255, 255), (0, 128, 0, 255)]---def test_multipage_and_repeated_export_are_byte_identical(tmp_path):- strip(tmp_path)- src = request(tmp_path, [{"id": "walk", "source": "walk.strip.json", "display": {"height": 10}}])- result = game_pack.pack(src, tmp_path / "first", page_size=12)- assert len(result["textures"]) == 3- game_pack.pack(src, tmp_path / "second", page_size=12)- before = {p.name: p.read_bytes() for p in (tmp_path / "first").iterdir()}- assert before == {p.name: p.read_bytes() for p in (tmp_path / "second").iterdir()}- game_pack.pack(src, tmp_path / "first", page_size=12)- assert before == {p.name: p.read_bytes() for p in (tmp_path / "first").iterdir()}- # Changing a published pack is explicit: a fresh output directory is required.- with pytest.raises(ValueError, match="different|existing|exists"):- game_pack.pack(src, tmp_path / "first", page_size=24)- assert before == {p.name: p.read_bytes() for p in (tmp_path / "first").iterdir()}--[email protected]("change,match", [- ({"display": {"height": 0}}, "positive"),- ({"display": {"height": 5000}}, "4096|page"),- ({"events": [{"frame": 3, "name": "bad"}]}, "event"),- ({"loop": "false"}, "bool"),- ({"end_frame": -1}, "end_frame"),- ({"resample": "typo"}, "resample"),-])-def test_bad_input_never_publishes_partial_output(tmp_path, change, match):- strip(tmp_path)- entry = {"id": "walk", "source": "walk.strip.json", "display": {"height": 10}, **change}- src = request(tmp_path, [entry])- with pytest.raises(ValueError, match=match):- game_pack.pack(src, tmp_path / "out")- assert not (tmp_path / "out").exists()---def test_size_limit_counts_both_images_and_manifest_before_publish(tmp_path):- strip(tmp_path)- src = request(tmp_path, [{"id": "walk", "source": "walk.strip.json", "display": {"height": 10}}])- with pytest.raises(ValueError, match="byte|MB"):- game_pack.pack(src, tmp_path / "out", max_bytes=10)- assert not (tmp_path / "out").exists()- for kwargs in ({"page_size": 4097}, {"max_bytes": 50_000_001}):- with pytest.raises(ValueError):- game_pack.pack(src, tmp_path / "out", **kwargs)---def test_cli_dispatch_and_real_files(tmp_path):- strip(tmp_path)- src = request(tmp_path, [{"id": "walk", "source": "walk.strip.json", "display": {"height": 10}}])- call = subprocess.run([sys.executable, "-m", "sprite_gen.cli", "game-pack", "--request", str(src),- "--out-dir", str(tmp_path / "out")], capture_output=True, encoding="utf-8")- assert call.returncode == 0, call.stderr- assert json.loads(call.stdout)["ok"] is True- assert (tmp_path / "out" / "game-pack.json").is_file()---def test_staging_write_error_cannot_publish_half_a_pack(tmp_path, monkeypatch):- strip(tmp_path)- src = request(tmp_path, [{"id": "walk", "source": "walk.strip.json", "display": {"height": 10}}])- import os- fsync = os.fsync- writes = []-- def full_disk(fd):- writes.append(fd)- if len(writes) == 2:- raise OSError("disk full")- fsync(fd)-- monkeypatch.setattr(os, "fsync", full_disk)- with pytest.raises(OSError, match="disk full"):- game_pack.pack(src, tmp_path / "out")- assert not (tmp_path / "out").exists()- assert not list(tmp_path.glob(".out-*"))diff --git a/tests/compose/test_game_pack_audio.py b/tests/compose/test_game_pack_audio.pydeleted file mode 100644index d9c9687..0000000--- a/tests/compose/test_game_pack_audio.py+++ /dev/null@@ -1,221 +0,0 @@-# SPDX-License-Identifier: Apache-2.0-import hashlib-import json--import numpy as np-import pytest-from PIL import Image--from sprite_gen.audio import processing-from sprite_gen.compose.game_pack import pack---def inputs(tmp_path):- Image.new('RGBA', (8, 8), 'red').save(tmp_path/'image.png')- request = {'version':1, 'assets':[{'id':'hero', 'source':'image.png', 'display':{'width':8},- 'events':[{'frame':0, 'name':'combat.hit'}]}]}- source = tmp_path/'audio'- source.mkdir()- files = {}- for fmt in ('ogg', 'm4a'):- data = b'synthetic-'+fmt.encode()- (source/f'sound.{fmt}').write_bytes(data)- files[fmt] = {'path':f'sound.{fmt}', 'duration_seconds':1, 'lufs':-18,- 'true_peak_dbfs':-2, 'sha256':hashlib.sha256(data).hexdigest()}- manifest = {'kind':'sprite-gen-sound','version':2,'event':'combat.hit', 'audio_kind':'sfx',- 'loop':False,'duration_seconds':1,'target_lufs':-18,'files':files,- 'recipe': {'processing_version':4},- 'normalization': {'pcm_lufs':-18, 'pcm_true_peak_dbtp':-2},- 'playback': {'version':2, 'sample_rate':48000, 'start_frame':0,- 'end_frame':48000, 'overlap_frames':0}}- (source/'sound.json').write_text(json.dumps(manifest))- path = tmp_path/'request.json'- path.write_text(json.dumps(request))- return path, request, manifest---def test_optional_audio_preserves_image_only_bytes_and_packs_events(tmp_path):- path, request, original = inputs(tmp_path)- pack(path, tmp_path/'before')- request['audio'] = []- path.write_text(json.dumps(request))- pack(path, tmp_path/'empty')- assert {p.name:p.read_bytes() for p in (tmp_path/'before').iterdir()} == {- p.name:p.read_bytes() for p in (tmp_path/'empty').iterdir()}- request['audio'] = [{'id':'hit','source':'audio/sound.json'}]- path.write_text(json.dumps(request))- result = pack(path, tmp_path/'with')- audio = result['audio']['hit']- assert audio['event'] == result['animations']['hero']['events'][0]['name']- assert (tmp_path/'with'/audio['files']['ogg']['path']).read_bytes() == b'synthetic-ogg'- assert audio['files']['m4a']['path'] == 'audio-hit.m4a'- assert audio['playback'] == original['playback']- helper = audio['player']- assert helper['path'] == 'sprite-gen-audio-v2.mjs'- assert helper['export'] == 'createAudioSource'- assert hashlib.sha256((tmp_path/'with'/helper['path']).read_bytes()).hexdigest() == helper['sha256']- assert pack(path, tmp_path/'with') == result- total = sum(p.stat().st_size for p in (tmp_path/'with').iterdir())- with pytest.raises(ValueError, match='bytes'):- pack(path, tmp_path/'small', max_bytes=total-1)- assert not (tmp_path/'small').exists()--[email protected]('defect', ['duplicate', 'traversal', 'digest', 'nonfinite', 'badloop', 'old', 'fraction', 'overlap',- 'prerule', 'quiet', 'norecipe', 'recipe2'])-def test_broken_audio_cannot_publish_a_partial_pack(tmp_path, defect):- path, request, manifest = inputs(tmp_path)- request['audio'] = [{'id':'hit','source':'audio/sound.json'}]- if defect == 'duplicate': request['audio'] *= 2- if defect == 'traversal': manifest['files']['ogg']['path'] = '../image.png'- if defect == 'digest': manifest['files']['ogg']['sha256'] = '0'*64- if defect == 'nonfinite': manifest['target_lufs'] = float('nan')- if defect == 'badloop': manifest['loop'] = 'false'- if defect == 'old': manifest['version'] = 1- if defect == 'fraction': manifest['playback']['end_frame'] = 48000.5- if defect == 'overlap': manifest['playback']['overlap_frames'] = 24000- if defect == 'prerule': del manifest['normalization']- if defect == 'quiet': manifest['files']['m4a']['lufs'] = -19.5 # under the target, its PCM not peak-limited- if defect == 'norecipe': del manifest['recipe']- if defect == 'recipe2': manifest['recipe']['processing_version'] = 2- path.write_text(json.dumps(request))- (tmp_path/'audio'/'sound.json').write_text(json.dumps(manifest))- with pytest.raises(ValueError): pack(path, tmp_path/'bad')- assert not (tmp_path/'bad').exists()---# A version 1 pack with sound, packed by 2.44.0 (before request version 2): its file names, the-# manifest's exact bytes and the page's decoded pixels (encoded PNG/WebP bytes depend on the zlib and-# libwebp build). The sound files and the helper are compared byte for byte below.-V1_AUDIO_FILES = ['atlas-000.png', 'atlas-000.webp', 'audio-hit.m4a', 'audio-hit.ogg', 'game-pack.json',- 'sprite-gen-audio-v2.mjs']-V1_AUDIO_MANIFEST_SHA256 = 'b79d31a4f38982f2c4a97b2aa5ddb4e77b545acee29210dac6a0e6649f9f5b67'-V1_AUDIO_PAGE_PIXELS_SHA256 = '834f7685ed723160d26784bb8ba1153e5f8ae56f5ddc8f51ebb0c54b1a63e067'---def with_sound(tmp_path):- path, request, _ = inputs(tmp_path)- request['audio'] = [{'id': 'hit', 'source': 'audio/sound.json'}]- path.write_text(json.dumps(request))- return path, request---def test_version_1_pack_with_sound_keeps_its_files_and_bytes(tmp_path):- path, _ = with_sound(tmp_path)- out = tmp_path/'out'- result = pack(path, out)- assert sorted(p.name for p in out.iterdir()) == V1_AUDIO_FILES- manifest = (out/'game-pack.json').read_bytes()- assert hashlib.sha256(manifest).hexdigest() == V1_AUDIO_MANIFEST_SHA256- assert json.loads(manifest)['version'] == 1- with Image.open(out/'atlas-000.png') as page:- assert hashlib.sha256(page.convert('RGBA').tobytes()).hexdigest() == V1_AUDIO_PAGE_PIXELS_SHA256- for fmt in ('ogg', 'm4a'):- assert (out/f'audio-hit.{fmt}').read_bytes() == f'synthetic-{fmt}'.encode()- assert hashlib.sha256((out/'sprite-gen-audio-v2.mjs').read_bytes()).hexdigest() == result['audio']['hit']['player']['sha256']---def test_version_2_pack_with_sound_adds_only_the_tile_files(tmp_path):- path, request = with_sound(tmp_path)- pack(path, tmp_path/'v1')- Image.new('RGBA', (8, 8), 'blue').save(tmp_path/'ground.png')- request.update(version=2, tiles=[{'id': 'ground', 'source': 'ground.png', 'display': {'width': 16}}])- path.write_text(json.dumps(request))- result = pack(path, tmp_path/'v2')- v1 = {p.name: p.read_bytes() for p in (tmp_path/'v1').iterdir()}- v2 = {p.name: p.read_bytes() for p in (tmp_path/'v2').iterdir()}- assert sorted(v2) == sorted([*v1, 'tile-ground.png', 'tile-ground.webp'])- for name in ('audio-hit.ogg', 'audio-hit.m4a', 'sprite-gen-audio-v2.mjs', 'atlas-000.png', 'atlas-000.webp'):- assert v2[name] == v1[name], name- assert result['version'] == 2 and list(result['audio']) == ['hit']- assert result['tiles']['ground']['image'] == 'tile-ground.png'---SOUND_ONLY_FILES = ['audio-hit.m4a', 'audio-hit.ogg', 'game-pack.json', 'sprite-gen-audio-v2.mjs']--[email protected]('version,assets', [(1, []), (1, None), (2, []), (2, None)])-def test_a_sound_only_request_packs_the_manifest_sound_and_helper(tmp_path, version, assets):- path, request = with_sound(tmp_path)- request['version'] = version- path.write_text(json.dumps(request))- pictured = pack(path, tmp_path/'pictured')- assert pictured['version'] == version and pictured['textures']- if assets is None:- del request['assets']- else:- request['assets'] = assets- path.write_text(json.dumps(request))- out = tmp_path/'sound'- result = pack(path, out)- assert sorted(p.name for p in out.iterdir()) == SOUND_ONLY_FILES- # the manifest a pack with pictures has, its textures and animations empty- assert result == {**pictured, 'textures': [], 'animations': {}}- assert json.loads((out/'game-pack.json').read_bytes()) == result- for name in ('audio-hit.m4a', 'audio-hit.ogg', 'sprite-gen-audio-v2.mjs'):- assert (out/name).read_bytes() == (tmp_path/'pictured'/name).read_bytes(), name- assert pack(path, out) == result--[email protected]('document', [{'version': 1, 'assets': []}, {'version': 1, 'assets': [], 'audio': []},- {'version': 1}, {'version': 2, 'assets': [], 'audio': []}, {'version': 2}])-def test_a_request_with_neither_pictures_nor_sound_is_refused(tmp_path, document):- path = tmp_path/'request.json'- path.write_text(json.dumps(document))- with pytest.raises(ValueError, match='nothing to pack'):- pack(path, tmp_path/'out')- assert not (tmp_path/'out').exists()---def version_3_bundle(tmp_path, lufs=-18., spike=None, timescale=48000, **changes):- """A sound made by processing version 3: real encodes of a synthetic tone, the file numbers that- version's loudnorm check recorded, and no PCM loudness record. 48003 frames are no whole- millisecond, so a millisecond AAC timescale cannot store them."""- t = np.arange(48003) / 48000- pcm = np.stack([np.sin(2*np.pi*440*t), np.sin(2*np.pi*440*t + .3)], axis=1)- pcm *= 10 ** ((lufs - processing.measure(pcm)['lufs']) / 20)- if spike:- pcm[24000:24048] = spike- path, request, manifest = inputs(tmp_path)- files = {}- for fmt, codec in (('ogg', ['-c:a', 'libopus', '-b:a', '160k']),- ('m4a', ['-c:a', 'aac', '-b:a', '192k', '-movflags', '+faststart',- '-movie_timescale', str(timescale)])):- file = tmp_path/'audio'/f'sound.{fmt}'- processing._ffmpeg(['-f', 'f32le', '-ar', '48000', '-ac', '2', '-i', 'pipe:0', *codec, str(file)],- pcm.astype('<f4').tobytes())- files[fmt] = {'path':file.name, 'duration_seconds':1.02, 'lufs':-18.6, 'true_peak_dbfs':-2,- 'encode_passes':1, 'pcm_peak_limit_dbtp':-2,- 'sha256':hashlib.sha256(file.read_bytes()).hexdigest()}- manifest['playback']['end_frame'], manifest['duration_seconds'] = 48003, 48003/48000- manifest.update(files=files, recipe={'processing_version':3},- normalization={'method':'loudnorm-two-pass', 'peak_limit_dbtp':-2, 'gain_limiter_passes':0})- for key, value in changes.items():- manifest[key] = {**manifest[key], **value} if isinstance(value, dict) else value- request['audio'] = [{'id':'hit','source':'audio/sound.json'}]- path.write_text(json.dumps(request))- (tmp_path/'audio'/'sound.json').write_text(json.dumps(manifest))- return path---def test_a_version_3_sound_is_packed_by_the_target_it_was_made_for(tmp_path):- result = pack(version_3_bundle(tmp_path), tmp_path/'pack')- for file in result['audio']['hit']['files'].values():- # its files are measured again over their frames, not taken from its loudnorm-era numbers- assert abs(file['lufs'] + 18) <= .3 and file['lufs'] != -18.6- assert -20 < file['true_peak_dbfs'] <= -1---# A processing_version that is neither 3 nor 4 is refused before any version 3 measuring;-# test_broken_audio_cannot_publish_a_partial_pack[recipe2] and [norecipe] own that.[email protected]('defect', ['quiet', 'peak-limited', 'hot', 'timescale'])-def test_a_version_3_sound_that_misses_its_rule_is_refused(tmp_path, defect):- path = version_3_bundle(- tmp_path, lufs=-21.5 if defect in ('quiet', 'peak-limited') else -18.,- spike=.94 if defect == 'hot' else None, # -0.5 dBTP while its manifest says -2- timescale=1000 if defect == 'timescale' else 48000, # the millisecond AAC duration of version 2- **({'normalization':{'pcm_lufs':-21.5, 'pcm_true_peak_dbtp':-2}} if defect == 'peak-limited' else {}))- with pytest.raises(ValueError, match={'quiet':'does not match', 'peak-limited':'does not match',- 'hot':'does not match', 'timescale':'container duration'}[defect]):- pack(path, tmp_path/'bad')- assert not (tmp_path/'bad').exists()diff --git a/tests/compose/test_game_pack_v2.py b/tests/compose/test_game_pack_v2.pydeleted file mode 100644index 9d2cdb0..0000000--- a/tests/compose/test_game_pack_v2.py+++ /dev/null@@ -1,414 +0,0 @@-# SPDX-License-Identifier: Apache-2.0-"""Pack contract version 2 (docs/game-pack.md "Version 2"): images, tiles and ui sections.--The manifest is checked field by field against the contract, with exact key sets, so a-consumer never meets a field the doc does not define. A version 1 request keeps its bytes:-the manifest text and every page's pixels are frozen below from the packer before version 2.-"""-import hashlib-import json-import math--import numpy as np-import pytest-from PIL import Image, ImageDraw--from sprite_gen.compose import game_pack-from sprite_gen.frames import ui_kit-from sprite_gen.frames.ui_kit import measure_insets-from sprite_gen.util.resample import resize_cell---def write_json(path, data):- path.write_text(json.dumps(data), encoding="utf-8")- return path---def prop(path, size=(40, 60)):- """A tall prop on a transparent canvas: a pole over a wide base slab, so the base differs from the bbox."""- image = Image.new("RGBA", size, (0, 0, 0, 0))- draw = ImageDraw.Draw(image)- draw.rectangle((16, 4, 23, 49), fill=(90, 120, 200, 255))- draw.rectangle((6, 50, 33, 57), fill=(120, 110, 90, 255))- image.save(path)- return image---def tile(path, size=(24, 16)):- image = Image.new("RGBA", size)- image.putdata([((x * 37) % 256, (y * 53) % 256, (x * y) % 256, 255) for y in range(size[1]) for x in range(size[0])])- image.save(path)- return image---def element(path, size, color):- image = Image.new("RGBA", size, (0, 0, 0, 0))- draw = ImageDraw.Draw(image)- draw.rectangle((0, 0, size[0] - 1, size[1] - 1), outline=color, width=3)- draw.rectangle((3, 3, size[0] - 4, size[1] - 4), fill=(20, 30, 50, 200))- image.save(path)- return image---UI_ELEMENTS = {- "panel": ((40, 30), "xy", {"left": 7, "right": 5, "top": 6, "bottom": 3}, {"left": 4, "right": 4, "top": 4, "bottom": 5}),- "hp_bar_frame": ((48, 12), "x", {"left": 9, "right": 5, "top": 0, "bottom": 0}, {"left": 10, "right": 6, "top": 3, "bottom": 3}),- "timer_badge": ((16, 16), "none", {"left": 0, "right": 0, "top": 0, "bottom": 0}, {"left": 5, "right": 5, "top": 5, "bottom": 5}),-}---def ui_kit_report(directory):- directory.mkdir()- elements, images = {}, {}- for index, (name, (size, stretch, insets, padding)) in enumerate(UI_ELEMENTS.items()):- images[name] = element(directory / f"{name}.png", size, (200, 40 * index, 90, 255))- elements[name] = {"file": f"{name}.png", "box": {"x": 0, "y": 0, "w": 64, "h": 64},- "rect": {"x": 1, "y": 1, "w": size[0], "h": size[1]},- "size": {"w": size[0], "h": size[1]}, "stretch": stretch,- "insets": insets, "padding": padding, "parts": 1}- write_json(directory / "ui-kit.json", {- "kind": "sprite-gen-ui-kit", "version": 1, "sheet": "/unused/sheet.png", "sheet_size": [256, 256],- "status": "pass", "review_reasons": [], "alpha_cleanup": None, "dropped_parts": 0, "unassigned": [],- "elements": elements,- })- return images---def scene_request(tmp_path, **override):- prop(tmp_path / "pillar.png")- prop(tmp_path / "stone.png", size=(30, 20))- tile(tmp_path / "ground.png")- Image.new("RGBA", (10, 10), (250, 200, 40, 255)).save(tmp_path / "sword.png")- ui_kit_report(tmp_path / "ui")- document = {- "version": 2,- "assets": [{"id": "coin", "source": "sword.png", "display": {"height": 5}}],- "images": [- {"id": "pillar", "source": "pillar.png", "display": {"height": 30}, "footprint": "base"},- {"id": "stone", "source": "stone.png", "display": {"width": 15}, "anchor": [10, 18],- "footprint": {"x": 3, "y": 11, "w": 9, "h": 5}},- {"id": "plain", "source": "stone.png", "display": {"width": 30}},- ],- "tiles": [{"id": "ground", "source": "ground.png", "display": {"width": 12}}],- "ui": {"kit": "ui/ui-kit.json", "scale": 0.5,- "icons": [{"id": "sword", "source": "sword.png", "display": {"height": 20}, "resample": "nearest"}]},- }- document.update(override)- return write_json(tmp_path / "game.json", document)---def atlas_frames(result):- return {name: (page, record) for page in result["textures"] for name, record in page["frames"].items()}---def crop(out, result, name):- page, record = atlas_frames(result)[name]- rect = record["frame"]- with Image.open(out / page["image"]) as image:- return image.crop((rect["x"], rect["y"], rect["x"] + rect["w"], rect["y"] + rect["h"])), record---def all_ints(value):- if isinstance(value, dict):- return all(all_ints(v) for v in value.values())- if isinstance(value, list):- return all(all_ints(v) for v in value)- return type(value) is int---def test_the_sides_of_a_nine_slice_are_the_ui_kit_s():- assert game_pack.SIDES is ui_kit.SIDES---def test_version_2_manifest_has_exactly_the_documented_sections(tmp_path):- out = tmp_path / "out"- result = game_pack.pack(scene_request(tmp_path), out)- assert json.loads((out / "game-pack.json").read_text()) == result- assert result["version"] == 2- assert set(result) == {"kind", "version", "textures", "animations", "images", "tiles", "ui"}- assert set(result["ui"]) == {"nine_slice", "icons"}- assert list(result["images"]) == sorted(result["images"]) == ["pillar", "plain", "stone"]- assert "coin" in result["animations"]---def test_images_are_atlas_frames_with_anchor_and_footprint_in_stored_pixels(tmp_path):- out = tmp_path / "out"- result = game_pack.pack(scene_request(tmp_path), out)- pillar, stone, plain = (result["images"][key] for key in ("pillar", "stone", "plain"))- for entry in (pillar, stone, plain):- assert set(entry) == {"frame", "size", "anchor", "footprint"}- # height 30 from 60: scale 0.5, a 20 x 30 frame; default anchor is the bottom centre- assert pillar["frame"] == "image/pillar"- assert pillar["size"] == {"w": 20, "h": 30}- assert pillar["anchor"] == [10, 30]- # base: opaque bbox rows 4..57 (54 rows), lowest fifth = ceil(54 / 5) = 11 rows (47..57); opaque there:- # the pole x 16..23 for rows 47..49 and the slab x 6..33 rows 50..57 -> x 6..33, y 47..57 in source pixels,- # scaled outward: x 3..17 (floor 3, ceil 17), y 23..29 (floor 23.5 -> 23, ceil 29) -> {3, 23, 14, 6}- assert pillar["footprint"] == {"x": 3, "y": 23, "w": 14, "h": 6}- # width 15 from 30: scale 0.5; anchor [10, 18] -> [5, 9]; footprint x 3..12, y 11..16 -> 1..6, 5..8- assert stone["size"] == {"w": 15, "h": 10}- assert stone["anchor"] == [5, 9]- assert stone["footprint"] == {"x": 1, "y": 5, "w": 5, "h": 3}- assert plain["footprint"] is None- image, record = crop(out, result, "image/pillar")- assert image.size == (20, 30)- with Image.open(tmp_path / "pillar.png") as source:- assert image.tobytes() == resize_cell(source.convert("RGBA"), (20, 30)).tobytes()- assert record["pivot"] == {"x": 0.5, "y": 1.0}- assert record["trimmed"] is False and record["rotated"] is False- _, record = crop(out, result, "image/stone")- assert record["pivot"] == {"x": 5 / 15, "y": 9 / 10}- assert all_ints([[entry["size"], entry["footprint"] or {}] for entry in result["images"].values()])---def test_tiles_are_separate_files_with_stored_and_display_sizes(tmp_path):- out = tmp_path / "out"- result = game_pack.pack(scene_request(tmp_path), out)- ground = result["tiles"]["ground"]- assert ground == {"image": "tile-ground.png", "webp": "tile-ground.webp",- "size": {"w": 24, "h": 16}, "display_size": {"w": 12, "h": 8}}- assert "tile-ground" not in json.dumps(result["textures"])- with Image.open(tmp_path / "ground.png") as source, Image.open(out / ground["image"]) as png, \- Image.open(out / ground["webp"]) as webp:- assert png.format == "PNG" and webp.format == "WEBP"- pixels = source.convert("RGBA").tobytes()- assert png.convert("RGBA").tobytes() == pixels- assert webp.convert("RGBA").tobytes() == pixels---def test_ui_nine_slice_insets_and_padding_are_in_stored_frame_pixels(tmp_path):- out = tmp_path / "out"- result = game_pack.pack(scene_request(tmp_path), out)- nine = result["ui"]["nine_slice"]- assert list(nine) == sorted(UI_ELEMENTS)- for name, (size, stretch, insets, padding) in UI_ELEMENTS.items():- entry = nine[name]- assert set(entry) == {"frame", "size", "stretch", "insets", "padding"}- assert entry["frame"] == f"ui/{name}"- stored = (round(size[0] * 0.5), round(size[1] * 0.5))- assert entry["size"] == {"w": stored[0], "h": stored[1]}- assert entry["stretch"] == stretch- image, record = crop(out, result, entry["frame"])- with Image.open(tmp_path / "ui" / f"{name}.png") as source:- assert image.tobytes() == resize_cell(source.convert("RGBA"), stored).tobytes()- # scaled and rounded up, or what the ui-kit measure finds on the stored pixels if that is larger:- # an ornament and its resampled fringe stay inside the fixed slices; content only shrinks- measured, _ = measure_insets(image, stretch)- assert entry["insets"] == {side: max(math.ceil(value * 0.5), measured[side]) for side, value in insets.items()}- assert all(entry["insets"][side] >= math.ceil(value * 0.5) for side, value in insets.items())- assert entry["padding"] == {side: math.ceil(value * 0.5) for side, value in padding.items()}- assert set(entry["insets"]) == set(entry["padding"]) == {"left", "right", "top", "bottom"}- assert record["pivot"] == {"x": 0.5, "y": 0.5}- assert nine["hp_bar_frame"]["insets"]["top"] == nine["hp_bar_frame"]["insets"]["bottom"] == 0- assert set(nine["timer_badge"]["insets"].values()) == {0}- assert all_ints({name: {k: v for k, v in entry.items() if k not in ("frame", "stretch")} for name, entry in nine.items()})---def test_ui_icons_are_fixed_atlas_frames(tmp_path):- out = tmp_path / "out"- result = game_pack.pack(scene_request(tmp_path), out)- assert result["ui"]["icons"] == {"sword": {"frame": "icon/sword", "size": {"w": 20, "h": 20}}}- image, record = crop(out, result, "icon/sword")- assert image.getpixel((7, 7)) == (250, 200, 40, 255)- assert record["pivot"] == {"x": 0.5, "y": 0.5}---def test_version_2_sections_default_to_empty_and_a_tile_only_pack_has_no_atlas(tmp_path):- tile(tmp_path / "ground.png")- request = write_json(tmp_path / "game.json", {- "version": 2, "tiles": [{"id": "ground", "source": "ground.png", "display": {"height": 32}}]})- out = tmp_path / "out"- result = game_pack.pack(request, out)- assert result["textures"] == [] and result["animations"] == {} and result["images"] == {}- assert result["ui"] == {"nine_slice": {}, "icons": {}}- assert result["tiles"]["ground"]["display_size"] == {"w": 48, "h": 32}- assert sorted(p.name for p in out.iterdir()) == ["game-pack.json", "tile-ground.png", "tile-ground.webp"]---def test_version_2_output_is_deterministic(tmp_path):- request = scene_request(tmp_path)- game_pack.pack(request, tmp_path / "a")- game_pack.pack(request, tmp_path / "b")- read = lambda d: {p.name: p.read_bytes() for p in d.iterdir()}- assert read(tmp_path / "a") == read(tmp_path / "b")- assert str(tmp_path) not in (tmp_path / "a" / "game-pack.json").read_text()--[email protected]("change,message", [- ({"version": 3}, "version must be 1 or 2"),- ({"images": [{"id": "pillar", "source": "pillar.png", "display": {"body_height": 30}}]}, "width or height"),- ({"images": [{"id": "a", "source": "pillar.png", "display": {"height": 9}},- {"id": "a", "source": "stone.png", "display": {"height": 9}}]}, "duplicate"),- ({"images": [{"id": "pillar", "source": "pillar.png", "display": {"height": 9}, "footprint": "top"}]}, "footprint"),- ({"images": [{"id": "pillar", "source": "pillar.png", "display": {"height": 9},- "footprint": {"x": 0, "y": 0, "w": 0, "h": 4}}]}, "footprint"),- ({"tiles": [{"id": "ground", "source": "ground.png", "display": {"width": 12, "height": 8}}]}, "width or height"),- ({"ui": {"kit": "ui/ui-kit.json", "scale": 0}}, "scale"),- ({"ui": {"kit": "ui/ui-kit.json", "scale": 0.5, "extra": 1}}, "unknown ui key"),- ({"ui": {"kit": "ui/ui-kit.json", "scale": 0.05}}, "inset"),-])-def test_bad_version_2_requests_are_refused(tmp_path, change, message):- request = scene_request(tmp_path, **change)- with pytest.raises(ValueError, match=message):- game_pack.pack(request, tmp_path / "out")- assert not (tmp_path / "out").exists()---def test_an_image_needs_exactly_one_frame(tmp_path):- strip = Image.new("RGBA", (8, 4), (255, 0, 0, 255))- strip.save(tmp_path / "two.png")- write_json(tmp_path / "two.json", {"frames": 2, "w": 4, "h": 4, "delay_ms": 100})- request = write_json(tmp_path / "game.json", {- "version": 2, "images": [{"id": "two", "source": "two.json", "display": {"height": 4}}]})- with pytest.raises(ValueError, match="one frame"):- game_pack.pack(request, tmp_path / "out")---def test_a_ui_kit_report_must_be_a_ui_kit_report(tmp_path):- request = scene_request(tmp_path)- report = json.loads((tmp_path / "ui" / "ui-kit.json").read_text())- report["elements"]["panel"]["stretch"] = "y"- write_json(tmp_path / "ui" / "ui-kit.json", report)- with pytest.raises(ValueError, match="stretch"):- game_pack.pack(request, tmp_path / "out")- report["elements"]["panel"]["stretch"] = "xy"- report["kind"] = "sprite-gen-game-pack"- write_json(tmp_path / "ui" / "ui-kit.json", report)- with pytest.raises(ValueError, match="ui-kit"):- game_pack.pack(request, tmp_path / "out")---def fill_strip(path, size, cap):- """A bar fill: a green strip with a lighter end cap at each end."""- image = Image.new("RGBA", size, (40, 180, 90, 255))- draw = ImageDraw.Draw(image)- draw.rectangle((0, 0, cap - 1, size[1] - 1), fill=(200, 250, 210, 255))- draw.rectangle((size[0] - cap, 0, size[0] - 1, size[1] - 1), fill=(200, 250, 210, 255))- image.save(path)- return image---def fill_kit(tmp_path, *, scale=1, inside="hp_bar_frame", stretch="x", cap=3, size=(40, 8)):- """A report with a bar frame (content area 32 x 6 at scale 1) and a fill drawn inside it."""- ui_kit_report(tmp_path / "ui")- report = json.loads((tmp_path / "ui" / "ui-kit.json").read_text())- fill_strip(tmp_path / "ui" / "hp_bar_fill.png", size, cap)- record = {"file": "hp_bar_fill.png", "box": {"x": 0, "y": 0, "w": 64, "h": 16},- "rect": {"x": 1, "y": 1, "w": size[0], "h": size[1]}, "size": {"w": size[0], "h": size[1]},- "stretch": stretch, "insets": {"left": cap + 2, "right": cap + 2, "top": 0, "bottom": 0},- "padding": {"left": 0, "right": 0, "top": 0, "bottom": 0}, "parts": 1}- if inside is not None:- record["inside"] = {"element": inside, "rect": {"x": 10, "y": 3, "w": 32, "h": 6}, "scale": 0.75}- report["elements"]["hp_bar_fill"] = record- write_json(tmp_path / "ui" / "ui-kit.json", report)- return write_json(tmp_path / "game.json", {"version": 2, "ui": {"kit": "ui/ui-kit.json", "scale": scale}})--[email protected]("scale", [1, 0.5, 2])-def test_a_fill_is_stored_at_its_frames_content_area(tmp_path, scale):- out = tmp_path / "out"- result = game_pack.pack(fill_kit(tmp_path, scale=scale), out)- nine = result["ui"]["nine_slice"]- frame, fill = nine["hp_bar_frame"], nine["hp_bar_fill"]- # the frame is packed as before; the fill's content rectangle is the frame's, in the frame's stored pixels- assert set(frame) == {"frame", "size", "stretch", "insets", "padding"}- pad = frame["padding"]- rect = {"x": pad["left"], "y": pad["top"], "w": frame["size"]["w"] - pad["left"] - pad["right"],- "h": frame["size"]["h"] - pad["top"] - pad["bottom"]}- assert set(fill) == {"frame", "size", "stretch", "insets", "padding", "inside"}- assert fill["frame"] == "ui/hp_bar_fill" and fill["stretch"] == "x"- assert fill["inside"] == {"element": "hp_bar_frame", "rect": rect}- assert fill["size"] == {"w": rect["w"], "h": rect["h"]}- assert fill["padding"] == {"left": 0, "right": 0, "top": 0, "bottom": 0}- # its ends are the fill's own, resized by the one factor that makes it as tall as the content area- factor = rect["h"] / 8- resized = resize_cell(Image.open(tmp_path / "ui" / "hp_bar_fill.png").convert("RGBA"),- (round(40 * factor), rect["h"]))- measured, _ = measure_insets(resized, "x")- insets = {side: max(math.ceil(value * factor), measured[side])- for side, value in {"left": 5, "right": 5, "top": 0, "bottom": 0}.items()}- assert fill["insets"] == insets- image, record = crop(out, result, "ui/hp_bar_fill")- assert image.size == (rect["w"], rect["h"]) and record["pivot"] == {"x": 0.5, "y": 0.5}- left, right = insets["left"], insets["right"]- stored, source = np.asarray(image), np.asarray(resized)- assert np.array_equal(stored[:, :left], source[:, :left])- assert np.array_equal(stored[:, rect["w"] - right:], source[:, resized.width - right:])- # the middle is the fill's own middle columns, repeated or dropped, never blended- middle = {tuple(map(tuple, source[:, x])) for x in range(left, resized.width - right)}- assert all(tuple(map(tuple, stored[:, x])) in middle for x in range(left, rect["w"] - right))--[email protected]("change,message", [- ({"inside": "mana_bar_frame"}, "hp_bar_fill: inside names mana_bar_frame, which is not a frame of this report"),- ({"inside": "hp_bar_fill"}, "hp_bar_fill: inside names hp_bar_fill, which is not a frame of this report"),- ({"stretch": "xy"}, "hp_bar_fill: a fill stretches in width only"),- # 4 px tall: scaled 1.5x to the 6 px content area, its 11 px ends are 17 px each, 34 of the 32 px it has- ({"cap": 9, "size": (40, 4)}, "hp_bar_fill: scaled to the height of hp_bar_frame's content area, its fixed ends"),-])-def test_bad_fills_are_refused(tmp_path, change, message):- request = fill_kit(tmp_path, **change)- with pytest.raises(ValueError, match=message):- game_pack.pack(request, tmp_path / "out")- assert not (tmp_path / "out").exists()---def test_a_fill_must_name_its_frame(tmp_path):- request = fill_kit(tmp_path)- report = json.loads((tmp_path / "ui" / "ui-kit.json").read_text())- report["elements"]["hp_bar_fill"]["inside"] = {"rect": {"x": 10, "y": 3, "w": 32, "h": 6}}- write_json(tmp_path / "ui" / "ui-kit.json", report)- with pytest.raises(ValueError, match="hp_bar_fill: inside must name the element"):- game_pack.pack(request, tmp_path / "out")---def test_version_1_refuses_the_version_2_sections(tmp_path):- tile(tmp_path / "ground.png")- for section, value in (("images", []), ("tiles", []), ("ui", {})):- request = write_json(tmp_path / "game.json", {- "version": 1, "assets": [{"id": "g", "source": "ground.png", "display": {"height": 4}}], section: value})- with pytest.raises(ValueError, match="version 2"):- game_pack.pack(request, tmp_path / "out")---def test_output_directory_must_not_hold_a_ui_kit_element(tmp_path):- request = scene_request(tmp_path)- with pytest.raises(ValueError, match="source"):- game_pack.pack(request, tmp_path / "ui")---# A version 1 request, packed by the packer before version 2 existed (sprite-gen 2.44.0): the manifest's-# exact bytes and each page's decoded pixels. Encoded PNG/WebP bytes depend on the zlib/libwebp build, so-# the pages are compared as pixels; everything the packer itself decides is frozen.-V1_MANIFEST_SHA256 = "f0c5d43dcb92d7717de82c7e284a1070dcda3493d80ad8e1e720d053141113de"-V1_PAGE_PIXELS_SHA256 = ["36a1d358264c2b7c155fe07dac88b9b7d0f6c3d403eea86739cb59bfd6e811fa"]---def v1_request(tmp_path):- strip = Image.new("RGBA", (36, 20))- for index, color in enumerate(((255, 0, 0, 255), (0, 128, 0, 200), (0, 0, 255, 90))):- strip.paste(Image.new("RGBA", (12, 20), color), (index * 12, 0))- strip.save(tmp_path / "walk.strip.png")- write_json(tmp_path / "walk.strip.json", {"frames": 3, "w": 12, "h": 20, "delay_ms": 80, "body_h": 16,- "anchor": [4, 18], "events": [{"frame": 1, "name": "impact"}]})- prop(tmp_path / "pillar.png")- return write_json(tmp_path / "game.json", {"version": 1, "assets": [- {"id": "walk", "source": "walk.strip.json", "display": {"body_height": 8}},- {"id": "pillar", "source": "pillar.png", "display": {"height": 30}},- {"id": "pixel", "source": "pillar.png", "display": {"height": 12}, "resample": "nearest"},- ]})---def test_version_1_request_keeps_its_manifest_bytes_and_page_pixels(tmp_path):- out = tmp_path / "out"- game_pack.pack(v1_request(tmp_path), out)- manifest = (out / "game-pack.json").read_bytes()- assert hashlib.sha256(manifest).hexdigest() == V1_MANIFEST_SHA256- result = json.loads(manifest)- assert result["version"] == 1 and set(result) == {"kind", "version", "textures", "animations"}- pages = []- for page in result["textures"]:- with Image.open(out / page["image"]) as image:- pages.append(hashlib.sha256(image.convert("RGBA").tobytes()).hexdigest())- assert pages == V1_PAGE_PIXELS_SHA256- assert sorted(p.name for p in out.iterdir()) == ["atlas-000.png", "atlas-000.webp", "game-pack.json"]diff --git a/tests/frames/test_slice_sheet_scale.py b/tests/frames/test_slice_sheet_scale.pyindex 6f4edff..95e78e2 100644--- a/tests/frames/test_slice_sheet_scale.py+++ b/tests/frames/test_slice_sheet_scale.py@@ -13,7 +13,6 @@ import pytestfrom PIL import Imagefrom sprite_gen import cli-from sprite_gen.compose import game_packfrom sprite_gen.frames import slice_sheet as slice_modulefrom sprite_gen.frames.slice_sheet import slice_sheet@@ -132,36 +131,6 @@ def test_sheet_scale_with_contain_takes_the_one_factor_every_cut_fits(tmp_path):assert abs(anchor_y - y1) <= 1 and abs(anchor_x - (x0 + x1) / 2) <= 1, path.name-def test_game_pack_images_keep_the_sliced_sizes_and_stand_on_the_reported_anchor(tmp_path):- boxes = [(30, 60), (30, 30), (80, 20)]- sheet = transparent_sheet(tmp_path / "props.png", boxes)- written = slice_sheet(sheet, tmp_path / "cells", None, grid=(3, 1), names=["post", "crate", "bench"],- prefix="prop_", canvas=(128, 96), baseline_y=92.0, target_height=84.0,- scale="sheet", fit="contain")- data = report(tmp_path / "cells", "prop_")- request = {"version": 2, "images": [- {"id": cell["name"], "source": f"cells/{cell['file']}", "display": {"height": 48},- "anchor": cell["anchor"], "footprint": "base"} for cell in data["cells"]]}- (tmp_path / "game.json").write_text(json.dumps(request), encoding="utf-8")- result = game_pack.pack(tmp_path / "game.json", tmp_path / "pack")- frames = {name: (page, record) for page in result["textures"] for name, record in page["frames"].items()}- for cell, (_w, h), path in zip(data["cells"], boxes, written):- entry = result["images"][cell["name"]]- # one canvas for every cell, so one display height scales them all by the same amount- assert entry["size"] == {"w": 64, "h": 48}- assert entry["anchor"] == pytest.approx([v * 0.5 for v in cell["anchor"]])- page, record = frames[entry["frame"]]- rect = record["frame"]- with Image.open(tmp_path / "pack" / page["image"]) as atlas:- frame = atlas.crop((rect["x"], rect["y"], rect["x"] + rect["w"], rect["y"] + rect["h"])).convert("RGBA")- x0, y0, x1, y1 = opaque_box(frame)- assert abs((y1 - y0) - h * data["factor"] * 0.5) <= 1, cell["name"]- anchor_x, anchor_y = entry["anchor"]- assert abs(anchor_y - y1) <= 1 and abs(anchor_x - (x0 + x1) / 2) <= 1, cell["name"]- footprint = entry["footprint"]- assert abs(footprint["y"] + footprint["h"] - anchor_y) <= 1, cell["name"]--def test_cli_and_the_script_take_scale_and_fit(tmp_path):sheet = chroma_sheet(tmp_path / "props.png", [(30, 80), (30, 20), (90, 30)])flags = ["--sheet", str(sheet), "--chroma-key", "magenta", "--grid", "3x1", "--prefix", "prop_",diff --git a/tests/frames/test_ui_kit.py b/tests/frames/test_ui_kit.pydeleted file mode 100644index 723da05..0000000--- a/tests/frames/test_ui_kit.py+++ /dev/null@@ -1,1707 +0,0 @@-# SPDX-License-Identifier: Apache-2.0-"""`ui-kit`: a transparent sheet drawn on the fixed layout becomes nine-slice elements.--The sheet is synthetic and drawn into the layout's own boxes: frames with known corner-ornaments (one with a long thin flourish along its top edge), a bar frame with an end gem-taller than the bar, a round badge, light colour noise, a faint haze ring around every-element and loose specks. Insets are checked to the pixel: every ornament column and row-lies inside a fixed slice, and nothing more than the 2 px margin does.--A tall (2:3) sheet holds the same seven frames at the same places and, in the band below them,-two bar fills with end caps of their own colour and a top-to-bottom shade, a slot and a counter-plate with corner ornaments, two pips and a joystick base and knob drawn as discs. A fill fits-its bar frame's content area exactly, in the report and in the pack; round parts never stretch.-A square sheet's report, element pixels and packs are frozen from the splitter before the tall-sheet existed.--The seven frames are the kit: an empty frame box refuses the sheet. The band's elements are-optional: an empty band box leaves that element out of the report and the pack and names it under-`missing`. The cut reads the drawing once, exactly: the reading that keeps the parts clearest of-their boxes' edges under any drift it considers, cut when no other reading comes within 1 px of-it. A sheet drawn a few percent shorter than the guide, so that the lower elements' centres lie in-the boxes above theirs, is read under its drift. With any set of band elements left out, under any-drift within the accepted range (along each axis a scale within a tenth of 1 and an offset within-96 px at 1024), exactly the elements not drawn are named missing and every drawn one is cut as-itself, never a neighbour under its name; an element drawn in the gap between two boxes, or a-drawing that drifted further, refuses the sheet with its own reason. So does a drawing that fits-the layout as well under two drifts that read it differently (small frames that lie inside their-boxes either way, and one dot on either pip's centre), while one that fits one drift clearly-better is named by it. A sheet whose every part lies inside its box under an accepted drift (small-drawings anywhere inside their boxes, or full-size frames with small band drawings) is cut-exactly as drawn, or refused as fitting the layout two ways, with two readings this file checks-by its own evaluation of the reading; and no drift sampled at random reads a drawing better than-the least cost the cut found, nor reads a cut sheet otherwise as well.--A kit is written whole into a new or empty directory: one that holds anything is refused and left as-it was. The kit is published at one step, the rename that gives it the out-dir's name or, with the-report outside, the link that gives the report its name. A failure or a kill just before or just-after any filesystem step of the publish leaves nothing before that step and the whole kit from it on;-an interrupt of any kind at any line or instruction of the publish leaves nothing or the whole kit;-and a run that another run's kit or report reaches first takes its own back out.-"""--import contextlib-import copy-import errno-import hashlib-import io-import json-import math-import os-import re-import shutil-import signal-import sys-from collections import Counter-from pathlib import Path--import numpy as np-import pytest-from PIL import Image--from sprite_gen import cli-from sprite_gen.compose import game_pack-from sprite_gen.frames import ui_kit-from sprite_gen.util.resample import resize_cell--SIZE = 512-TALL = (SIZE, SIZE * 3 // 2)-BORDER = (200, 200, 220, 255)-ORNAMENT = (120, 220, 200, 255)-FLOURISH = (255, 180, 60, 255)-INTERIOR = (20, 30, 60, 210)-TRACK = (10, 10, 20, 180)-GEM = (220, 40, 80, 255)-FILL = (60, 200, 120, 255)-FILL_CAP = (200, 255, 220, 255)-PIP_ON = (255, 220, 90, 255)-PIP_OFF = (70, 60, 50, 255)-KNOB = (180, 190, 210, 255)---def slow_but(values, fast):- """``values`` for a parametrize: those ``fast`` takes stay in the fast bundle, the rest are marked slow and run by- `pytest --full` — the same property read on more samples, or the same sweep at more places."""- return [value if fast(value) else pytest.param(value, marks=pytest.mark.slow) for value in values]---def fill(pixels, x0, y0, x1, y1, color):- pixels[y0:y1, x0:x1] = color---def draw_frame(pixels, x, y, w, h, k, flourish=0):- fill(pixels, x, y, x + w, y + h, BORDER)- fill(pixels, x + 3, y + 3, x + w - 3, y + h - 3, INTERIOR)- for cx, cy in ((x, y), (x + w - k, y), (x, y + h - k), (x + w - k, y + h - k)):- fill(pixels, cx, cy, cx + k, cy + k, ORNAMENT)- if flourish:- fill(pixels, x + k, y + 4, x + k + flourish, y + 6, FLOURISH)---def draw_bar(pixels, x, y, w, h, radius, cap):- fill(pixels, x + radius, y + 6, x + w, y + h - 6, BORDER)- fill(pixels, x + radius, y + 9, x + w - 3, y + h - 9, TRACK)- fill(pixels, x + w - cap, y + 2, x + w, y + h - 2, ORNAMENT)- yy, xx = np.indices((h, 2 * radius))- disc = np.hypot(xx - radius + 0.5, yy - h / 2 + 0.5) <= radius- region = pixels[y:y + h, x:x + 2 * radius]- region[disc] = GEM---def draw_badge(pixels, x, y, d):- yy, xx = np.indices((d, d))- r = np.hypot(xx - d / 2 + 0.5, yy - d / 2 + 0.5)- region = pixels[y:y + d, x:x + d]- region[r <= d / 2] = BORDER- region[r <= d / 2 - 3] = INTERIOR---def draw_fill(pixels, x, y, w, h, cap):- """A bar fill: one colour along its length, shaded from top to bottom, with an end cap of its own colour."""- shade = np.linspace(1.0, 0.6, h)[:, None]- region = pixels[y:y + h, x:x + w]- region[..., 3] = 255- for channel in range(3):- region[..., channel] = (FILL[channel] * shade).round().astype(np.uint8)- fill(pixels, x, y, x + cap, y + h, FILL_CAP)- fill(pixels, x + w - cap, y, x + w, y + h, FILL_CAP)---def draw_disc(pixels, x, y, d, color, ring=0):- yy, xx = np.indices((d, d))- r = np.hypot(xx - d / 2 + 0.5, yy - d / 2 + 0.5)- region = pixels[y:y + d, x:x + d]- region[r <= d / 2] = BORDER if ring else color- region[r <= d / 2 - ring] = color---# element -> (offset inside its box, drawing parameters); every element sits 4 px inside its box-PLAN = {"panel": dict(k=18, flourish=60), "button": dict(k=12), "button_pressed": dict(k=12),- "card": dict(k=16), "hp_bar_frame": dict(radius=20, cap=10), "xp_bar_frame": dict(radius=20, cap=10),- "timer_badge": dict(), "hp_bar_fill": dict(cap=6), "xp_bar_fill": dict(cap=6),- "slot": dict(k=14), "badge": dict(k=10), "pip_on": dict(color=PIP_ON, ring=3),- "pip_off": dict(color=PIP_OFF, ring=3), "joystick_base": dict(color=INTERIOR, ring=6),- "joystick_knob": dict(color=KNOB)}---def synthetic_sheet(*, size=(SIZE, SIZE), haze=True, noise=True, stray=False, missing=(), crest=False,- squeeze=1.0, drift=None, nudge=None):- """The sheet, and where each element was drawn. `missing` names the boxes left empty; `squeeze` draws- the layout that much shorter, from the top edge down, as image models draw it; `drift`, a scale and an- offset along x and then along y (offsets in sheet pixels), draws every box moved that way instead; `nudge`- moves single elements off their boxes by (dx, dy) sheet pixels."""- missing = {missing} if isinstance(missing, str) else set(missing)- sx, tx, sy, ty = drift if drift is not None else (1, 0, squeeze, 0)- nudge = nudge or {}- pixels = np.zeros((size[1], size[0], 4), dtype=np.uint8)- drawn = {}- for name, (bx, by, bw, bh) in ui_kit.boxes(size).items():- if name in missing:- continue- bx, bw = round(bx * sx + tx), round(bw * sx)- by, bh = round(by * sy + ty), round(bh * sy)- dx, dy = nudge.get(name, (0, 0))- x, y, w, h = bx + 4 + dx, by + 4 + dy, bw - 8, bh - 8- params = PLAN[name]- if name.endswith("bar_frame"):- draw_bar(pixels, x, y, w, h, **params)- elif name.endswith("bar_fill"):- draw_fill(pixels, x, y, w, h, **params)- elif name == "timer_badge":- w = h = min(w, h)- draw_badge(pixels, x, y, w)- elif name.startswith(("pip_", "joystick_")):- w = h = min(w, h)- draw_disc(pixels, x, y, w, **params)- else:- draw_frame(pixels, x, y, w, h, **params)- if crest and name == "card":- fill(pixels, x + w // 2 - 6, y, x + w // 2 + 6, y + 14, FLOURISH)- drawn[name] = (x, y, w, h)- solid = pixels[..., 3] > 0- if noise:- rng = np.random.default_rng(3)- jitter = rng.integers(-4, 5, pixels[..., :3].shape)- pixels[..., :3] = np.where(solid[..., None], np.clip(pixels[..., :3].astype(int) + jitter, 0, 255), 0)- if haze:- near = np.zeros_like(solid)- for dy in range(-6, 7):- for dx in range(-6, 7):- near |= np.roll(np.roll(solid, dy, 0), dx, 1)- ring = near & ~solid- pixels[ring] = (150, 150, 170, 22)- for sx, sy in ((5, 500), (500, 5), (330, 470)):- pixels[sy, sx] = (200, 200, 200, 40)- if stray:- fill(pixels, 250, 410, 270, 430, BORDER)- return Image.fromarray(pixels), drawn---def split(**kwargs):- image, drawn = synthetic_sheet(**kwargs)- elements, report = ui_kit.split_ui_kit(image)- return image, drawn, elements, report---def offset(report, drawn, name):- rect = report["elements"][name]["rect"]- x, y, w, h = drawn[name]- return x - rect["x"], y - rect["y"], rect["x"] + rect["w"] - (x + w), rect["y"] + rect["h"] - (y + h)---FRAMES = ["panel", "button", "button_pressed", "card", "hp_bar_frame", "xp_bar_frame", "timer_badge"]-BAND = ["hp_bar_fill", "xp_bar_fill", "slot", "badge", "pip_on", "pip_off", "joystick_base", "joystick_knob"]---def test_layout_is_the_documented_table_and_scales_with_the_sheet():- assert [entry.name for entry in ui_kit.LAYOUT] == FRAMES + BAND- full = ui_kit.boxes((1024, 1024))- assert list(full) == FRAMES- assert full["panel"] == (48, 48, 576, 400)- assert full["card"] == (704, 400, 272, 576)- assert full["timer_badge"] == (48, 816, 160, 160)- assert ui_kit.boxes((512, 512))["card"] == (352, 200, 136, 288)- assert {e.name: e.stretch for e in ui_kit.LAYOUT} == {- "panel": "xy", "button": "xy", "button_pressed": "xy", "card": "xy",- "hp_bar_frame": "x", "xp_bar_frame": "x", "timer_badge": "none",- "hp_bar_fill": "x", "xp_bar_fill": "x", "slot": "xy", "badge": "xy",- "pip_on": "none", "pip_off": "none", "joystick_base": "none", "joystick_knob": "none"}- # the 2:3 sheet keeps the seven frames where the square sheet has them and adds the band below- tall = ui_kit.boxes((1024, 1536))- assert list(tall) == FRAMES + BAND- assert {name: tall[name] for name in FRAMES} == full- assert tall["hp_bar_fill"] == (48, 1024, 608, 64)- assert tall["xp_bar_fill"] == (48, 1136, 608, 64)- assert tall["slot"] == (48, 1248, 192, 192)- assert tall["badge"] == (288, 1248, 176, 112)- assert tall["pip_on"] == (512, 1248, 96, 96)- assert tall["pip_off"] == (512, 1392, 96, 96)- assert tall["joystick_base"] == (704, 1024, 272, 272)- assert tall["joystick_knob"] == (768, 1344, 144, 144)- assert ui_kit.boxes(TALL)["joystick_base"] == (352, 512, 136, 136)- # boxes never touch: 48 px apart at 1024, and 48 px in from the sheet's edges- for layout, (width, height) in ((full, (1024, 1024)), (tall, (1024, 1536))):- names = list(layout)- for i, a in enumerate(names):- ax, ay, aw, ah = layout[a]- assert ax >= 48 and ay >= 48 and ax + aw + 48 <= width and ay + ah + 48 <= height, a- for b in names[i + 1:]:- bx, by, bw, bh = layout[b]- assert ax + aw + 48 <= bx or bx + bw + 48 <= ax or ay + ah + 48 <= by or by + bh + 48 <= ay---def test_frame_insets_cover_every_corner_ornament_and_the_long_flourish():- _, drawn, elements, report = split()- assert report["status"] == "pass", report["review_reasons"]- for name in ("panel", "button", "button_pressed", "card"):- entry = report["elements"][name]- left, top, right, bottom = offset(report, drawn, name)- k = PLAN[name]["k"]- reach = k + PLAN[name].get("flourish", 0)- assert entry["stretch"] == "xy"- assert entry["insets"] == {"left": left + reach + 2, "right": right + k + 2,- "top": top + k + 2, "bottom": bottom + k + 2}, name- assert elements[name].size == (entry["size"]["w"], entry["size"]["h"])---def test_bar_insets_cover_the_gem_and_the_cap_and_padding_is_the_track():- _, drawn, elements, report = split()- for name in ("hp_bar_frame", "xp_bar_frame"):- entry = report["elements"][name]- left, top, right, bottom = offset(report, drawn, name)- radius, cap = PLAN[name]["radius"], PLAN[name]["cap"]- assert entry["stretch"] == "x"- # the cap is taller than the bar, so its kept 2 px anti-aliased edge lies left of it, inside the- # element: that edge belongs to the cap's fixed slice too- assert entry["insets"] == {"left": left + 2 * radius + 2, "right": right + cap + 2 + 2, "top": 0, "bottom": 0}- # the track: right of the gem, left of the cap, inside the border rows (9 px from the drawn top/bottom)- assert entry["padding"] == {"left": left + 2 * radius + 2, "right": right + cap + 2,- "top": top + 9 + 2, "bottom": bottom + 9 + 2}---def test_badge_does_not_stretch_and_its_content_fits_inside_the_ring():- _, drawn, elements, report = split()- entry = report["elements"]["timer_badge"]- assert entry["stretch"] == "none"- assert entry["insets"] == {"left": 0, "right": 0, "top": 0, "bottom": 0}- left, top, _, _ = offset(report, drawn, "timer_badge")- d = drawn["timer_badge"][2]- centre = (left + d / 2, top + d / 2)- pad, size = entry["padding"], entry["size"]- corners = [(pad["left"], pad["top"]), (size["w"] - pad["right"], pad["top"]),- (pad["left"], size["h"] - pad["bottom"]), (size["w"] - pad["right"], size["h"] - pad["bottom"])]- for cx, cy in corners:- assert math.hypot(cx - centre[0], cy - centre[1]) <= d / 2 - 3- inner = d / 2 - 3- assert size["w"] - pad["left"] - pad["right"] >= 1.2 * inner---def test_frame_padding_keeps_text_off_the_border_and_the_ornaments():- _, drawn, elements, report = split()- for name in ("panel", "card", "button"):- entry = report["elements"][name]- left, top, right, bottom = offset(report, drawn, name)- pad = entry["padding"]- k = PLAN[name]["k"]- for side, edge in (("left", left), ("right", right), ("top", top), ("bottom", bottom)):- assert edge + k <= pad[side] <= edge + k + 4, (name, side, pad)---def test_haze_is_cleared_before_cutting_and_reported():- _, drawn, elements, report = split()- cleanup = report["alpha_cleanup"]- assert cleanup["floor"] == 64 and cleanup["edge_px"] == 2- assert cleanup["haze_fraction_before"] > 0.01 and cleanup["haze_fraction_after"] == 0- assert cleanup["changed_solid_pixels"] == 0 and cleanup["changed_edge_pixels"] == 0- assert report["dropped_parts"] == 0- assert report["unassigned"] == []- # the element keeps at most its two-pixel anti-aliased edge of haze, never the six-pixel ring- for name in drawn:- assert all(0 <= value <= 2 for value in offset(report, drawn, name)), name---def test_ornament_reaching_the_middle_of_an_edge_is_flagged():- _, _, _, report = split(crest=True)- assert report["status"] == "needs-review"- assert any(reason.startswith("card:") and "x" in reason for reason in report["review_reasons"])---def test_a_large_part_outside_every_box_is_reported():- _, _, _, report = split(stray=True)- assert report["status"] == "needs-review"- assert report["unassigned"] == [{"rect": {"x": 250, "y": 410, "w": 20, "h": 20}, "pixels": 400}]---def test_an_empty_box_fails():- image, _ = synthetic_sheet(missing="button_pressed")- with pytest.raises(ValueError, match="^button_pressed: its box holds no element; generate the sheet again$"):- ui_kit.split_ui_kit(image)---def test_a_sheet_that_is_neither_square_nor_2_3_fails():- for size in ((512, 400), (512, 900), (768, 512)):- with pytest.raises(ValueError, match=r"square \(1:1.*2:3"):- ui_kit.split_ui_kit(Image.new("RGBA", size))---def test_cli_writes_element_pngs_and_a_report_the_pack_reads(tmp_path):- image, drawn = synthetic_sheet()- sheet = tmp_path / "uikit.png"- image.save(sheet)- before = sheet.read_bytes()- out = tmp_path / "ui"- assert ui_kit.main(["--sheet", str(sheet), "--out-dir", str(out)]) == 0- assert sheet.read_bytes() == before- report = json.loads((out / "ui-kit.json").read_text())- assert report["kind"] == "sprite-gen-ui-kit" and report["version"] == 1- assert report["sheet"] == str(sheet.resolve()) and report["sheet_size"] == [SIZE, SIZE]- assert list(report["elements"]) == FRAMES- # every element of a square sheet is required, so its report has no `missing`, as before the 2:3 sheet- assert "missing" not in report and "layout_fit" not in report- assert sorted(p.name for p in out.iterdir()) == sorted([f"{name}.png" for name in FRAMES] + ["ui-kit.json"])- cleaned, _ = ui_kit.clear_haze(image.convert("RGBA"), floor=64, edge=2)- for name, entry in report["elements"].items():- assert entry["file"] == f"{name}.png"- assert entry["box"] == dict(zip("xywh", ui_kit.boxes((SIZE, SIZE))[name]))- rect = entry["rect"]- with Image.open(out / entry["file"]) as element:- assert element.size == (entry["size"]["w"], entry["size"]["h"]) == (rect["w"], rect["h"])- crop = cleaned.crop((rect["x"], rect["y"], rect["x"] + rect["w"], rect["y"] + rect["h"]))- assert element.convert("RGBA").tobytes() == crop.tobytes()- request = tmp_path / "game.json"- request.write_text(json.dumps({"version": 2, "ui": {"kit": "ui/ui-kit.json"}}))- result = game_pack.pack(request, tmp_path / "pack")- for name, entry in report["elements"].items():- packed = result["ui"]["nine_slice"][name]- assert packed["insets"] == entry["insets"] and packed["padding"] == entry["padding"]- assert packed["size"] == entry["size"] and packed["stretch"] == entry["stretch"]---def test_cli_refuses_to_write_into_the_sheets_directory_over_the_sheet(tmp_path):- image, _ = synthetic_sheet()- sheet = tmp_path / "panel.png"- image.save(sheet)- with pytest.raises(SystemExit, match="sheet"):- ui_kit.main(["--sheet", str(sheet), "--out-dir", str(tmp_path)])---# --out-dir, --report (None: the default <out-dir>/ui-kit.json) and the `file` the report gives the-# panel: the PNG's path from the report's own directory, with "/" separators-REPORT_PLACES = [- ("ui", None, "panel.png"),- ("elements", "reports/kit.json", "../elements/panel.png"),- ("ui", "ui/reports/kit.json", "../panel.png"),- ("reports/elements", "reports/kit.json", "elements/panel.png"),-]---def test_a_report_anywhere_names_the_written_pngs_and_packs_the_same(tmp_path):- image, _ = synthetic_sheet()- sheet = tmp_path / "uikit.png"- image.save(sheet)- packs = []- for index, (out_dir, report, panel) in enumerate(REPORT_PLACES):- root = tmp_path / f"place-{index}"- args = ["ui-kit", "--sheet", str(sheet), "--out-dir", str(root / out_dir)]- if report is not None:- args += ["--report", str(root / report)]- assert cli.main(args) == 0- report_path = root / (report or f"{out_dir}/ui-kit.json")- written = json.loads(report_path.read_text())- assert written["elements"]["panel"]["file"] == panel- for name, entry in written["elements"].items():- assert (report_path.parent / entry["file"]).resolve() == (root / out_dir / f"{name}.png").resolve()- request = root / "game.json"- request.write_text(json.dumps({"version": 2, "ui": {"kit": report_path.relative_to(root).as_posix()}}))- assert cli.main(["game-pack", "--request", str(request), "--out-dir", str(root / "pack")]) == 0- packs.append({path.name: path.read_bytes() for path in (root / "pack").iterdir()})- assert len(json.loads(packs[0]["game-pack.json"])["ui"]["nine_slice"]) == len(FRAMES)- assert packs == [packs[0]] * len(REPORT_PLACES)---def test_a_report_path_that_is_not_json_is_refused_before_anything_is_written(tmp_path):- image, _ = synthetic_sheet()- sheet = tmp_path / "uikit.png"- image.save(sheet)- out = tmp_path / "ui"- # the report would replace an element PNG of the same name- with pytest.raises(SystemExit, match=r"--report must be a \.json path"):- ui_kit.main(["--sheet", str(sheet), "--out-dir", str(out), "--report", str(out / "panel.png")])- assert not out.exists()---def test_guide_draws_every_box_and_the_text_names_every_element(tmp_path):- path = tmp_path / "guide.png"- cell = ui_kit.draw_guide(path, (1024, 1024))- with Image.open(path) as guide:- guide = guide.convert("RGB")- assert guide.size == (1024, 1024)- for x, y, w, h in ui_kit.boxes((1024, 1024)).values():- assert guide.getpixel((x + w // 2, y)) == ui_kit.GUIDE_BOX- assert guide.getpixel((x, y + h // 2)) == ui_kit.GUIDE_BOX- assert guide.getpixel((x + w // 2, y + h // 2)) == ui_kit.GUIDE_BACKGROUND- assert cell == {"kind": "ui-kit", "width": 1024, "height": 1024,- "boxes": {name: dict(zip("xywh", box)) for name, box in ui_kit.boxes((1024, 1024)).items()}}- text = ui_kit.guide_text()- assert ui_kit.guide_text((1024, 1024)) == text- positions = [text.index(entry.what) for entry in ui_kit.LAYOUT[:len(FRAMES)]]- assert positions == sorted(positions)- assert "last attached image is a layout guide" in text- assert "no text" in text- assert not any(entry.what in text for entry in ui_kit.LAYOUT[len(FRAMES):])---def test_tall_guide_draws_the_square_boxes_and_the_band_and_names_every_element(tmp_path):- path = tmp_path / "guide.png"- cell = ui_kit.draw_guide(path, (683, 1024))- assert {slot.name for slot in ui_kit.LAYOUT if slot.round} == set(ROUND)- with Image.open(path) as guide:- guide = guide.convert("RGB")- assert guide.size == (683, 1024)- for name, (x, y, w, h) in ui_kit.boxes((683, 1024)).items():- assert on_guide_line(guide, (x + w // 2, y), (0, 1)) and on_guide_line(guide, (x, y + h // 2), (1, 0))- assert guide.getpixel((x + w // 2, y + h // 2)) == ui_kit.GUIDE_BACKGROUND- # a round part's place is a circle, so the corner of its box is the guide's grey, not its outline- assert (guide.getpixel((x, y)) == ui_kit.GUIDE_BACKGROUND) == (name in ROUND), name- assert cell == {"kind": "ui-kit", "width": 683, "height": 1024,- "boxes": {name: dict(zip("xywh", box)) for name, box in ui_kit.boxes((683, 1024)).items()}}- assert list(cell["boxes"]) == FRAMES + BAND- text = ui_kit.guide_text((683, 1024))- assert text == ui_kit.guide_text((1024, 1536))- positions = [text.index(entry.what) for entry in ui_kit.LAYOUT]- assert positions == sorted(positions)- assert "15 blue boxes and circles" in text and "last attached image is a layout guide" in text- assert "no text" in text and "no plate, tile or backing" in text and "no frame, rim or end pieces" in text---ROUND = ("pip_on", "pip_off", "joystick_base", "joystick_knob")---def on_guide_line(guide, point, step):- """The guide's outline passes ``point`` or one of the two pixels inward from it along ``step``."""- return any(guide.getpixel((point[0] + i * step[0], point[1] + i * step[1])) == ui_kit.GUIDE_BOX for i in range(3))---def test_a_round_part_drawn_on_a_square_plate_is_flagged():- image, drawn = synthetic_sheet(size=TALL, noise=False, haze=False)- pixels = np.asarray(image).copy()- # a square plate behind the lit dot: the box's corners around the disc are painted too- x, y, w, h = drawn["pip_on"]- plate = pixels[y:y + h, x:x + w]- plate[plate[..., 3] == 0] = BORDER- _, report = ui_kit.split_ui_kit(Image.fromarray(pixels))- assert report["status"] == "needs-review"- note = "its corners are filled: it was drawn on a square plate or backing, not as a circle; regenerate it"- assert [reason for reason in report["review_reasons"] if reason.startswith(ROUND)] == [f"pip_on: {note}"]- plated = Image.fromarray(np.ascontiguousarray(pixels[y:y + h, x:x + w]))- assert ui_kit.measure_round(plated) == [note]- assert ui_kit.measure_round(Image.fromarray(np.ascontiguousarray(np.asarray(image)[y:y + h, x:x + w]))) == []---def tall_split(**kwargs):- return split(size=TALL, **kwargs)---def test_tall_sheet_cuts_every_element_of_the_whole_kit():- _, drawn, elements, report = tall_split()- assert report["status"] == "pass", report["review_reasons"]- assert report["sheet_size"] == list(TALL)- assert list(report["elements"]) == list(elements) == FRAMES + BAND- assert report["unassigned"] == [] and report["dropped_parts"] == 0- # nothing is missing, and every box held its element, so the layout was not fitted- assert report["missing"] == [] and "layout_fit" not in report- for name in FRAMES + BAND:- entry = report["elements"][name]- assert entry["file"] == f"{name}.png" and entry["parts"] == 1- assert entry["box"] == dict(zip("xywh", ui_kit.boxes(TALL)[name]))- assert elements[name].size == (entry["size"]["w"], entry["size"]["h"])- # the cut is the drawn element and at most its kept two-pixel haze edge- assert all(0 <= value <= 2 for value in offset(report, drawn, name)), name---def test_tall_sheet_cuts_the_seven_frames_as_the_square_sheet_does():- _, _, square_elements, square = split(noise=False)- _, _, tall_elements, tall = tall_split(noise=False)- for name in FRAMES:- assert tall["elements"][name] == square["elements"][name]- assert tall_elements[name].tobytes() == square_elements[name].tobytes()---def test_fills_stretch_in_width_and_fit_the_content_area_of_their_bar_frame():- _, drawn, elements, report = tall_split()- for fill, frame in (("hp_bar_fill", "hp_bar_frame"), ("xp_bar_fill", "xp_bar_frame")):- entry, bar = report["elements"][fill], report["elements"][frame]- left, top, right, bottom = offset(report, drawn, fill)- cap = PLAN[fill]["cap"]- assert entry["stretch"] == "x"- assert entry["insets"] == {"left": left + cap + 2, "right": right + cap + 2, "top": 0, "bottom": 0}- # a fill holds no content: its padding is 0, as a frame's insets are 0 along an axis it keeps- assert entry["padding"] == {"left": 0, "right": 0, "top": 0, "bottom": 0}- pad, size = bar["padding"], bar["size"]- rect = {"x": pad["left"], "y": pad["top"], "w": size["w"] - pad["left"] - pad["right"],- "h": size["h"] - pad["top"] - pad["bottom"]}- assert entry["inside"] == {"element": frame, "rect": rect, "scale": round(rect["h"] / entry["size"]["h"], 6)}- # scaled by `scale`, the fill is as tall as the content area to the pixel and its two ends fit inside it- assert abs(entry["size"]["h"] * entry["inside"]["scale"] - rect["h"]) < 0.01- assert (entry["insets"]["left"] + entry["insets"]["right"]) * entry["inside"]["scale"] < rect["w"]- for name in FRAMES + BAND:- if name not in ("hp_bar_fill", "xp_bar_fill"):- assert "inside" not in report["elements"][name], name---def test_pips_and_joystick_parts_never_stretch_and_keep_their_round_shape():- _, drawn, elements, report = tall_split()- for name in ("pip_on", "pip_off", "joystick_base", "joystick_knob"):- entry = report["elements"][name]- assert entry["stretch"] == "none"- assert entry["insets"] == entry["padding"] == {"left": 0, "right": 0, "top": 0, "bottom": 0}- d = drawn[name][2]- assert d == drawn[name][3]- assert d <= entry["size"]["w"] <= d + 4 and d <= entry["size"]["h"] <= d + 4- assert abs(entry["size"]["w"] - entry["size"]["h"]) <= 2, name- # the two pips are drawn in boxes of one size, so one dot swaps for the other in place- assert ui_kit.boxes(TALL)["pip_on"][2:] == ui_kit.boxes(TALL)["pip_off"][2:]---def test_slot_and_badge_insets_cover_their_corner_ornaments_and_padding_keeps_content_off_them():- _, drawn, elements, report = tall_split()- for name in ("slot", "badge"):- entry = report["elements"][name]- left, top, right, bottom = offset(report, drawn, name)- k = PLAN[name]["k"]- assert entry["stretch"] == "xy"- assert entry["insets"] == {"left": left + k + 2, "right": right + k + 2,- "top": top + k + 2, "bottom": bottom + k + 2}, name- for side, edge in (("left", left), ("right", right), ("top", top), ("bottom", bottom)):- assert edge + k <= entry["padding"][side] <= edge + k + 4, (name, side, entry["padding"])---def test_the_frames_are_required_and_the_band_is_optional():- assert [slot.name for slot in ui_kit.LAYOUT if not slot.optional] == FRAMES- assert [slot.name for slot in ui_kit.LAYOUT if slot.optional] == BAND--[email protected]("missing", ["pip_off", tuple(BAND)])-def test_an_empty_box_of_the_band_leaves_that_element_out_of_the_kit(missing):- gone = [missing] if isinstance(missing, str) else list(missing)- image, drawn = synthetic_sheet(size=TALL, missing=missing)- elements, report = ui_kit.split_ui_kit(image)- kept = [name for name in FRAMES + BAND if name not in gone]- assert report["missing"] == gone- assert list(report["elements"]) == list(elements) == kept- # a missing element is not a measurement to review: the elements that are there are measured as ever- assert report["status"] == "pass", report["review_reasons"]- assert "layout_fit" not in report- for name in kept:- assert all(0 <= value <= 2 for value in offset(report, drawn, name)), name---def test_every_empty_frame_box_is_named_and_an_empty_band_box_is_not():- image, _ = synthetic_sheet(size=TALL, missing=("panel", "card", "pip_on"))- with pytest.raises(ValueError, match="^panel, card: their boxes hold no element; generate the sheet again$"):- ui_kit.split_ui_kit(image)---SQUEEZE = 0.93---def test_a_sheet_drawn_shorter_than_the_guide_is_fitted_before_its_parts_are_assigned():- # Drawn 7 % shorter from the top edge down, the lower pip's and the lower fill's centres lie in the- # widened boxes above theirs (half the gap, 12 px here): assigned by the layout's own boxes, three boxes- # would be empty (badge, pip_off, joystick_knob), two would hold two elements each, and the upper fill- # would lie in no box.- image, drawn = synthetic_sheet(size=TALL, squeeze=SQUEEZE)- boxes, reach = ui_kit.boxes(TALL), 12- for name, above in (("pip_off", "pip_on"), ("xp_bar_fill", "hp_bar_fill")):- _, y, _, h = drawn[name]- _, ay, _, ah = boxes[above]- assert ay - reach <= y + h / 2 < ay + ah + reach, name- elements, report = ui_kit.split_ui_kit(image)- assert report["missing"] == [] and report["unassigned"] == []- assert list(elements) == FRAMES + BAND- for name in FRAMES + BAND:- entry = report["elements"][name]- assert entry["parts"] == 1, name- assert all(0 <= value <= 2 for value in offset(report, drawn, name)), name- # each element's box is its layout box moved onto the drawing, and the drawn element lies inside it- x, y, w, h = drawn[name]- box = entry["box"]- assert box["x"] - 2 <= x and x + w <= box["x"] + box["w"] + 2, name- assert box["y"] - 2 <= y and y + h <= box["y"] + box["h"] + 2, name- fit = report["layout_fit"]- assert set(fit) == {"scale", "offset"}- assert abs(fit["scale"]["x"] - 1) < 0.005 and abs(fit["offset"]["x"]) < 2- assert abs(fit["scale"]["y"] - SQUEEZE) < 0.005 and abs(fit["offset"]["y"]) < 3---def test_a_squeezed_sheet_with_an_empty_band_box_is_fitted_and_names_it():- image, drawn = synthetic_sheet(size=TALL, squeeze=SQUEEZE, missing="joystick_knob")- elements, report = ui_kit.split_ui_kit(image)- assert report["missing"] == ["joystick_knob"] and "layout_fit" in report- assert list(elements) == [name for name in FRAMES + BAND if name != "joystick_knob"]- assert all(report["elements"][name]["parts"] == 1 for name in elements)--[email protected]("name", FRAMES)-def test_a_squeezed_sheet_with_an_empty_frame_box_still_refuses_it(name):- # fitting the layout to the drawing never fills an empty frame's box with a neighbour: the sheet is refused- # by that frame's own name- image, _ = synthetic_sheet(size=TALL, squeeze=SQUEEZE, missing=name)- with pytest.raises(ValueError, match=f"^{name}: its box holds no element; generate the sheet again$"):- ui_kit.split_ui_kit(image)---# The drift a cut accepts (docs/ui-kit.md "Reading the drawing"): along each axis a scale within a-# tenth of 1 and an offset within 96 px at 1024.-ACCEPTED_SCALE = (0.9, 1.1)-ACCEPTED_OFFSET = 96---def accepted_drift(rng, size=TALL):- """A drift drawn at random within the accepted range, among those that keep every box 8 px inside the sheet."""- unit = size[0] / ui_kit.REFERENCE- while True:- sx, sy = rng.uniform(*ACCEPTED_SCALE, size=2)- tx, ty = rng.uniform(-ACCEPTED_OFFSET, ACCEPTED_OFFSET, size=2) * unit- if all(8 <= x * sx + tx and (x + w) * sx + tx <= size[0] - 8 and 8 <= y * sy + ty- and (y + h) * sy + ty <= size[1] - 8 for x, y, w, h in ui_kit.boxes(size).values()):- return float(sx), float(tx), float(sy), float(ty)---def assert_cut_as_drawn(report, elements, drawn, drift):- """Exactly the band elements that were not drawn are missing, and every drawn element is cut whole as itself:- its cut is its own drawing to within its 2 px edge, so it holds no neighbour's. A fitted layout is the drift the- sheet was drawn with, to within a hundredth in scale and 4 px in offset, and puts each drawing inside its- element's fitted box."""- kept = [name for name in FRAMES + BAND if name in drawn]- assert report["missing"] == [name for name in BAND if name not in drawn]- assert list(report["elements"]) == list(elements) == kept- for name in kept:- assert report["elements"][name]["parts"] == 1, name- assert all(0 <= value <= 2 for value in offset(report, drawn, name)), (name, offset(report, drawn, name))- if "layout_fit" in report:- fit = report["layout_fit"]- for axis, scale, shift in (("x", *drift[:2]), ("y", *drift[2:])):- assert abs(fit["scale"][axis] - scale) <= 0.01 and abs(fit["offset"][axis] - shift) <= 4, (fit, drift)- for name in kept:- x, y, w, h = drawn[name]- box = report["elements"][name]["box"]- assert box["x"] - 2 <= x and x + w <= box["x"] + box["w"] + 2, name- assert box["y"] - 2 <= y and y + h <= box["y"] + box["h"] + 2, name---PROBE_MISSING = ["hp_bar_fill", "pip_off", "joystick_knob"]---def test_a_squeezed_sheet_missing_several_band_elements_names_those_and_cuts_no_neighbour_under_their_names(tmp_path):- # Drawn 6 % shorter with three band elements left out, the lower fill's centre lies in the empty upper fill's- # widened box and the lit dot's in the lower fill's: assigned by the layout's own boxes, the lower fill would be- # cut as `hp_bar_fill`, the lit dot as `xp_bar_fill`, and the lit dot named missing. The CLI, an outside report- # and the pack name exactly the elements drawn.- image, drawn = synthetic_sheet(size=TALL, squeeze=0.94, missing=PROBE_MISSING)- boxes, reach = ui_kit.boxes(TALL), 12- for name, other in (("xp_bar_fill", "hp_bar_fill"), ("pip_on", "xp_bar_fill")):- x, y, w, h = drawn[name]- ox, oy, ow, oh = boxes[other]- assert ox - reach <= x + w / 2 < ox + ow + reach and oy - reach <= y + h / 2 < oy + oh + reach, name- elements, report = ui_kit.split_ui_kit(image)- assert_cut_as_drawn(report, elements, drawn, (1, 0, 0.94, 0))- sheet = tmp_path / "source.png"- image.save(sheet)- out, report_path = tmp_path / "parts", tmp_path / "reports" / "kit.json"- assert ui_kit.main(["--sheet", str(sheet), "--out-dir", str(out), "--report", str(report_path)]) == 0- written = json.loads(report_path.read_text())- assert written["missing"] == PROBE_MISSING- kept = [name for name in FRAMES + BAND if name not in PROBE_MISSING]- assert sorted(p.stem for p in out.glob("*.png")) == sorted(kept)- request = tmp_path / "game.json"- request.write_text(json.dumps({"version": 2, "ui": {"kit": "reports/kit.json", "scale": 0.5}}))- packed = game_pack.pack(request, tmp_path / "pack")- assert sorted(packed["ui"]["nine_slice"]) == sorted(kept)--[email protected]("squeeze", [0.9, 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99])-def test_a_sheet_squeezed_from_the_top_by_any_accepted_amount_names_the_missing_band_elements(squeeze):- image, drawn = synthetic_sheet(size=TALL, squeeze=squeeze, missing=PROBE_MISSING)- elements, report = ui_kit.split_ui_kit(image)- assert_cut_as_drawn(report, elements, drawn, (1, 0, squeeze, 0))---# fast: no element left out, and each left out alone[email protected]("subset", slow_but(range(2 ** len(BAND)), lambda subset: subset & (subset - 1) == 0))-def test_every_set_of_missing_band_elements_under_a_random_accepted_drift_is_named_and_the_rest_cut_as_drawn(subset):- # Each of the 256 sets of band elements left out, on a sheet drawn under a drift picked at random (seeded by the- # set) within the accepted range: a scale and an offset along x and along y.- rng = np.random.default_rng(subset)- missing = [name for bit, name in enumerate(BAND) if subset >> bit & 1]- drift = accepted_drift(rng)- image, drawn = synthetic_sheet(size=TALL, drift=drift, missing=missing)- elements, report = ui_kit.split_ui_kit(image)- assert_cut_as_drawn(report, elements, drawn, drift)--[email protected]("name", FRAMES)-def test_an_empty_frame_box_under_a_random_accepted_drift_still_refuses_the_sheet_by_its_name(name):- rng = np.random.default_rng(FRAMES.index(name))- missing = [name] + [band for band in BAND if rng.random() < 0.5]- image, _ = synthetic_sheet(size=TALL, drift=accepted_drift(rng), missing=missing)- with pytest.raises(ValueError, match=f"^{name}: its box holds no element; generate the sheet again$"):- ui_kit.split_ui_kit(image)---def test_the_accepted_drift_is_the_documented_range():- assert (1 - ui_kit.DRIFT_SCALE, 1 + ui_kit.DRIFT_SCALE) == ACCEPTED_SCALE- assert ui_kit.DRIFT_OFFSET == ACCEPTED_OFFSET--[email protected]("nudge, name", [(30, "pip_on"), (42, "pip_off")])-def test_a_band_element_drawn_in_the_gap_between_two_boxes_refuses_the_sheet_with_its_own_reason(nudge, name):- # The lit dot drawn so far below its box that its centre lies in the gap between its box and the unlit dot's- # (left empty): either dot could be meant, so the sheet is refused, naming the box that holds it, and never cut- # under a guessed name.- image, _ = synthetic_sheet(size=TALL, missing="pip_off", nudge={"pip_on": (0, nudge)})- refusal = f"^{name}: its box holds a part centred outside it .*; generate the sheet again$"- with pytest.raises(ValueError, match=refusal):- ui_kit.split_ui_kit(image)---def test_a_sheet_drawn_further_off_its_guide_than_a_cut_accepts_is_refused_with_its_own_reason():- image, _ = synthetic_sheet(size=TALL, squeeze=0.8)- with pytest.raises(ValueError, match="^the drawing drifted further from the layout than a cut accepts"):- ui_kit.split_ui_kit(image)---def draw_ellipse(pixels, cx, cy, w, h, color):- """An ellipse ``w`` x ``h`` px whose bounding box is centred on (cx, cy)."""- yy, xx = np.indices((h, w))- region = pixels[cy - h // 2:cy - h // 2 + h, cx - w // 2:cx - w // 2 + w]- region[((xx - w / 2 + 0.5) / (w / 2)) ** 2 + ((yy - h / 2 + 0.5) / (h / 2)) ** 2 <= 1] = color---def two_way_sheet(dot):- """A sheet that fits the layout two ways (the counterexample to PR #125's cut): the seven frames drawn small, 20 x 8- px, each inside its own box both where the layout puts the box and with the layout squeezed to 0.9 from the top- edge, and one dot, ``dot`` px wide and tall, centred on pip_off's box so squeezed, which is the centre of pip_on's- own box. The sheet, and the frames' rects and the dot's."""- boxes = ui_kit.boxes(TALL)- pixels = np.zeros((TALL[1], TALL[0], 4), dtype=np.uint8)- drawn = {}- for name in FRAMES:- x, y, w, h = boxes[name]- cx, cy = x + w // 2, min(y + h // 2, int(0.9 * (y + h)) - 6)- fill(pixels, cx - 10, cy - 4, cx + 10, cy + 4, BORDER)- drawn[name] = (cx - 10, cy - 4, 20, 8)- x, y, w, h = boxes["pip_off"]- cx, cy = x + w // 2, round(0.9 * (y + h / 2))- draw_ellipse(pixels, cx, cy, *dot, PIP_OFF)- drawn["dot"] = (cx - dot[0] // 2, cy - dot[1] // 2, *dot)- return Image.fromarray(pixels), drawn--[email protected]("dot", [(18, 18), (60, 18)])-def test_a_drawing_that_fits_the_layout_two_ways_is_refused_with_its_own_reason(tmp_path, dot):- # Where the layout puts the boxes, and with the layout squeezed to 0.9, every frame lies inside its own box, clear- # of its edges, and the dot is centred on pip_on's box in the first and on pip_off's in the second: the drawing says- # neither which drift it was drawn with nor which dot it is. A dot 60 px wide overflows either box alike. The sheet- # is refused with its own reason, by the CLI too, which writes nothing.- image, drawn = two_way_sheet(dot)- boxes = ui_kit.boxes(TALL)- for sy, pip in ((1.0, "pip_on"), (0.9, "pip_off")):- for name in FRAMES:- x, y, w, h = drawn[name]- bx, by, bw, bh = boxes[name]- assert bx + 1 <= x and x + w <= bx + bw - 1, (sy, name)- assert sy * by + 1 <= y and y + h <= sy * (by + bh) - 1, (sy, name)- x, y, w, h = drawn["dot"]- bx, by, bw, bh = boxes[pip]- assert x + w / 2 == bx + bw / 2 and y + h / 2 == pytest.approx(sy * (by + bh / 2)), (sy, pip)- refusal = ("^pip_on, pip_off: under another drift the cut accepts, the drawing fits the layout at least as well "- r"\(to within 1 px\) with these elements named differently, so it does not say which elements they "- "are; generate the sheet again$")- with pytest.raises(ValueError, match=refusal):- ui_kit.split_ui_kit(image)- sheet, out = tmp_path / "uikit.png", tmp_path / "ui"- image.save(sheet)- with pytest.raises(SystemExit, match="^ui-kit: pip_on, pip_off: under another drift the cut accepts"):- ui_kit.main(["--sheet", str(sheet), "--out-dir", str(out)])- assert not out.exists()---def squeezed_sheet():- """A model's drawing of the layout squeezed to 0.9 from the top edge with pip_off alone in the band: each frame 96 %- as wide and 55 % as tall as its squeezed box (the timer badge round), inside that box and as near its own box's- centre as that allows, and the dot 72 % as wide as its box, on pip_off's squeezed centre."""- boxes = ui_kit.boxes(TALL)- pixels = np.zeros((TALL[1], TALL[0], 4), dtype=np.uint8)- for name in FRAMES:- x, y, w, h = boxes[name]- rw, rh = 0.96 * w, 0.55 * 0.9 * h- if name == "timer_badge":- rw = rh = 0.55 * 0.9 * min(w, h)- cx, cy = x + w / 2, min(max(y + h / 2, 0.9 * y + rh / 2 + 1), 0.9 * (y + h) - rh / 2 - 1)- fill(pixels, round(cx - rw / 2), round(cy - rh / 2), round(cx + rw / 2) + 1, round(cy + rh / 2) + 1, BORDER)- x, y, w, h = boxes["pip_off"]- r, cx, cy = 0.4 * 0.9 * min(w, h), x + w / 2, 0.9 * (y + h / 2)- draw_disc(pixels, round(cx - r), round(cy - r), round(cx + r) - round(cx - r) + 1, PIP_OFF)- return Image.fromarray(pixels)---def test_a_drawing_that_fits_one_drift_better_is_named_by_it():- # Squeezed to 0.9, the layout holds every frame clear of its box's edges and the dot on pip_off's centre. The dot- # would be pip_on under a layout stretched a little and moved up, but no such drift keeps the frames and the dot- # clear of the edges: the nearest leaves them more than a pixel short of it. The dot is pip_off.- elements, report = ui_kit.split_ui_kit(squeezed_sheet())- assert report["missing"] == [name for name in BAND if name != "pip_off"]- assert list(elements) == FRAMES + ["pip_off"]---def scattered_sheet(seed):- """A 2:3 sheet drawn under a drift picked at random within the accepted range, with a random set of band elements- left out, each element a rectangle a random share of its box across (from a twentieth to nine tenths) anywhere- inside its moved box, at least 1 px clear of the edges. The sheet, and each element's rect by name."""- rng = np.random.default_rng(seed)- sx, tx, sy, ty = accepted_drift(rng)- share = rng.choice([0.05, 0.1, 0.2, 0.4, 0.7, 0.9])- missing = [name for name in BAND if rng.random() < 0.6]- pixels = np.zeros((TALL[1], TALL[0], 4), dtype=np.uint8)- drawn = {}- for name, (bx, by, bw, bh) in ui_kit.boxes(TALL).items():- if name in missing:- continue- x0, x1, y0, y1 = bx * sx + tx, (bx + bw) * sx + tx, by * sy + ty, (by + bh) * sy + ty- w = max(5, int((x1 - x0) * share * rng.uniform(0.5, 1)))- h = max(5, int((y1 - y0) * share * rng.uniform(0.5, 1)))- w, h = min(w, int(x1 - x0) - 4), min(h, int(y1 - y0) - 4)- x = int(rng.integers(math.ceil(x0) + 1, math.floor(x1) - w))- y = int(rng.integers(math.ceil(y0) + 1, math.floor(y1) - h))- fill(pixels, x, y, x + w, y + h, BORDER)- drawn[name] = (x, y, w, h)- return Image.fromarray(pixels), drawn---def anchored_sheet(seed):- """A 2:3 sheet drawn under a drift picked at random within the accepted range: the seven frames full size, as- `synthetic_sheet` draws them, and a random half of the band elements, each a rectangle a random share of its box- across (from a twentieth to seven tenths) anywhere inside its moved box, at least 1 px clear of the edges. The- sheet, and each element's rect by name."""- rng = np.random.default_rng(100_000 + seed)- drift = accepted_drift(rng)- sx, tx, sy, ty = drift- image, drawn = synthetic_sheet(size=TALL, drift=drift, missing=BAND, haze=False, noise=False)- pixels = np.asarray(image).copy()- share = rng.choice([0.05, 0.1, 0.2, 0.4, 0.7])- for name in BAND:- if rng.random() < 0.5:- continue- bx, by, bw, bh = ui_kit.boxes(TALL)[name]- x0, x1, y0, y1 = bx * sx + tx, (bx + bw) * sx + tx, by * sy + ty, (by + bh) * sy + ty- w = max(5, int((x1 - x0) * share * rng.uniform(0.5, 1)))- h = max(5, int((y1 - y0) * share * rng.uniform(0.5, 1)))- w, h = min(w, int(x1 - x0) - 4), min(h, int(y1 - y0) - 4)- x = int(rng.integers(math.ceil(x0) + 1, math.floor(x1) - w))- y = int(rng.integers(math.ceil(y0) + 1, math.floor(y1) - h))- fill(pixels, x, y, x + w, y + h, BORDER)- drawn[name] = (x, y, w, h)- return Image.fromarray(pixels), drawn---# The reading of a drawing (docs/ui-kit.md "Reading the drawing"), evaluated here at given drifts, apart from the cut's-# own search. A drift (sx, tx, sy, ty) moves each layout box (x, y, w, h) to (x sx + tx, y sy + ty, w sx, h sy). Each-# part goes to the first box, in layout order, whose moved box widened by half the gap (the widening scaled with it)-# holds its centroid, or to none. A part in a box costs how far each of its four sides falls short of lying CLEARANCE px-# inside the moved box; a part in no box costs half the gap, CLEARANCE and half its smaller extent. A reading's cost is-# the sum. The cut considers the drifts within READ_SCALE and READ_OFFSET (px at 1024) along each axis, and two readings-# whose costs differ by at most TIE px fit the drawing equally well.-CLEARANCE = TIE = 1-READ_SCALE = (0.875, 1.125)-READ_OFFSET = 120---def read_at(parts, size, drifts):- """At each of ``drifts``: the reading's cost, and each part's box (its index in layout order, -1 for none)."""- layout = np.asarray(list(ui_kit.boxes(size).values()), dtype=float)- reach = ui_kit.GAP / 2 * size[0] / ui_kit.REFERENCE- centroid = np.asarray([part["centroid"] for part in parts], dtype=float).reshape(-1, 2)- bbox = np.asarray([part["bbox"] for part in parts], dtype=float).reshape(-1, 4)- drifts = np.asarray(drifts, dtype=float).reshape(-1, 4)- held = np.ones((len(drifts), len(parts), len(layout)), dtype=bool) # [drift, part, box]- short = np.zeros(held.shape)- for axis in (0, 1):- s, t = drifts[:, 2 * axis, None, None], drifts[:, 2 * axis + 1, None, None]- low, high = layout[:, axis], layout[:, axis] + layout[:, 2 + axis]- at = centroid[None, :, axis, None]- held &= ((low - reach) * s + t <= at) & (at < (high + reach) * s + t)- short += np.maximum(0, low * s + t + CLEARANCE - bbox[None, :, axis, None])- short += np.maximum(0, bbox[None, :, 2 + axis, None] - (high * s + t) + CLEARANCE)- placed = held.any(axis=2)- box = np.where(placed, held.argmax(axis=2), -1)- loose = reach + CLEARANCE + np.minimum(bbox[:, 2] - bbox[:, 0], bbox[:, 3] - bbox[:, 1]) / 2- inside = np.take_along_axis(short, np.maximum(box, 0)[..., None], axis=2)[..., 0]- return np.where(placed, inside, loose).sum(axis=1), box---def assert_two_readings(refusal, size):- """The two readings an ambiguity refusal names, each evaluated here at its drift: it reads the drawing as the- refusal says, every frame holds a part, it costs at most TIE px (the drawing lies inside its boxes, so the least- cost is 0), and the two read the drawing differently."""- assert refusal.reason == "ambiguous", str(refusal)- names = list(ui_kit.boxes(size))- one, other = refusal.witnesses- for reading in (one, other):- cost, box = read_at(refusal.parts, size, [reading.drift])- assert [names[i] if i >= 0 else None for i in box[0]] == list(reading.boxes), (reading, str(refusal))- assert set(FRAMES) <= set(reading.boxes), reading- assert cost[0] <= TIE + 1e-6, (reading, cost[0])- assert one.boxes != other.boxes---def assert_read_as_drawn(image, drawn, edge=0):- """The sheet, every part of it inside its box under the drift it was drawn with, is cut as drawn or refused as- fitting the layout two ways (`assert_two_readings`), never refused otherwise. Cut as drawn: exactly the band- elements not drawn are missing, and each drawn element is cut as its own drawing, its rect within ``edge`` px of the- drawn one on every side, inside its element's box (the layout's, moved by `layout_fit`) to within a pixel."""- try:- elements, report = ui_kit.split_ui_kit(image)- except ui_kit.Refusal as refusal:- assert_two_readings(refusal, image.size)- return- assert report["missing"] == [name for name in BAND if name not in drawn]- assert list(elements) == list(report["elements"]) == [name for name in FRAMES + BAND if name in drawn]- for name, (x, y, w, h) in drawn.items():- rect, box = report["elements"][name]["rect"], report["elements"][name]["box"]- assert all(abs(value) <= edge for value in offset(report, drawn, name)), (name, rect, drawn[name])- assert box["x"] - 1 <= rect["x"] and rect["x"] + rect["w"] <= box["x"] + box["w"] + 1, (name, rect, box)- assert box["y"] - 1 <= rect["y"] and rect["y"] + rect["h"] <= box["y"] + box["h"] + 1, (name, rect, box)--[email protected]("seed", [2, 5, 6])-def test_a_sheet_of_small_drawings_that_fits_the_layout_one_way_is_cut_as_drawn(tmp_path, seed):- # Drawn wholly inside their boxes under a drift within the accepted range, with no other reading within 1 px: these- # sheets were refused as drifted further than a cut accepts (fitted at a scale of 0.758, 1.371 and 0.798), the- # least-squares fit of box centres dragged by small drawings placed off their boxes' centres. They are cut as drawn,- # by the CLI too.- image, drawn = scattered_sheet(seed)- elements, report = ui_kit.split_ui_kit(image)- assert report["missing"] == [name for name in BAND if name not in drawn]- assert list(elements) == list(drawn)- for name, (x, y, w, h) in drawn.items():- assert report["elements"][name]["rect"] == {"x": x, "y": y, "w": w, "h": h}, name- sheet, out = tmp_path / "uikit.png", tmp_path / "ui"- image.save(sheet)- assert ui_kit.main(["--sheet", str(sheet), "--out-dir", str(out)]) == 0- written = json.loads((out / "ui-kit.json").read_text())- assert written["missing"] == report["missing"] and written["elements"] == report["elements"]- assert sorted(p.name for p in out.iterdir()) == sorted([f"{name}.png" for name in drawn] + ["ui-kit.json"])--[email protected]("seed", slow_but(range(512), lambda seed: seed < 16))-def test_a_sheet_of_small_drawings_under_a_random_accepted_drift_is_cut_as_drawn_or_refused_as_two_readings(seed):- # Small drawings anywhere inside their boxes leave the drift less certain, so a sheet may fit the layout under two- # drifts that read it differently, and is then refused, naming both readings. It is never refused for another- # reason, and whenever it is cut, exactly the band elements not drawn are missing and every element drawn is cut as- # its own drawing, never under another's name.- image, drawn = scattered_sheet(seed)- assert_read_as_drawn(image, drawn)--[email protected]("seed", slow_but(range(256), lambda seed: seed < 8))-def test_full_size_frames_and_small_band_drawings_are_cut_as_drawn_or_refused_as_two_readings(seed):- # The full-size frames pin the drift; the band's small drawings lie anywhere inside their boxes, off their centres.- image, drawn = anchored_sheet(seed)- assert_read_as_drawn(image, drawn, edge=2)---def sampled_drifts(rng, size, around):- """Drifts at random within the drifts the cut considers: uniform, and near each drift of ``around``."""- unit = size[0] / ui_kit.REFERENCE- low = np.array([READ_SCALE[0], -READ_OFFSET * unit] * 2)- high = np.array([READ_SCALE[1], READ_OFFSET * unit] * 2)- near = [np.asarray(drift) + rng.normal(0, [0.004, 2.0, 0.004, 2.0], (2000, 4)) for drift in around]- drifts = np.concatenate([rng.uniform(low, high, (4000, 4))] + near)- return drifts[((drifts >= low) & (drifts <= high)).all(axis=1)]---COUNTEREXAMPLE_SHEETS = ([f"scattered-{seed}" for seed in range(1, 9)] + [f"anchored-{seed}" for seed in range(4)]- + ["two-way-18", "two-way-60", "squeezed", "nudged", "stray"])---def counterexample_sheet(label):- """A sheet for the counterexample search, and the drift it was drawn with."""- number = int(label.rpartition("-")[2]) if label[-1].isdigit() else None- if label.startswith("scattered"):- return scattered_sheet(number)[0], accepted_drift(np.random.default_rng(number))- if label.startswith("anchored"):- return anchored_sheet(number)[0], accepted_drift(np.random.default_rng(100_000 + number))- if label.startswith("two-way"):- return two_way_sheet((number, 18))[0], (1, 0, 1, 0)- if label == "squeezed":- return squeezed_sheet(), (1, 0, 0.9, 0)- if label == "nudged":- return synthetic_sheet(size=TALL, missing="pip_off", nudge={"pip_on": (0, 30)})[0], (1, 0, 1, 0)- return synthetic_sheet(size=TALL, stray=True)[0], (1, 0, 1, 0)--[email protected]("label", slow_but(COUNTEREXAMPLE_SHEETS, lambda label: label in {"scattered-1", "anchored-0"}))-def test_no_sampled_drift_reads_the_drawing_better_than_the_cut_found(label):- # A search for counterexamples, which proves nothing when it finds none: thousands of drifts at random, uniform over- # the drifts the cut considers and near the drift the sheet was drawn with and the cut's, evaluated here. None reads- # the drawing at a lower cost than the least the cut's search found (`_read`, the judgment `split_ui_kit` decides- # by); and when the sheet is cut, no reading that holds every frame, within TIE of the least such cost, reads it- # otherwise than the cut.- image, drawn_drift = counterexample_sheet(label)- judgment = ui_kit._read(image)- try:- ui_kit.split_ui_kit(image)- except ui_kit.Refusal:- cut = None- else:- (cut,) = judgment.candidates- around = [drawn_drift] + ([cut.drift] if cut is not None else [])- drifts = sampled_drifts(np.random.default_rng(COUNTEREXAMPLE_SHEETS.index(label)), image.size, around)- cost, box = read_at(judgment.parts, image.size, drifts)- assert cost.min() >= judgment.least - 1e-6, (label, cost.min(), judgment.least)- if cut is not None:- names = list(ui_kit.boxes(image.size))- valid = np.all([(box == names.index(name)).any(axis=1) for name in FRAMES], axis=0)- near = valid & (cost <= judgment.least_valid + TIE - 1e-6)- assert near.any(), label- want = np.array([names.index(name) if name is not None else -1 for name in cut.boxes])- assert (box[near] == want).all(), label---def test_a_mark_between_two_boxes_whose_widened_boxes_touch_is_never_read_in_no_box():- # The gap between the two dots' boxes is twice the reach, so their widened boxes touch: under every drift that- # leaves the mark inside the dots' columns, its centroid lies in one of them. A tall thin mark centred in that gap- # costs less in no box than in either dot's box, but no drift reads it in no box, so no reading that does is cut or- # named. Both readings that put it in a dot's box fit the sheet as well: the sheet is refused, and each of the two- # readings the refusal names reads the sheet as it says.- image, _ = synthetic_sheet(size=TALL, haze=False, noise=False)- pixels = np.asarray(image).copy()- x, y, w, h = ui_kit.boxes(TALL)["pip_on"]- below = ui_kit.boxes(TALL)["pip_off"][1]- cx, cy = x + w // 2, (y + h + below) // 2- fill(pixels, cx - 2, cy - 10, cx + 2, cy + 10, BORDER)- with pytest.raises(ui_kit.Refusal, match="^pip_on, pip_off: under another drift the cut accepts") as refused:- ui_kit.split_ui_kit(Image.fromarray(pixels))- names = list(ui_kit.boxes(TALL))- for reading in refused.value.witnesses:- cost, box = read_at(refused.value.parts, TALL, [reading.drift])- assert [names[i] if i >= 0 else None for i in box[0]] == list(reading.boxes), reading- assert None not in reading.boxes and cost[0] <= refused.value.least + TIE + 1e-6, (reading, cost[0])---def test_a_sheet_of_many_small_parts_is_cut_or_refused_in_seconds():- # Every element a 4 px square (16 px, the smallest part kept) anywhere inside its moved box, with about half the- # band left out, and sixty more such squares scattered over the sheet: most squares lie in no box under any drift,- # so no reading keeps the drawing clear of its boxes' edges; the search proves that within its work bound, and the- # sheet is decided or refused as off the layout within seconds.- rng = np.random.default_rng(47)- sx, tx, sy, ty = accepted_drift(rng)- pixels = np.zeros((TALL[1], TALL[0], 4), dtype=np.uint8)- for name, (bx, by, bw, bh) in ui_kit.boxes(TALL).items():- if name in BAND and rng.random() < 0.5:- continue- x0, x1, y0, y1 = bx * sx + tx, (bx + bw) * sx + tx, by * sy + ty, (by + bh) * sy + ty- x = int(rng.integers(math.ceil(x0) + 1, math.floor(x1) - 5))- y = int(rng.integers(math.ceil(y0) + 1, math.floor(y1) - 5))- fill(pixels, x, y, x + 4, y + 4, BORDER)- for _ in range(60):- x, y = rng.integers(0, TALL[0] - 4), rng.integers(0, TALL[1] - 4)- fill(pixels, x, y, x + 4, y + 4, BORDER)- with contextlib.suppress(ValueError):- ui_kit.split_ui_kit(Image.fromarray(pixels))---def test_the_cli_names_the_missing_elements_and_writes_no_png_for_them(tmp_path, capsys):- image, _ = synthetic_sheet(size=TALL, missing=("pip_off", "joystick_knob"))- sheet = tmp_path / "uikit.png"- image.save(sheet)- out = tmp_path / "ui"- assert ui_kit.main(["--sheet", str(sheet), "--out-dir", str(out)]) == 0- report = json.loads((out / "ui-kit.json").read_text())- assert report["missing"] == ["pip_off", "joystick_knob"]- kept = [name for name in FRAMES + BAND if name not in report["missing"]]- assert sorted(p.name for p in out.iterdir()) == sorted([f"{name}.png" for name in kept] + ["ui-kit.json"])- assert capsys.readouterr().out.rstrip().endswith("; missing, left out of the kit: pip_off, joystick_knob")---def tree(root):- """The visible files (by their bytes) and directories (None) under ``root``, and the hidden entries apart:- each by its path, not what it holds."""- visible, hidden = {}, []- for path in sorted(root.rglob("*")):- rel = path.relative_to(root)- if any(part.startswith(".") for part in rel.parts):- if not any(part.startswith(".") for part in rel.parts[:-1]):- hidden.append(rel.as_posix())- continue- visible[rel.as_posix()] = path.read_bytes() if path.is_file() else None- return visible, hidden---def test_a_kit_is_written_into_a_new_or_empty_out_dir_and_one_that_holds_anything_is_refused(tmp_path):- # A rerun into the directory an earlier kit filled, with another sheet, is refused by the directory's name and- # leaves it byte for byte as it was, as does any other file in it, a hidden one too, or a file at its path. An- # empty directory takes a kit, a refused sheet writes nothing, and a --report outside --out-dir must be new.- sheet, out = tmp_path / "uikit.png", tmp_path / "ui"-- def run(out_dir, size=TALL, missing=(), report=None):- synthetic_sheet(size=size, missing=missing)[0].save(sheet)- return ui_kit.main(["--sheet", str(sheet), "--out-dir", str(out_dir)]- + (["--report", str(report)] if report else []))-- def refused(out_dir, held):- return (rf"^ui-kit: --out-dir {re.escape(str(out_dir.resolve()))} {held}; "- "a kit is written whole into a new or empty directory$")-- assert run(out) == 0- kit = tree(out)- for size, missing in ((TALL, "pip_off"), ((SIZE, SIZE), ())):- with pytest.raises(SystemExit, match=refused(out, "holds badge.png and 15 more")):- run(out, size, missing)- assert tree(out) == kit- for name in ("logo.png", ".hidden"):- other = tmp_path / f"other{name}"- other.mkdir()- (other / name).write_bytes(b"not a kit")- with pytest.raises(SystemExit, match=refused(other, f"holds {re.escape(name)}")):- run(other)- assert tree(other) == (({}, [name]) if name.startswith(".") else ({name: b"not a kit"}, []))- (tmp_path / "taken").write_bytes(b"a file")- with pytest.raises(SystemExit, match=refused(tmp_path / "taken", "is a file")):- run(tmp_path / "taken")- assert (tmp_path / "taken").read_bytes() == b"a file"- (tmp_path / "empty").mkdir()- assert run(tmp_path / "empty", missing="pip_off") == 0- kept = [name for name in FRAMES + BAND if name != "pip_off"]- assert sorted(tree(tmp_path / "empty")[0]) == sorted([f"{name}.png" for name in kept] + ["ui-kit.json"])- with pytest.raises(SystemExit, match="^ui-kit: panel: its box holds no element; generate the sheet again$"):- run(tmp_path / "new", missing="panel")- assert not (tmp_path / "new").exists()- report = tmp_path / "kit.json"- report.write_text("{}\n")- with pytest.raises(SystemExit, match=rf"^ui-kit: --report {re.escape(str(report.resolve()))} already exists; "- "a report outside --out-dir is written to a new path$"):- run(tmp_path / "elements", report=report)- assert report.read_text() == "{}\n" and not (tmp_path / "elements").exists()- # no hidden directory or temp file of a run is left anywhere- assert [path.name for path in tmp_path.rglob(".*") if path.name != ".hidden"] == []---# the out-dir and the report (None: in the out-dir) of each placement; the outside one's directories are made by-# the run, so a run that fails must remove them again-PUBLISH_PLACES = {"inside": ("ui", None), "outside": ("kit/elements", "reports/kit.json")}-FS_CALLS = ("open", "fsync", "rename", "replace", "link", "unlink", "rmdir", "mkdir")-KILLED = 97---class Faults:- """Every filesystem call the publish makes once the sheet is cut, counted. The k-th one fails once, just before it- runs or just after it returned: by an OSError (EIO), or by ending the process there, as a kill would. An interrupt- at a call is an interrupt at that call's instruction, which the instruction sweep below raises."""-- def __init__(self, monkeypatch, cut):- self.armed, self.calls, self.fail_at, self.when, self.mode, self.fired = False, [], None, None, None, False- for name in FS_CALLS:- monkeypatch.setattr(os, name, self.wrap(name, getattr(os, name)))-- def split_then_arm(image, **kwargs):- self.armed = True- return cut[0], copy.deepcopy(cut[1])-- monkeypatch.setattr(ui_kit, "split_ui_kit", split_then_arm)-- def fail(self, name):- self.fired = True- if self.mode == "kill":- os._exit(KILLED)- raise OSError(errno.EIO, f"injected {name} failure")-- def wrap(self, name, call):- def faulty(*args, **kwargs):- if not self.armed:- return call(*args, **kwargs)- paths = [Path(str(arg)).name for arg in args[:2] if isinstance(arg, (str, os.PathLike))]- self.calls.append(f"{name}({', '.join(paths)})")- here = len(self.calls) == self.fail_at- if here and self.when == "before":- self.fail(name)- result = call(*args, **kwargs)- if here and self.when == "after":- if name == "open":- os.close(result) # the run never gets it, so it would stay open in this process- self.fail(name)- return result- return faulty-- def run(self, args, fail_at=None, when=None, mode=None):- """The command's exit code or its refusal; a kill runs it in a child process and gives the child's code."""- self.calls, self.fail_at, self.when, self.mode, self.fired = [], fail_at, when, mode, False- if mode != "kill":- try:- return ui_kit.main(args)- except SystemExit as exc:- return str(exc)- finally:- self.armed = False- pid = os.fork()- if pid == 0:- code = 1- try:- sys.stdout = sys.stderr = io.StringIO()- code = ui_kit.main(args)- finally:- os._exit(code)- self.armed = False- return os.waitstatus_to_exitcode(os.waitpid(pid, 0)[1])---def files_of(state):- return {path: data for path, data in state.items() if data is not None}---# A kill forks the test process, which pytest-xdist runs with threads of its own: the child makes only the publish's-# filesystem calls and leaves by os._exit, and one that hung would end the test by its timeout.[email protected]("ignore:This process .* is multi-threaded, use of fork:DeprecationWarning")[email protected]("mode", ["raise", pytest.param("kill", marks=pytest.mark.skipif(- not hasattr(os, "fork"), reason="a kill is a child process ended at the fault"))])[email protected]("when", ["before", "after"])[email protected]("start", slow_but(["absent", "empty", "empty, removed first"], lambda start: start == "absent"))[email protected]("placement", slow_but(sorted(PUBLISH_PLACES), lambda placement: placement == "inside"))-def test_a_failure_or_a_kill_at_any_step_of_the_publish_leaves_nothing_or_the_whole_kit(- tmp_path, monkeypatch, placement, start, when, mode):- # Each filesystem call of the publish fails once, just before it runs or just after it returned, in a copy of the- # same start. One of those calls publishes the kit: the rename that gives it --out-dir's name or, with the report- # outside, the link that gives the report its name. An error before that leaves the start exactly, with nothing- # hidden; from it on, the whole kit. A kill leaves what the run had made: the start, the whole kit or, killed- # between the rename and the link, the whole --out-dir and no report yet; never part of a kit under the out-dir's- # name, and nothing hidden but the run's own staging directory or report temp beside them. "removed first" is the- # Windows rename, which takes no existing directory's name, so an empty --out-dir is removed just before it.- out_rel, report_rel = PUBLISH_PLACES[placement]- sheet = tmp_path / "uikit.png"- image, _ = synthetic_sheet(size=TALL, missing="pip_off")- image.save(sheet)- faults = Faults(monkeypatch, ui_kit.split_ui_kit(image))- if start == "empty, removed first":- monkeypatch.setattr(ui_kit, "RENAME_ONTO_EMPTY_DIR", False)- template = tmp_path / "start"- template.mkdir()- if start != "absent":- (template / out_rel).mkdir(parents=True)-- def copy_of_start(name):- return Path(shutil.copytree(template, tmp_path / name))-- def args(root):- return (["--sheet", str(sheet), "--out-dir", str(root / out_rel)]- + (["--report", str(root / report_rel)] if report_rel else []))-- before, _ = tree(template)- reference = copy_of_start("reference")- assert faults.run(args(reference)) == 0- calls = faults.calls- complete, litter = tree(reference)- assert litter == []- report = report_rel or f"{out_rel}/ui-kit.json"- kit_files = [path for path in files_of(complete) if path != report]- assert len(kit_files) == 14 and report in complete- # the sweep reaches each file of the kit, the rename of the out-dir and the report's own commit- reached = {name for call in calls for name in call[call.index("(") + 1:-1].split(", ")}- assert {Path(path).name for path in kit_files} | {Path(out_rel).name, Path(report).name} <= reached, calls-- def naming(op, target):- """The number of the call ``op(…, target)``, which gives ``target`` its name."""- return next(k for k, call in enumerate(calls, 1) if call.startswith(f"{op}(") and call.endswith(f", {target})"))-- renamed = naming("rename", Path(out_rel).name)- published = naming("link", Path(report_rel).name) if report_rel else renamed- without_report = {path: data for path, data in files_of(complete).items() if path != report}- beside = [f"{Path(out_rel).parent / f'.{Path(out_rel).name}.ui-kit-'}".removeprefix("./")]- if report_rel:- beside.append(f"{Path(report_rel).parent / f'.{Path(report_rel).name}.'}".removeprefix("./"))- for k, call in enumerate(calls, 1):- root = copy_of_start(f"k{k}")- outcome = faults.run(args(root), fail_at=k, when=when, mode=mode)- after, hidden = tree(root)- where = (k, when, call, outcome, sorted(after), hidden)-- def ran(step):- return step < k or (step == k and when == "after")-- assert all(any(entry.startswith(prefix) for prefix in beside) for entry in hidden), where- if mode == "kill":- assert outcome == KILLED, where- left = complete if ran(published) else without_report if ran(renamed) else before- assert files_of(after) == files_of(left), where- directories = {path for path, data in after.items() if data is None}- kept = {path for path, data in before.items() if data is None}- if start == "empty, removed first":- kept.discard(out_rel)- assert kept <= directories <= kept | {path for path, data in complete.items() if data is None}, where- continue- assert faults.fired, where- assert outcome in (0, f"ui-kit: [Errno {errno.EIO}] injected {call[:call.index('(')]} failure"), where- if ran(published):- # hidden: only the report's temp, when removing it after the kit was published is what failed- assert after == complete and (hidden == [] or (- report_rel and mode == "raise" and all(entry.startswith(beside[-1]) for entry in hidden))), where- else:- assert outcome != 0 and after == before and hidden == [], where---class Halt(BaseException):- """An exception of no standard kind."""---# How each kind of interrupt arrives and what it ends the run with: a real signal through Python's own SIGINT-# handler, or an exception of no standard kind. A SIGTERM handler that exits ends the run through the same-# `except BaseException`, with no signal-specific code, so it is not swept again.-INTERRUPTS = {- "SIGINT": (signal.SIGINT, signal.default_int_handler, KeyboardInterrupt),- "BaseException": (None, None, Halt),-}---# Interrupted after a file is opened and before its with statement holds it, or as that statement closes it, a run-# leaves the file object to be closed when the run's frames go, which Python reports as an unclosed file.[email protected]("ignore:unclosed file:ResourceWarning")[email protected]("kind", sorted(INTERRUPTS))[email protected]("granularity", ["line", "instruction"])[email protected]("start", slow_but(["absent", "empty", "empty, removed first"], lambda start: start == "absent"))[email protected]("placement", slow_but(sorted(PUBLISH_PLACES), lambda placement: placement == "inside"))-def test_an_interrupt_at_any_line_or_instruction_of_the_publish_leaves_nothing_or_the_whole_kit(- tmp_path, monkeypatch, placement, start, granularity, kind):- # Python may raise an interrupt at any instruction: a signal's handler runs between instructions, and so does a- # tracer's or a debugger's callback, which can receive the signal or raise its own exception there. A tracer on the- # publish's own functions raises the interrupt once per run, at one line, or one instruction, of the publish, each- # in turn. Every run ends with that interrupt and leaves the start exactly, with nothing hidden, or the whole kit.- # The publish is given a small kit directly (one run per instruction); with the report inside --out-dir, it is in- # a directory of its own there. What ended a run is kept without its traceback, so the run's frames, and a file- # object only they hold, go when the run ends; a run interrupted between opening a file and wrapping the descriptor- # cannot close it, so each descriptor the run opened and left open is closed after it.- out_rel, report_rel = PUBLISH_PLACES[placement]- signum, handler, ends = INTERRUPTS[kind]- if start == "empty, removed first":- monkeypatch.setattr(ui_kit, "RENAME_ONTO_EMPTY_DIR", False)- event = "line" if granularity == "line" else "opcode"- data = b'{"kind": "sprite-gen-ui-kit"}\n'- opened, open_fd = [], os.open-- def recorded_open(*args, **kwargs):- fd = open_fd(*args, **kwargs)- opened.append((fd, os.fstat(fd)))- return fd-- monkeypatch.setattr(os, "open", recorded_open)-- def publish(root, target=None):- """Publish the kit into ``root``, interrupted at ``target``, one event of the run: (function, instruction- offset, occurrence). Answers the tree before and after, the run's events as such targets with where each- was, whether the interrupt was raised, and what ended the run (0 when nothing did)."""- root.mkdir()- if start != "absent":- (root / out_rel).mkdir(parents=True)- report = root / report_rel if report_rel else None- files = {"one.png": b"one", "two.png": b"two"} | ({} if report else {"reports/kit.json": data})- given = tree(root)- seen, events, raised = Counter(), [], []- opened.clear()-- def each(frame, what, arg):- if what == event:- key = (id(frame.f_code), frame.f_lasti)- seen[key] += 1- events.append((*key, seen[key], f"{frame.f_code.co_name}:{frame.f_lineno}@{frame.f_lasti}"))- if events[-1][:3] == target and not raised:- raised.append(True)- sys.settrace(None)- if signum is None:- raise Halt- signal.raise_signal(signum)- return each-- def calls(frame, what, arg):- if frame.f_code.co_filename != ui_kit.__file__:- return None- if event == "opcode":- frame.f_trace_opcodes, frame.f_trace_lines = True, False- return each-- previous = signal.signal(signum, handler) if signum is not None else None- tracer = sys.gettrace()- sys.settrace(calls)- try:- ui_kit._write_kit(root / out_rel, files, report, data)- ended = 0- except BaseException as exc:- ended = exc.with_traceback(None)- finally:- sys.settrace(tracer)- if signum is not None:- signal.signal(signum, previous)- for fd, stat in opened:- with contextlib.suppress(OSError): # closed by the run: gone, or another file's number now- if os.path.samestat(os.fstat(fd), stat):- os.close(fd)- return given, tree(root), events, bool(raised), ended-- # the first opcode-traced run of a function reports none of its instructions on Python 3.12, and some from 3.13- publish(tmp_path / "warm-up")- before, complete, events, _, ended = publish(tmp_path / "reference")- assert ended == 0 and complete[1] == [] and complete != before- assert {Path(path).name for path in files_of(complete[0])} == {"one.png", "two.png", "kit.json"}- missed, bad = [], []- for n, (*target, at) in enumerate(events):- given, after, _, raised, ended = publish(tmp_path / f"{n}", tuple(target))- if not raised: # the run never reached that event (see below)- missed.append(at)- continue- assert given == before- if not (isinstance(ended, ends) and after in (before, complete)):- bad.append((f"{at}#{target[2]}", repr(ended), sorted(after[0]), after[1]))- assert bad == []- # Every line event of the reference run recurs in a faulted one. A tracer's instruction events can differ a little- # between runs on Python 3.13 and later, so one a faulted run never reaches gets no interrupt; most do.- assert (missed == [] if granularity == "line" else len(missed) < len(events) / 2), missed--[email protected]("placement", sorted(PUBLISH_PLACES))-def test_a_kit_that_reaches_the_out_dir_first_refuses_this_run_and_stays_whole(tmp_path, monkeypatch, placement):- # Two runs into one new --out-dir: the other run's kit lands there just before this run renames its own in.- # This run is refused, removes what it made (its staging directory, the report's directory) and leaves the- # other kit as it was.- out_rel, report_rel = PUBLISH_PLACES[placement]- sheet, other = tmp_path / "uikit.png", tmp_path / "other"- synthetic_sheet(size=TALL)[0].save(sheet)- assert ui_kit.main(["--sheet", str(sheet), "--out-dir", str(other)]) == 0- synthetic_sheet(size=TALL, missing="pip_off", noise=False)[0].save(sheet)- out = (tmp_path / out_rel).resolve()- rename = os.rename-- def the_other_kit_first(src, dst, *args, **kwargs):- if Path(dst) == out and not out.exists():- shutil.copytree(other, out)- return rename(src, dst, *args, **kwargs)-- monkeypatch.setattr(os, "rename", the_other_kit_first)- with pytest.raises(SystemExit, match=rf"^ui-kit: --out-dir {re.escape(str(out))} was filled while this kit "- r"was cut: it holds badge\.png and 15 more; nothing was written$"):- ui_kit.main(["--sheet", str(sheet), "--out-dir", str(out)]- + (["--report", str(tmp_path / report_rel)] if report_rel else []))- assert tree(out) == tree(other)- assert [path.name for path in tmp_path.rglob(".*")] == []- assert not (tmp_path / "reports").exists()---def test_a_report_that_appears_first_refuses_this_run_and_is_kept(tmp_path, monkeypatch):- # Two runs with their own --out-dir and one --report outside them: the other run's report lands just before- # this run's own. This run is refused, takes its kit back out, and the other report stays as it was.- sheet, out, report = tmp_path / "uikit.png", tmp_path / "elements", tmp_path / "reports" / "kit.json"- synthetic_sheet(size=TALL)[0].save(sheet)- theirs = b'{"kind": "sprite-gen-ui-kit", "the other run": true}\n'- link = os.link-- def the_other_report_first(src, dst, *args, **kwargs):- if Path(dst) == report.resolve() and not report.exists():- report.write_bytes(theirs)- return link(src, dst, *args, **kwargs)-- monkeypatch.setattr(os, "link", the_other_report_first)- with pytest.raises(SystemExit, match=rf"^ui-kit: --report {re.escape(str(report.resolve()))} appeared while "- "this kit was cut; nothing was written$"):- ui_kit.main(["--sheet", str(sheet), "--out-dir", str(out), "--report", str(report)])- assert report.read_bytes() == theirs- assert not out.exists()- assert sorted(path.relative_to(tmp_path).as_posix() for path in tmp_path.rglob("*")) == [- "reports", "reports/kit.json", "uikit.png"]---def test_a_fill_whose_ends_do_not_fit_its_bar_frame_is_flagged():- image, drawn = synthetic_sheet(size=TALL, noise=False, haze=False)- pixels = np.asarray(image).copy()- # end caps 112 px long on a 296 px fill, short of its middle fifth: scaled to the 26 px track's height- # (the fill is 24 px tall), the two fixed ends are 247 px wide, and the track is 242 px long- x, y, w, h = drawn["xp_bar_fill"]- fill(pixels, x, y, x + 112, y + h, FILL_CAP)- fill(pixels, x + w - 112, y, x + w, y + h, FILL_CAP)- _, report = ui_kit.split_ui_kit(Image.fromarray(pixels))- entry = report["elements"]["xp_bar_fill"]- assert entry["insets"]["left"] == entry["insets"]["right"] == 114- rect = entry["inside"]["rect"]- assert (entry["insets"]["left"] + entry["insets"]["right"]) * entry["inside"]["scale"] >= rect["w"]- assert report["status"] == "needs-review"- assert [reason for reason in report["review_reasons"] if reason.startswith("xp_bar_fill:")] == [- "xp_bar_fill: scaled to the height of xp_bar_frame's content area, its fixed ends are wider than that "- "area; a full bar would overflow it"]---def pack_tall_kit(tmp_path, scale, **kwargs):- image, drawn = synthetic_sheet(size=TALL, **kwargs)- sheet = tmp_path / "uikit.png"- image.save(sheet)- assert ui_kit.main(["--sheet", str(sheet), "--out-dir", str(tmp_path / "ui")]) == 0- request = tmp_path / "game.json"- request.write_text(json.dumps({"version": 2, "ui": {"kit": "ui/ui-kit.json", "scale": scale}}))- out = tmp_path / "pack"- return game_pack.pack(request, out), out---def stored_frame(out, result, frame):- for page in result["textures"]:- if frame in page["frames"]:- box = page["frames"][frame]["frame"]- with Image.open(out / page["image"]) as atlas:- return atlas.convert("RGBA").crop((box["x"], box["y"], box["x"] + box["w"], box["y"] + box["h"]))- raise AssertionError(frame)--[email protected]("scale", [1, 0.5, 0.37])-def test_a_packed_fill_is_stored_as_its_bar_frames_content_area(tmp_path, scale):- result, out = pack_tall_kit(tmp_path, scale)- nine = result["ui"]["nine_slice"]- assert list(nine) == sorted(FRAMES + BAND)- for fill_name, frame in (("hp_bar_fill", "hp_bar_frame"), ("xp_bar_fill", "xp_bar_frame")):- entry, bar = nine[fill_name], nine[frame]- assert set(entry) == {"frame", "size", "stretch", "insets", "padding", "inside"}- assert all("inside" not in nine[name] for name in nine if not name.endswith("_fill"))- pad = bar["padding"]- rect = {"x": pad["left"], "y": pad["top"], "w": bar["size"]["w"] - pad["left"] - pad["right"],- "h": bar["size"]["h"] - pad["top"] - pad["bottom"]}- # the fill is stored at the frame's content area: at full width it covers it to the pixel, never past it- assert entry["inside"] == {"element": frame, "rect": rect}- assert entry["size"] == {"w": rect["w"], "h": rect["h"]}- assert rect["x"] + rect["w"] + pad["right"] == bar["size"]["w"]- assert rect["y"] + rect["h"] + pad["bottom"] == bar["size"]["h"]- assert entry["stretch"] == "x" and entry["insets"]["top"] == entry["insets"]["bottom"] == 0- assert entry["insets"]["left"] + entry["insets"]["right"] < rect["w"]- assert entry["padding"] == {"left": 0, "right": 0, "top": 0, "bottom": 0}- stored = stored_frame(out, result, entry["frame"])- assert stored.size == (rect["w"], rect["h"])- # its ends are the fill's own ends resized by one factor, never stretched: the factor makes it as tall- # as the content area- with Image.open(tmp_path / "ui" / f"{fill_name}.png") as source:- source = source.convert("RGBA")- factor = rect["h"] / source.height- resized = resize_cell(source, (max(1, round(source.width * factor)), rect["h"]))- left, right = entry["insets"]["left"], entry["insets"]["right"]- cells = np.asarray(stored)- ends = np.asarray(resized)- assert np.array_equal(cells[:, :left], ends[:, :left])- assert np.array_equal(cells[:, rect["w"] - right:], ends[:, resized.width - right:])- # round parts keep their aspect: scaled by `scale` alone, never stretched- report = json.loads((tmp_path / "ui" / "ui-kit.json").read_text())- for name in ("pip_on", "pip_off", "joystick_base", "joystick_knob"):- entry, source = nine[name], report["elements"][name]["size"]- assert entry["stretch"] == "none" and set(entry["insets"].values()) == {0}- assert entry["size"] == {"w": max(1, round(source["w"] * scale)), "h": max(1, round(source["h"] * scale))}- assert stored_frame(out, result, entry["frame"]).size == (entry["size"]["w"], entry["size"]["h"])--[email protected]("missing", ["xp_bar_fill", tuple(BAND)])-def test_a_partial_kit_packs_only_the_elements_it_holds(tmp_path, missing):- gone = {missing} if isinstance(missing, str) else set(missing)- result, out = pack_tall_kit(tmp_path, 0.5, missing=missing)- nine = result["ui"]["nine_slice"]- assert set(nine) == set(FRAMES + BAND) - gone- # the manifest names only frames the atlas holds, and the written manifest is the one returned- assert {name for page in result["textures"] for name in page["frames"]} == {f"ui/{name}" for name in nine}- assert json.loads((out / "game-pack.json").read_text())["ui"]["nine_slice"] == nine--[email protected]("size", [TALL])[email protected]("scale", [0.75, 0.5, 0.37, 0.25])-def test_packed_kit_keeps_ornament_fringes_out_of_the_stretched_middle(tmp_path, scale, size):- image, _ = synthetic_sheet(size=size, noise=False, haze=False)- sheet = tmp_path / "uikit.png"- image.save(sheet)- assert ui_kit.main(["--sheet", str(sheet), "--out-dir", str(tmp_path / "ui")]) == 0- request = tmp_path / "game.json"- request.write_text(json.dumps({"version": 2, "ui": {"kit": "ui/ui-kit.json", "scale": scale}}))- out = tmp_path / "pack"- result = game_pack.pack(request, out)- frames = {name: (page, record) for page in result["textures"] for name, record in page["frames"].items()}- for name, entry in result["ui"]["nine_slice"].items():- page, record = frames[entry["frame"]]- box = record["frame"]- with Image.open(out / page["image"]) as atlas:- stored = np.asarray(atlas.convert("RGBA").crop(- (box["x"], box["y"], box["x"] + box["w"], box["y"] + box["h"]))).astype(float)- stored[..., :3] *= stored[..., 3:] / 255- insets, (w, h) = entry["insets"], (entry["size"]["w"], entry["size"]["h"])- if entry["stretch"] in ("xy", "x"):- band = stored[:, insets["left"]:w - insets["right"]]- # every stretched column looks like the band's own median column, within 8 of 255- assert np.abs(band - np.median(band, axis=1)[:, None]).max() <= 8, (name, scale, "x")- if entry["stretch"] == "xy":- band = stored[insets["top"]:h - insets["bottom"]]- assert np.abs(band - np.median(band, axis=0)[None]).max() <= 8, (name, scale, "y")---def test_padding_follows_a_smooth_gradient_face_to_its_border():- # a button face that darkens smoothly from top to bottom (70 units over its height), inside a sharp- # 4 px silver border: the content area is the whole face, not a band around its centre- w, h = 160, 64- pixels = np.zeros((h, w, 4), dtype=np.uint8)- pixels[:, :] = BORDER- face = np.linspace(110, 40, h - 8).round().astype(np.uint8)- pixels[4:h - 4, 4:w - 4, 0] = 20- pixels[4:h - 4, 4:w - 4, 1] = face[:, None] // 2- pixels[4:h - 4, 4:w - 4, 2] = face[:, None]- pixels[4:h - 4, 4:w - 4, 3] = 255- padding, notes = ui_kit.measure_padding(Image.fromarray(pixels))- assert padding == {"left": 6, "right": 6, "top": 6, "bottom": 6}- assert notes == []---# A square sheet, split and packed by `ui-kit` and `game-pack` before the 2:3 sheet existed (base bfcab36):-# the guide, the report (sheet path aside) and every element's pixels, and the pack's manifest bytes and page-# pixels at two scales. Encoded PNG bytes depend on the zlib build, so images are compared as pixels.-SQUARE_FROZEN = {- "guide_text": "6dccc85d1b063e3d7714435ca629ad0ade3b42b720e01ae2b63bd74723383b43",- "guide_image": "66fe2622be0544604774c577bf1eb0619abd48f430a0eafe983a4f9132acaf91",- "report": "56d2b589e613f436fd18c295d74e6031505ffb5114397384929cca9f1e959888",- "elements": {- "button.png": "080fcf70864cb593dc41bbce0ca25f53aa98dc0046b376f2244970e130ff3d97",- "button_pressed.png": "cd789c638d312ad99406db8886c892d3caeb9a2754b31a9a4eb2af7a03f735a2",- "card.png": "79e53083c231e2cffabad9f96204d907c9fc7e9e0e32ba631aa19a6c14e34b67",- "hp_bar_frame.png": "d79732398bf77c5cc378a050d4340e7824f8353539a03cc6d5116fb914267f51",- "panel.png": "e1cb7ffd6c22205d8de77417ceb8d4193a76cb30e06ac2b7186cd61a2e45048d",- "timer_badge.png": "18e772b599a5c07004eab4c06cf43650b8617690ee151e265d0de9b32d4e9588",- "xp_bar_frame.png": "9209c935bc75c4dfb465c9060b7f3b8783186f2f69a0ebb85b7ecd161ef9bc00",- },- "pack": {- 0.5: ("1c1e4f1f8a844c8ab9eafd2ebbe0adea3a62b79d960d1518f2c55b6f62576a86",- ["8c107995d96e71ba7693c30a763b8b47df5c497a5041506ec5152fb465e9e640"]),- 0.37: ("698822abe6d887c04cc54e3ed40526366da298f164bda81c77980574c2c94445",- ["a819f45d7b812e5c420a3f9908dd7bb48e80ba8bac94354859ffd2af09bb40d2"]),- },-}---def pixel_digest(path):- with Image.open(path) as image:- return hashlib.sha256(image.convert("RGBA").tobytes()).hexdigest()---def test_a_square_sheet_is_split_and_packed_as_before_the_tall_sheet(tmp_path):- ui_kit.draw_guide(tmp_path / "guide.png", (1024, 1024))- assert hashlib.sha256(ui_kit.guide_text().encode()).hexdigest() == SQUARE_FROZEN["guide_text"]- assert pixel_digest(tmp_path / "guide.png") == SQUARE_FROZEN["guide_image"]- image, _ = synthetic_sheet()- sheet = tmp_path / "uikit.png"- image.save(sheet)- assert ui_kit.main(["--sheet", str(sheet), "--out-dir", str(tmp_path / "ui")]) == 0- text = (tmp_path / "ui" / "ui-kit.json").read_text().replace(json.dumps(str(sheet.resolve())), '"<sheet>"')- assert hashlib.sha256(text.encode()).hexdigest() == SQUARE_FROZEN["report"]- assert {png.name: pixel_digest(png) for png in sorted((tmp_path / "ui").glob("*.png"))} == SQUARE_FROZEN["elements"]- for scale, (manifest, pages) in SQUARE_FROZEN["pack"].items():- request = tmp_path / f"game-{scale}.json"- request.write_text(json.dumps({"version": 2, "ui": {"kit": "ui/ui-kit.json", "scale": scale}}))- out = tmp_path / f"pack-{scale}"- result = game_pack.pack(request, out)- assert hashlib.sha256((out / "game-pack.json").read_bytes()).hexdigest() == manifest, scale- assert [pixel_digest(out / page["image"]) for page in result["textures"]] == pages, scalediff --git a/tests/gen/test_layout_guide.py b/tests/gen/test_layout_guide.pyindex f963b8a..58bfa4f 100644--- a/tests/gen/test_layout_guide.py+++ b/tests/gen/test_layout_guide.py@@ -119,59 +119,8 @@ def test_refuses_a_ratio_it_cannot_read(tmp_path, monkeypatch):_run(tmp_path, monkeypatch, layout_guide=True, aspect_ratio="tall")-def test_ui_kit_guide_attaches_the_kit_layout_and_names_every_element(tmp_path, monkeypatch):- from sprite_gen.frames import ui_kit-- fake, report = _run(tmp_path, monkeypatch, layout_guide="ui-kit", aspect_ratio="1:1")-- guide = fake.attached[0].convert("RGB")- assert guide.size == (1024, 1024)- for x, y, w, h in ui_kit.boxes((1024, 1024)).values():- assert guide.getpixel((x + w // 2, y)) == ui_kit.GUIDE_BOX- assert guide.getpixel((x + w // 2, y + h // 2)) == ui_kit.GUIDE_BACKGROUND- request = fake.requests[0]- assert request.prompt.startswith("a tall knight, full body\n\n")- assert request.prompt.endswith(ui_kit.guide_text())- assert "crown" not in request.prompt- cell = report["extra"]["layout_guide"]- assert cell["kind"] == "ui-kit"- assert cell["boxes"]["panel"] == {"x": 48, "y": 48, "w": 576, "h": 400}- assert report["refs"] == []---def test_ui_kit_guide_is_square_or_2_3(tmp_path, monkeypatch):- for ratio in ("16:9", "3:4", "9:16"):- with pytest.raises(SystemExit, match=r"square \(1:1.*2:3"):- _run(tmp_path, monkeypatch, layout_guide="ui-kit", aspect_ratio=ratio)- fake, _ = _run(tmp_path, monkeypatch, layout_guide="ui-kit")- assert fake.attached[0].size == (1024, 1024)---def test_ui_kit_guide_at_2_3_is_the_whole_kit(tmp_path, monkeypatch):- from sprite_gen.frames import ui_kit-- fake, report = _run(tmp_path, monkeypatch, layout_guide="ui-kit", aspect_ratio="2:3")-- guide = fake.attached[0].convert("RGB")- assert guide.size == (683, 1024)- boxes = ui_kit.boxes((683, 1024))- assert list(boxes) == [slot.name for slot in ui_kit.LAYOUT]- for name, (x, y, w, h) in boxes.items():- # a box's top edge, or a round part's circle, passes the top centre of its place- assert ui_kit.GUIDE_BOX in [guide.getpixel((x + w // 2, y + i)) for i in range(3)], name- assert guide.getpixel((x + w // 2, y + h // 2)) == ui_kit.GUIDE_BACKGROUND- request = fake.requests[0]- assert request.aspect_ratio == "2:3"- assert request.prompt.endswith(ui_kit.guide_text((683, 1024)))- assert ui_kit.guide_text((683, 1024)) != ui_kit.guide_text()- cell = report["extra"]["layout_guide"]- assert cell["kind"] == "ui-kit" and (cell["width"], cell["height"]) == (683, 1024)- assert cell["boxes"]["joystick_knob"] == dict(zip("xywh", boxes["joystick_knob"]))- assert cell["boxes"]["panel"] == {"x": 32, "y": 32, "w": 384, "h": 267}--def test_the_flag_alone_is_still_the_figure_guide():parser = gen._build_parser()assert parser.parse_args(["--out", "x.png", "--layout-guide"]).layout_guide == "figure"- assert parser.parse_args(["--out", "x.png", "--layout-guide", "ui-kit"]).layout_guide == "ui-kit"+ assert parser.parse_args(["--out", "x.png", "--layout-guide", "figure"]).layout_guide == "figure"assert parser.parse_args(["--out", "x.png"]).layout_guide is Nonediff --git a/tests/gen/test_painted_checkerboard.py b/tests/gen/test_painted_checkerboard.pyindex c3d583b..8fbd20e 100644--- a/tests/gen/test_painted_checkerboard.py+++ b/tests/gen/test_painted_checkerboard.py@@ -125,12 +125,12 @@ class _CheckerboardProvider:return gen_base.ProviderRun(provider=self.name, elapsed_seconds=0.1, model=request.model)-def test_a_ui_kit_generation_that_comes_back_on_a_checkerboard_is_refused(tmp_path, monkeypatch):+def test_a_generation_with_a_layout_guide_that_comes_back_on_a_checkerboard_is_refused(tmp_path, monkeypatch):# the layout guide is an attached image, so `auto` keys the result (`refs-attached`): the checkerboard is# refused with its own reason instead of being keyed into an empty sheet, and nothing is publishedmonkeypatch.setattr(gen, "_make_provider", lambda name, *, keep_session: _CheckerboardProvider())- out, report = tmp_path / "uikit.png", tmp_path / "report.json"+ out, report = tmp_path / "props.png", tmp_path / "report.json"with pytest.raises(SystemExit, match=r"^chroma: the background is a painted transparency checkerboard"):- gen.run(provider="fake", prompt="A game UI kit in brass and walnut.", out=out, report=report,- transparent=True, layout_guide="ui-kit", aspect_ratio="2:3")+ gen.run(provider="fake", prompt="A sheet of six wooden props.", out=out, report=report,+ transparent=True, layout_guide=True, aspect_ratio="2:3")assert not out.exists() and not report.exists()diff --git a/tests/gen/test_provider_address.py b/tests/gen/test_provider_address.pyindex 38bda26..2601457 100644--- a/tests/gen/test_provider_address.py+++ b/tests/gen/test_provider_address.py@@ -24,7 +24,6 @@ from PIL import Imagefrom http_answer import Answerfrom sprite_gen import gen-from sprite_gen.audio import provider as sound_providerfrom sprite_gen.gen import anthropic_api, facing_vision, openai_provider, retry, video, xaiROOT = Path(__file__).resolve().parents[2]@@ -38,7 +37,6 @@ DEFAULTS = {"openai": ("SPRITE_GEN_OPENAI_BASE_URL", "https://api.openai.com/v1"),"xai": ("SPRITE_GEN_XAI_BASE_URL", "https://api.x.ai/v1"),"anthropic": ("SPRITE_GEN_ANTHROPIC_BASE_URL", "https://api.anthropic.com/v1"),- "elevenlabs": ("SPRITE_GEN_ELEVENLABS_BASE_URL", "https://api.elevenlabs.io/v1"),}@@ -96,8 +94,6 @@ def _answer(method: str, path: str, headers: dict[str, str] | None = None) -> tu}if (method, route.path) == ("POST", "/anthropic/messages"):return 200, {"Content-Type": "text/event-stream"}, SSE- if (method, route.path) == ("POST", "/elevenlabs/sound-generation"):- return 200, {}, b"audio"return 200, {"Content-Type": "application/json"}, json.dumps(answers[(method, route.path)]).encode()@@ -135,7 +131,7 @@ def loopback_only(monkeypatch):@pytest.fixturedef relay(monkeypatch, tmp_path):- """A relay on 127.0.0.1 standing in for all four providers, one path prefix each — its address is not set yet."""+ """A relay on 127.0.0.1 standing in for all three providers, one path prefix each — its address is not set yet."""server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Relay)server.seen = []server.root = f"http://127.0.0.1:{server.server_address[1]}"@@ -189,10 +185,6 @@ def _claude_batch(tmp_path):assert set(anthropic_api.batch_results(KEY, ended)) == {"c1"}-def _sound(tmp_path):- assert sound_provider.generate(sound_provider.request("sfx", "Impact", 3, False))[0] == b"audio"--SITES = {"openai-image": (_openai_image, "openai", [("POST", "/openai/images/generations")]),"openai-vision": (_openai_vision, "openai", [("POST", "/openai/responses")]),@@ -204,7 +196,6 @@ SITES = {"claude-batch": (_claude_batch, "anthropic", [("POST", "/anthropic/messages/batches"), ("GET", "/anthropic/messages/batches/msgbatch_01"),("GET", "/anthropic/sprite-gen/fetch?url=" + urllib.parse.quote(RESULTS, safe=""))]),- "elevenlabs-sound": (_sound, "elevenlabs", [("POST", "/elevenlabs/sound-generation?output_format=mp3_44100_128")]),}@@ -244,7 +235,6 @@ def _capture(monkeypatch, sent: list[str]) -> None:return _Lines(answer) if headers.get("Content-Type") == "text/event-stream" else answermonkeypatch.setattr(urllib.request, "urlopen", urlopen)- monkeypatch.setattr(sound_provider, "urlopen", urlopen)class _Lines(Answer):diff --git a/tests/packaging/test_curation_asset_packaging.py b/tests/packaging/test_curation_asset_packaging.pyindex a80379a..56b41af 100644--- a/tests/packaging/test_curation_asset_packaging.py+++ b/tests/packaging/test_curation_asset_packaging.py@@ -172,5 +172,6 @@ def test_the_package_never_reaches_into_the_scripts_wrappers() -> None:"instead:\n" + "\n".join(offenders))-def test_built_wheel_carries_browser_audio_player(wheel_names: set[str]) -> None:- assert 'sprite_gen/audio/sprite-gen-audio-v2.mjs' in wheel_names+def test_built_wheel_carries_the_face_player(wheel_names: set[str]) -> None:+ # `face-bake` runs the face pack's player with node from the installed package (`video/*.mjs` package data)+ assert 'sprite_gen/video/sprite-gen-face-v1.mjs' in wheel_namesdiff --git a/tests/spec/test_assets.py b/tests/spec/test_assets.pyindex 948edd9..f11a6c2 100644--- a/tests/spec/test_assets.py+++ b/tests/spec/test_assets.py@@ -333,24 +333,6 @@ def test_row_major_sheet_ignores_unused_cells_and_keeps_sidecar_policy(tmp_path)assert [f.getpixel((0, 0)) for f in seq.frames] == [Image.new("RGBA", (1, 1), c).getpixel((0, 0)) for c in colors]-def test_all_direction_rows_share_one_snapshot_decode(tmp_path, monkeypatch):- source = tmp_path / "directions.json"- source.write_text(json.dumps({"cell": [6, 8], "frames": 2, "fps": 10, "rows": ["NE", "SW"]}))- image = Image.new("RGBA", (12, 16), "red")- image.paste(Image.new("RGBA", (12, 8), "blue"), (0, 8))- image.save(tmp_path / "directions.png")- reads, decodes = [], []- read, decode = assets._read_bytes, assets._decode_image- monkeypatch.setattr(assets, "_read_bytes", lambda p: (reads.append(p.name), read(p))[1])- monkeypatch.setattr(assets, "_decode_image", lambda data: (decodes.append(len(data)), decode(data))[1])- sequences = assets.load_asset_states(source)- assert list(sequences) == ["NE", "SW"]- assert reads == ["directions.json", "directions.png"] and len(decodes) == 1- assert sequences["NE"].frames[0].getpixel((0, 0)) == (255, 0, 0, 255)- assert sequences["SW"].frames[0].getpixel((0, 0)) == (0, 0, 255, 255)- assert sequences["NE"].fingerprints() == sequences["SW"].fingerprints()--@pytest.mark.parametrize(("module", "name", "written"), [("sprite_gen.spec.runio", "REQUEST_KIND", "sprite-gen-request"),("sprite_gen.video.align", "REPORT_KIND", "sprite-gen-video-cycle-align-report"),diff --git a/tests/video/test_stop.py b/tests/video/test_stop.pyindex 84470e8..bf71cdd 100644--- a/tests/video/test_stop.py+++ b/tests/video/test_stop.py@@ -16,7 +16,6 @@ import numpy as npimport pytestfrom PIL import Image, ImageDraw-from sprite_gen.compose import game_packfrom sprite_gen.util.resample import resize_cellfrom sprite_gen.video import evidence, loop, stop@@ -317,25 +316,6 @@ def test_stop_refuses_a_loop_it_cannot_leave(tmp_path):make(tmp_path, few, meta_path, name="few")-def test_game_pack_packs_the_stop_to_play_once(tmp_path):- keyed, run_from = clip(tmp_path, cycles=2)- meta = cut(tmp_path, keyed, run_from + PERIOD)- out = make(tmp_path, keyed, meta)- request = tmp_path / "game.json"- request.write_text(json.dumps({"version": 1, "assets": [- {"id": "hero_run_side", "source": str(meta), "display": {"body_height": 56}},- {"id": "hero_stop_side", "source": str(tmp_path / "stop" / "stop.strip.json"), "display": {"body_height": 56}}]}))- packed = game_pack.pack(request, tmp_path / "pack")- run_anim, stop_anim = packed["animations"]["hero_run_side"], packed["animations"]["hero_stop_side"]- assert run_anim["loop"] is True- assert (stop_anim["loop"], stop_anim["hold_last"]) == (False, True) and len(stop_anim["frames"]) == len(out["shown"])- # Drawn at their pivots, the loop's cell lies where the stop's sidecar says it does: the stop stands where the run did.- f = stop_anim["size"]["w"] / out["strip"]["w"]- origin = out["strip"]["loop_cell_origin"]- for axis in (0, 1):- assert abs(stop_anim["anchor"][axis] - origin[axis] * f - run_anim["anchor"][axis]) <= 1.0--def test_stop_source_identity_is_the_loop_cut_from(tmp_path):keyed, run_from = clip(tmp_path, cycles=2)meta = cut(tmp_path, keyed, run_from + PERIOD)diff --git a/tests/workflow/test_capabilities.py b/tests/workflow/test_capabilities.pyindex a07b3a0..69bb8ac 100644--- a/tests/workflow/test_capabilities.py+++ b/tests/workflow/test_capabilities.py@@ -95,11 +95,12 @@ def test_types_defaults_and_flags_are_written_as_json() -> None:assert slicing["--cell-width"] == {"name": "--cell-width", "type": "int", "default": 512}inputs = {arg["name"]: arg for arg in _document()["verbs"]["compose-gif"]["args"]}["inputs"]assert inputs == {"name": "inputs", "positional": True, "type": "path", "nargs": "*"}- sound = {arg["name"]: arg for arg in _document()["verbs"]["sound"]["args"]}- assert sound["--loop"] == {"name": "--loop", "aliases": ["--no-loop"], "type": "flag"}+ prepare = {arg["name"]: arg for arg in _document()["verbs"]["prepare"]["args"]}+ assert prepare["--fit-ground-frames"] == {"name": "--fit-ground-frames", "aliases": ["--no-fit-ground-frames"],+ "type": "flag"}video, video_prompt = ({arg["name"]: arg for arg in _document()["verbs"][verb]["args"]} for verb in ("video", "video-prompt"))assert video["--model"]["default"] == video_prompt["--model"]["default"] == "grok-imagine-video-1.5"- assert _document()["verbs"]["sound"]["exclusive"] == [{"one_of": ["--prompt", "--prompt-file"], "required": True}]+ assert _document()["verbs"]["video-sway"]["exclusive"] == [{"one_of": ["--loop-dir", "--frames"], "required": True}]rife = _document()["verbs"]["rife"]assert rife["args"] == [] and list(rife["commands"]) == ["install"]assert {arg["name"] for arg in rife["commands"]["install"]["args"]} == {"--dir", "--zip", "--force", "--no-check",@@ -133,7 +134,7 @@ def test_what_each_paid_verb_calls() -> None:paid = {name: entry["providers"] for name, entry in verbs.items() if entry["paid"]}assert paid == {"gen": ["openai", "xai"], "gen-set": ["openai", "xai"], "logo": ["openai", "xai"],- "pixel-draw": ["anthropic"], "sound": ["elevenlabs"], "curation": ["xai"],+ "pixel-draw": ["anthropic"], "curation": ["xai"],"video": ["xai"], "video-extend": ["xai"], "video-edit": ["xai"], "video-set": ["xai"],}assert verbs["video-resume"]["providers"] == ["xai"] and verbs["video-resume"]["paid"] is False@@ -150,8 +151,6 @@ def test_the_provider_section_is_the_address_registry_and_the_key_names() -> Non"xai": {"base_url_env": "SPRITE_GEN_XAI_BASE_URL", "base_url": "https://api.x.ai/v1", "key_env": "XAI_API_KEY"},"anthropic": {"base_url_env": "SPRITE_GEN_ANTHROPIC_BASE_URL", "base_url": "https://api.anthropic.com/v1","key_env": "ANTHROPIC_API_KEY"},- "elevenlabs": {"base_url_env": "SPRITE_GEN_ELEVENLABS_BASE_URL", "base_url": "https://api.elevenlabs.io/v1",- "key_env": "ELEVENLABS_API_KEY"},}