Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
feat(handedness): a character with an item on one side has its left-facing views drawn, not mirrored, and checked
Soohong Kim00bdac451d58
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5d39dfb..7f18037 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,13 @@All notable public changes to `sprite-gen` are recorded here. Versions track the `version:` field in `SKILL.md` and `pyproject.toml`.+## Unreleased - A character with an item on one side has its left-facing views drawn, not mirrored++- **Handedness, said once** (`sprite_gen/gen/handedness.py`): `--handed "<item>=<left|right> [part]"` names an item on one of the character's own sides ("the black smartwatch=left wrist"); the engine works out where that side is in each view — the picture's right or left in a front, back or diagonal view, near or far in a side or diagonal view (`placement`) — and says it in the prompts (`text`). `sprite-gen gen --direction <view> [--facing …] --handed …` adds the engine's still view sentence and, per item, which side it is on, where that is in the view, and that the sentence outranks an attached picture; with `--handed`, `--facing-fix mirror` is refused and `regen` never falls back to a mirror. `video-prompt --handed` and `video-set --handed` end the clip prompt with where the item stays, anchored to the first frame and named once where it shows; on the far side of a side view it is not named at all — the near arm "stays bare, exactly as in the image" — since a clip prompt that names a hidden item draws it on the near arm. [docs/video-pipeline.md](docs/video-pipeline.md#handedness--an-item-on-one-side).+- **Left-facing views drawn, not mirrored — opt-in**: `video-set --facing right,left` films every side and diagonal view both ways, each from its own still (`--base side@right=… --base side@left=…`); a turned view missing a still for one facing is refused, naming the `gen --direction … --facing …` call that draws it. Items are named `<view>-<facing>-<state>`, the table names the facing, each side still is inspected for its own facing, and gaits are aligned across all eight. Mirroring stays the default (drawing costs as much again); one facing keeps the item names and table as before.+- **New `sprite-gen handed-check`** checks a still or loop frame by frame: a colour-marked item (`--marker`, a saturated colour nothing else on the character has) must sit on its view's picture side of the body's centre, in one place only, showing in at least half the frames on a near side and, against a `--reference` front or back picture, no more than a sliver on the far side of a side view. `--strap --zone` adds the item's band seen without its marker (a bare strap on the other arm) within the rows it sits in. Specks of the marker's hue left on outlines by a clip's colour blocks are recorded, not judged. `--board` draws every frame with its verdict; exit 1 on a failure. Drawn test figures pass as they should look and fail turned over in every view (`tests/qa/test_handed_check.py`).+- **Fix: a diagonal facing left was filmed heading right.** The diagonal walk and run sentences said "to the right" and "toward the upper right" whatever `--facing` was; they now take the facing ("heading diagonally toward the viewer and to the left"). `video-prompt` and `video-set` also cut a left-facing diagonal's loop with `--facing left` (it was always `right`), which mirrors the jump repair's hair box. Right-facing prompts are unchanged.+## v2.21.0 - A clip made by a video MCP on your agent (ZCRE) becomes a loop: the prompt comes out, the mp4 goes in- **New `sprite-gen video-prompt`** prints the clip prompt `video-set` sends for one (direction, state) — `build_prompt` with `--character`, `--motion` and `--model` — so an agent that makes the clip itself, with a video MCP connected to it, sends the same sentence. `--json` adds the duration (the state's own), whether the clip ends on the canvas (`last_frame`), the loop cut (`cycle`), the canvas, clip, frames and loop steps with placeholders, and for a front or back walk the mid-step redraw (`start_still`). sprite-gen never calls the MCP: the agent uploads the `video-canvas` still, quotes, asks the user, generates and saves the mp4, and `video-frames` and `video-loop` take it from there. [docs/video-pipeline.md](docs/video-pipeline.md#a-clip-from-a-video-mcp-on-your-agent--zcre).diff --git a/README.es.md b/README.es.mdindex 3480833..973156f 100644--- a/README.es.md+++ b/README.es.md@@ -114,6 +114,8 @@ sprite-gen video-set --base side=still.png --states idle,walk,run,jump,attack --¿Generas clips con un MCP de vídeo conectado a tu agente? Con el de ZCRE (지크), el agente crea el clip con tu propia cuenta de ZCRE y sprite-gen lo recorta: `sprite-gen video-prompt --direction side --state walk --no-last-frame` imprime el prompt, y `video-frames` y `video-loop` reciben el mp4. Solo caminar, correr y saltar, porque Grok Imagine 1.5 de ZCRE no tiene fotograma final ([cómo](docs/video-pipeline.md#a-clip-from-a-video-mcp-on-your-agent--zcre)).+¿Un reloj en una sola muñeca o una horquilla en un lado de la cabeza? Al voltear una vista hacia la derecha, el objeto pasa al otro lado, así que dibuja las vistas hacia la izquierda: `sprite-gen gen --direction side --facing left --handed "the black smartwatch=left wrist"` dice dónde está el objeto en esa vista, `video-set --facing right,left --handed …` filma cada vista lateral y diagonal en ambos sentidos desde su propia imagen, y `sprite-gen handed-check` comprueba fotograma a fotograma que un objeto marcado por color está en el lado correcto. Voltear sigue siendo lo predeterminado, porque dibujar las vistas izquierdas cuesta otro tanto ([cómo](docs/video-pipeline.md#handedness--an-item-on-one-side)).+**C · utilidades** — cada una funciona por su cuenta.```bashdiff --git a/README.fr.md b/README.fr.mdindex 29dd3a7..8cbaa68 100644--- a/README.fr.md+++ b/README.fr.md@@ -114,6 +114,8 @@ sprite-gen video-set --base side=still.png --states idle,walk,run,jump,attack --Vous générez vos clips avec un MCP vidéo connecté à votre agent ? Avec celui de ZCRE (지크), l'agent crée le clip sur votre propre compte ZCRE et sprite-gen le découpe : `sprite-gen video-prompt --direction side --state walk --no-last-frame` affiche le prompt, puis `video-frames` et `video-loop` prennent le mp4. Marche, course et saut uniquement, car Grok Imagine 1.5 de ZCRE n'a pas d'image de fin ([comment](docs/video-pipeline.md#a-clip-from-a-video-mcp-on-your-agent--zcre)).+Une montre à un seul poignet, une barrette d'un seul côté de la tête ? Retournée, une vue tournée vers la droite met l'objet de l'autre côté : dessinez donc les vues tournées vers la gauche. `sprite-gen gen --direction side --facing left --handed "the black smartwatch=left wrist"` dit où est l'objet dans cette vue, `video-set --facing right,left --handed …` filme chaque vue de profil et de trois-quarts dans les deux sens à partir de sa propre image, et `sprite-gen handed-check` vérifie image par image qu'un objet marqué par sa couleur est du bon côté. Le retournement reste le défaut, car dessiner les vues de gauche coûte autant une seconde fois ([comment](docs/video-pipeline.md#handedness--an-item-on-one-side)).+**C · utilitaires** — chacun est autonome.```bashdiff --git a/README.ja.md b/README.ja.mdindex 44d2294..31c0b28 100644--- a/README.ja.md+++ b/README.ja.md@@ -114,6 +114,8 @@ sprite-gen video-set --base side=still.png --states idle,walk,run,jump,attack --エージェントに接続した動画 MCP でクリップを作る場合: ZCRE(지크)の MCP なら、エージェントがあなた自身の ZCRE アカウントでクリップを作り、sprite-gen がそれを切り出します。`sprite-gen video-prompt --direction side --state walk --no-last-frame` がプロンプトを出し、`video-frames` と `video-loop` が mp4 を受け取ります。ZCRE の Grok Imagine 1.5 には終了フレームがないため、歩き・走り・ジャンプのみです([手順](docs/video-pipeline.md#a-clip-from-a-video-mcp-on-your-agent--zcre))。+片方の手首の時計や頭の片側のピンのように左右が違うキャラクターなら: 右向きの絵を反転すると小物が反対側に移るので、左向きは別に描きます。`sprite-gen gen --direction side --facing left --handed "the black smartwatch=left wrist"` がその向きで小物がどこにあるかをプロンプトに書き、`video-set --facing right,left --handed …` が横と斜めの向きをそれぞれ描いたスチルから両向き撮り、`sprite-gen handed-check` が色で目印をつけた小物が正しい側にあるかをフレームごとに確かめます。左向きを描くとその分費用がかかるため、既定は今まで通り反転です([手順](docs/video-pipeline.md#handedness--an-item-on-one-side))。+**C · ユーティリティ** — それぞれ単独で動作します。```bashdiff --git a/README.ko.md b/README.ko.mdindex a104869..d7b3f2b 100644--- a/README.ko.md+++ b/README.ko.md@@ -122,6 +122,8 @@ sprite-gen video-set --base side=still.png --states idle,walk,run,jump,attack --에이전트에 연결된 영상 MCP 로 클립을 만든다면: 지크(ZCRE) MCP 로 에이전트가 사용자 본인의 ZCRE 계정에서 클립을 만들고 sprite-gen 이 그 클립을 자른다. `sprite-gen video-prompt --direction side --state walk --no-last-frame` 가 프롬프트를 내고, 받은 mp4 는 `video-frames`·`video-loop` 가 받는다. ZCRE 의 Grok Imagine 1.5 에는 끝 프레임이 없어 걷기·달리기·점프만 된다([방법](docs/video-pipeline.md#a-clip-from-a-video-mcp-on-your-agent--zcre)).+한쪽 손목의 시계, 머리 한쪽의 핀처럼 좌우가 다른 캐릭터라면: 오른쪽을 보는 그림을 뒤집으면 소품이 반대쪽으로 가니 왼쪽을 보는 방향은 따로 그린다. `sprite-gen gen --direction side --facing left --handed "the black smartwatch=left wrist"` 가 그 방향에서 소품이 어디 있는지 문장으로 넣고, `video-set --facing right,left --handed …` 가 옆·대각 방향을 각자 그린 스틸로 양쪽 다 찍으며, `sprite-gen handed-check` 가 색으로 표시된 소품이 맞는 쪽에 있는지 프레임마다 확인한다. 왼쪽을 따로 그리면 그만큼 값이 더 들어 기본은 지금처럼 반전이다([방법](docs/video-pipeline.md#handedness--an-item-on-one-side)).+**C · 유틸리티** — 각각 독립적으로 쓴다.```bashdiff --git a/README.md b/README.mdindex f9565dd..0e2bc10 100644--- a/README.md+++ b/README.md@@ -129,6 +129,8 @@ sprite-gen video-set --base side=still.png --states idle,walk,run,jump,attack --Making clips through a video MCP connected to your agent? With ZCRE's (지크), the agent makes the clip on your own ZCRE account and sprite-gen cuts it: `sprite-gen video-prompt --direction side --state walk --no-last-frame` prints the prompt, then `video-frames` and `video-loop` take the mp4. Walk, run and jump only, because ZCRE's Grok Imagine 1.5 has no end frame ([how](docs/video-pipeline.md#a-clip-from-a-video-mcp-on-your-agent--zcre)).+A watch on one wrist, a pin on one side of the head? Turned over, a right-facing view puts it on the other side, so draw the left-facing views instead: `sprite-gen gen --direction side --facing left --handed "the black smartwatch=left wrist"` says where the item is in that view, `video-set --facing right,left --handed …` films each side and diagonal view both ways from its own still, and `sprite-gen handed-check` checks, frame by frame, that a colour-marked item is on the right side. Mirroring stays the default, since drawing the left views costs as much again ([how](docs/video-pipeline.md#handedness--an-item-on-one-side)).+**C · utilities** — each stands alone.```bashdiff --git a/README.zh-Hans.md b/README.zh-Hans.mdindex f7a669c..39f6ca4 100644--- a/README.zh-Hans.md+++ b/README.zh-Hans.md@@ -114,6 +114,8 @@ sprite-gen video-set --base side=still.png --states idle,walk,run,jump,attack --通过连接到智能体的视频 MCP 生成片段?使用 ZCRE(지크)的 MCP 时,智能体用你自己的 ZCRE 账户生成片段,sprite-gen 负责切割:`sprite-gen video-prompt --direction side --state walk --no-last-frame` 输出提示词,`video-frames` 和 `video-loop` 接收 mp4。ZCRE 的 Grok Imagine 1.5 没有结束帧,因此仅支持行走、奔跑和跳跃([方法](docs/video-pipeline.md#a-clip-from-a-video-mcp-on-your-agent--zcre))。+一只手腕上的手表、头一侧的发夹这类左右不同的角色:把朝右的画面翻转,物件就到了另一侧,所以朝左的方向要单独画。`sprite-gen gen --direction side --facing left --handed "the black smartwatch=left wrist"` 会在提示词里写明该方向下物件的位置,`video-set --facing right,left --handed …` 用各自画好的静帧把侧面和斜向方向两边都拍,`sprite-gen handed-check` 逐帧检查用颜色标记的物件是否在正确一侧。单独画朝左方向要多花同样的费用,所以默认仍是翻转([方法](docs/video-pipeline.md#handedness--an-item-on-one-side))。+**C · 实用工具** —— 每个都可独立使用。```bashdiff --git a/SKILL.md b/SKILL.mdindex 365a535..4625b9d 100644--- a/SKILL.md+++ b/SKILL.md@@ -73,7 +73,8 @@ it never changes the requested direction. Image correction requires explicit opt| `gen --facing` | `preserve` (default), `right`, `left` | With `--ref`, an explicit direction adds a prompt requirement and checks the generated still. || `gen --facing-fix` | `none` (default), `mirror`, `regen` | Record without correction; opt into mirroring an observed opposite or regenerating once and rechecking. A still-opposite regeneration is mirrored. || `video --direction` | `side`, `front`, `back`, `front_diagonal`, `back_diagonal`; unset by default | `side` opts into facing inspection and a matching prompt requirement; the others skip it. The two diagonals are three-quarter views turned right (`VIEW_TEXT`); a walk or run in one is filmed pinned (`pins_last_frame`). |-| `video --facing`, `video-set --facing` | `right` (default), `left` | Required side direction. |+| `video --facing`, `video-set --facing` | `right` (default), `left`; `video-set` also `right,left` | Required side direction. `right,left` films every side and diagonal view both ways, each from its own still (`--base side@left=…`); none is mirrored. |+| `gen --direction`, `--handed`; `video-prompt` / `video-set --handed` | a view; `"<item>=<left\|right> [part]"` | An item on one of the character's own sides: the still and clip prompts say where it is in each view, and mirroring is refused. || `video --facing-fix`, `video-set --facing-fix` | `none` (default), `mirror` | Record the observation; opt into mirroring an observed opposite in a copy. Batch side inspection is enabled by default. |Direction is requested through the generation and motion prompts, which cannot guarantee model compliance.@@ -83,6 +84,10 @@ under `extra.facing`; video reports and batch items use `facing`. `final_directior a value derived from it, not independent verification; `final_direction_source` identifies which.An uncertain or failed inspection records `unknown` and its reason and continues without correction;front-facing observations also remain unchanged. Mirroring does not preserve left/right accessory handedness.+It stays the default, since drawing the left-facing views costs as much again; for a character with a watch on+one wrist or a pin on one side, offer to draw them instead with `--handed` and check them with `handed-check`+(a colour-marked item, frame by frame; `--board` for the eye) —+[handedness](docs/video-pipeline.md#handedness--an-item-on-one-side).## Execution routesdiff --git a/docs/README.md b/docs/README.mdindex 8288745..a32795a 100644--- a/docs/README.md+++ b/docs/README.md@@ -38,7 +38,7 @@ flowchart LR| Pipeline / tool group / workflow | Entry doc | Verbs ||---|---|---|| **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` |+| **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`; `handed-check` for an item on one side || **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`, `compose-layers`, breathing (compose), `export-pngs`, `export-aseprite` || **E · asset tools** — independent background, shadow and motion tools | [asset-tools.md](asset-tools.md) | `background-tile`, `shadow`, `inspect-motion` |diff --git a/docs/gen.md b/docs/gen.mdindex 070030f..bb93d69 100644--- a/docs/gen.md+++ b/docs/gen.md@@ -193,6 +193,8 @@ sprite-gen gen \[--resolution 1k|1.5k|2k] # grok output-size tier, priced with --quality[--model ID] \[--layout-guide] # attach a one-slot layout guide (safe box, crown and floor lines); see below+ [--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[--report REPORT.json] \[--keep-session] # codex: keep the rollout jsonl instead of deleting it```@@ -213,6 +215,12 @@ Backward-compatible wrapper: `$SPRITE_GEN_ROOT/.venv/bin/python $SPRITE_GEN_ROOT(`auth_source`, `transport`, `endpoint`, and the knobs the request actuallycarried).+- **`--direction`** adds the view sentence a sprite still is drawn with (`still_view_text`; a side or+ diagonal view also takes `--facing`, a front or back view refuses it) and records `extra.view`.+ **`--handed`** adds, per item, which of the character's own sides it is on and where that side is in+ the view; with it, `--facing-fix mirror` is refused and `regen` never mirrors. See+ [video-pipeline](video-pipeline.md#handedness--an-item-on-one-side).+## `--quality` and `--resolution` — the two billed knobsThey are one shared vocabulary; what a backend can honour is a per-providerdiff --git a/docs/video-pipeline.md b/docs/video-pipeline.mdindex e8c309d..b5a69ed 100644--- a/docs/video-pipeline.md+++ b/docs/video-pipeline.md@@ -126,7 +126,8 @@ run kept facing away in the one clip whose frames passed; the side walk walked iSince 2.17.0 there are two three-quarter views, `front_diagonal` and `back_diagonal`: turned to theright, the way an isometric game's character walks down and up to the right (turned over, they face-left). A walk or run in one says where it heads on the screen in those words: "walks naturally in+left; a character with an item on one side has them drawn facing left instead, see+[handedness](#handedness--an-item-on-one-side)). A walk or run in one says where it heads on the screen in those words: "walks naturally inplace, as if on a treadmill, heading diagonally away from the viewer toward the upper right, like acharacter walking up and to the right in an isometric game, without moving across the screen. Itkeeps the exact three-quarter back angle of the image the whole time: its back stays turned toward@@ -276,6 +277,86 @@ Measured 2026-10-04, one side walk end to end on that route: a 1024² still, `vi73 frames and no edge contact, and `video-loop --cycle auto` cut a periodic 20-frame walk (seam 0.72)with three frames remade by RIFE and a jolt warning (index 0.85), as a Pro walk can carry.+### Handedness — an item on one side++A watch on one wrist, a pin on one side of the head, a bag on one shoulder: a right-facing view turned+over puts the item on the other side. Mirroring stays the default — five views make eight directions —+because drawing the left-facing views costs as much again. For a character whose item must stay put,+draw them instead, and say where the item is.++**The item, once.** `--handed "<item>=<left|right> [body part]"` names an item and the character's own+side it is on (`handedness.parse`; repeatable): `"the black smartwatch=left wrist"`. The engine works+out where that side is in each view (`handedness.placement`):++| view | own left side, turned right | own left side, turned left |+|---|---|---|+| `front` | the picture's right | (not turned) |+| `back` | the picture's left | (not turned) |+| `side` | the far side, behind the body | the near side, toward the viewer |+| `front_diagonal` | the picture's right, far side | the picture's right, near side |+| `back_diagonal` | the picture's left, far side | the picture's left, near side |++The own right side is the mirror of every row. A side view has no picture side — both arms cross the+middle of the body — only near and far.++**The still.** `sprite-gen gen --direction <view> [--facing right|left] --handed …` adds the engine's+view sentence (`still_view_text`, the one a diagonal or front still is drawn with) and, per item, the+handedness sentence (`handedness.text`): the item is on the own left wrist only and the right wrist has+none; where that wrist is in this view (at the picture's right, on the far side; or, facing right,+behind the body, hidden or a sliver); and that these sentences decide the side whatever an attached+picture shows. A side or diagonal view needs `--facing`, a front or back view takes none. With+`--handed`, `--facing-fix mirror` is refused and `regen` never falls back to mirroring a still-opposite+retry: a mirror moves the item. Do not attach a picture whose item is on the other side — a mirrored+still, or a side picture drawn the wrong way: check it with `handed-check` first. A front or back+picture, where the item's side is plain, is the safe reference.++**The clip.** `video-prompt --handed …` and `video-set --handed …` end the clip prompt with where the+item stays (`build_prompt(handed=...)`). The clip starts from a still already drawn with the item in+place, so the sentence anchors to the image and names the item once, positively, where it shows: "The+black smartwatch stays on the wrist at the right of the picture, nearer the viewer for the whole clip,+exactly as in the image, and on no other wrist." Where the item is hidden — the far side of a side+view — the item is not named at all: "The wrist in front of the body stays bare, exactly as in the+image, for the whole clip." A clip prompt that names a hidden item, and lists what the near arm must+not wear, draws it on the near arm. A far arm that swings into view can still grow a bare band in a+near-side view; holding the arms still (`--motion`) is the caller's choice, and `handed-check --strap`+finds it.++**Left-facing views, drawn.** `video-set --facing right,left` films every side and diagonal view both+ways, each from its own still: `--base side@right=E.png --base side@left=W.png --base+front_diagonal@right=SE.png --base front_diagonal@left=SW.png …` (front and back once, as before). A+turned view with no still for one facing is refused, naming the `gen --direction … --facing …` call+that draws it — the engine never turns one over for the other. Items are named `side-left-walk`, the+table reads `side (left)`, each side still is inspected for its own facing into its own copy+(`side-left.facing.png`), every gait is aligned across all eight (`--align-cycles auto`), and a+left-facing diagonal is canvassed, prompted ("heading diagonally toward the viewer and to the left")+and cut (`video-loop --facing left`) as a left one. One facing keeps the item names and table as before.++**The check.** `sprite-gen handed-check --strip <loop>.strip.png --direction <view> [--facing …]+--handed … --marker '#RRGGBB'` (or `--image`, `--frames-dir`) finds the item by a saturated colour+nothing else on the character has — a watch's screen — and checks every frame:++- a view with a picture side: every blob of that hue is on that side of the body's centre (the mean x+ of its opaque pixels);+- every view: the item in at most one place (blobs within 2 % of the body height are one; one smaller+ than a quarter of the largest is a speck — a clip's colour blocks tint outlines toward the item's+ hue — recorded and drawn, not judged);+- the near side of a side or diagonal view: the item shows in at least half the frames;+- the far side of a side view: no blob larger than half the item seen whole on `--reference` (a keyed+ front or back picture); without one this rule is reported unchecked.++`--strap '#RRGGBB' --zone TOP,BOTTOM` adds the item's band seen without its marker: pixels of that+colour in those rows of the body (fractions of its height), eroded so outlines drop out, wider and+taller than 1.6 % of the body height and away from every marker blob, are another place the item+shows. It is opt-in because dark colours are common — outlines, a hat, motion smear on the legs — and+the zone is the character's wrist height. `--board` draws every frame with its blobs ringed (green as+expected, red not) and bands boxed, for what pixels cannot judge: an unmarked item, an item hidden on+the wrong hand. The exit code is 1 on a failure.++A set that made its left-facing views by mirroring fails: a front view turned over puts the item on+the wrong side; a side view facing right (item hidden on the far arm) turned over hides it on the near+arm; a diagonal turned over moves it across the picture. `tests/qa/test_handed_check.py` draws each+view as it should look, passes it, and fails it turned over.+## 3. Frames — extract, key, check the edges`ffmpeg` extracts every frame; the clip's real fps is recorded (never assumed). Eachdiff --git a/sprite_gen/_modules.py b/sprite_gen/_modules.pyindex bb93bb1..4a9f958 100644--- a/sprite_gen/_modules.py+++ b/sprite_gen/_modules.py@@ -13,6 +13,7 @@ MODULE_DOMAIN = {'tile': 'background','shadow': 'effects','motion': 'qa',+ 'handed': 'qa','render': 'scene','inspect_scene': 'scene','model': 'scene',@@ -89,8 +90,8 @@ DOMAIN_TITLE = dict(DOMAINS)PIPELINES: list[dict[str, object]] = [{"key": "A", "name": "atlas rows", "verbs": ["prepare", "gen", "gen-set", "extract", "compose-atlas", "curation"],"chain": "prepare → gen (or gen-set) → extract → compose-atlas; optional curation and recompose", "doc": "docs/run-contract.md"},- {"key": "B", "name": "video → loop", "verbs": ["video-canvas", "video", "video-prompt", "video-frames", "video-loop", "video-set", "video-cycle-align"],- "chain": "video-canvas → video (or video-prompt + a video MCP) → video-frames → video-loop, or video-set; video-cycle-align across a set", "doc": "docs/video-pipeline.md"},+ {"key": "B", "name": "video → loop", "verbs": ["video-canvas", "video", "video-prompt", "video-frames", "video-loop", "video-set", "video-cycle-align", "handed-check"],+ "chain": "video-canvas → video (or video-prompt + a video MCP) → video-frames → video-loop, or video-set; video-cycle-align across a set; handed-check for an item on one side", "doc": "docs/video-pipeline.md"},]TOOL_GROUPS: list[dict[str, object]] = [diff --git a/sprite_gen/cli.py b/sprite_gen/cli.pyindex 47dcd6c..804b4b9 100644--- a/sprite_gen/cli.py+++ b/sprite_gen/cli.py@@ -12,6 +12,7 @@ from sprite_gen.background import tilefrom sprite_gen.curate import anchorfrom sprite_gen.compose import compose_atlas, compose_cycle, compose_gif, compose_layers, export_aseprite, export_pngsfrom sprite_gen.qa import correction_loop, inspect, preview, score, motion+from sprite_gen.qa import handed as handed_checkfrom sprite_gen.frames import cutout, extract, slice_sheet, unpack_atlasfrom sprite_gen.gen import gen_set, prepare, videofrom sprite_gen.video import batch as video_batch@@ -356,6 +357,12 @@ COMMANDS: dict[str, tuple[str, Callable[[argparse.ArgumentParser], None], Callabvideo_batch.add_arguments,video_batch.run,),+ # Handedness (docs/video-pipeline.md#handedness--an-item-on-one-side): an asymmetric item's side, checked by its colour per frame.+ "handed-check": (+ "Check that a colour-marked asymmetric item (a watch on one wrist) is on the side its handedness puts it in every frame of a still or loop; a board for the eye.",+ handed_check.add_arguments,+ handed_check.run,+ ),"video-cycle-align": ("One cycle length for every direction of a set: resample each loop to the median length (RIFE between source frames only), start on a foot strike.",video_align.add_arguments,diff --git a/sprite_gen/gen/__init__.py b/sprite_gen/gen/__init__.pyindex 4a77c36..90db47e 100644--- a/sprite_gen/gen/__init__.py+++ b/sprite_gen/gen/__init__.py@@ -48,6 +48,7 @@ from sprite_gen.spec.runio import atomic_write_textfrom . import chroma as chroma_modfrom . import facing as facing_mod+from . import handedness as handed_modfrom .base import (QUALITIES,RESOLUTIONS,@@ -325,6 +326,8 @@ def generate_image(refs: list[Path] | None = None,facing: str | None = None,facing_fix: str = "none",+ view: str | None = None,+ handed: list[handed_mod.Handed] | None = None,model: str | None = None,aspect_ratio: str | None = None,quality: str | None = None,@@ -349,12 +352,15 @@ def generate_image(raise SystemExit("gen: empty prompt; pass --prompt or --prompt-file")if facing is not None:facing_mod.validate(facing, facing_fix)+ view_text = _view_text(view, facing, facing_fix, handed)out = out.expanduser().resolve()refs = [Path(r).expanduser().resolve() for r in (refs or [])]for ref in refs:if not ref.is_file():raise SystemExit(f"gen: reference image not found: {ref}")+ if view_text:+ prompt += "\n\n" + view_textif refs and facing is not None:prompt += "\n\n" + facing_mod.prompt_suffix(facing)backend = _make_provider(provider, keep_session=keep_session)@@ -412,7 +418,7 @@ def generate_image(facing_report = Noneif refs and facing is not None:request, run, facing_report = facing_mod.prepare_correction(- backend, request, run, workdir, facing=facing, fix=facing_fix)+ backend, request, run, workdir, facing=facing, fix=facing_fix, mirror_ok=not handed)raw = request.rawraw_bytes = verify_png(raw)@@ -461,6 +467,8 @@ def generate_image(chroma=chroma_stats,extra={**run.extra, **({"trim_alpha": trim_stats} if trim_stats else {}),**({"facing": facing_report} if facing_report else {}),+ **({"view": {"direction": view, "facing": facing if view in handed_mod.LATERAL_VIEWS else None,+ "handed": [vars(h) for h in handed or []]}} if view else {}),**({"layout_guide": guide_cell} if guide_cell else {})},)finally:@@ -468,6 +476,29 @@ def generate_image(shutil.rmtree(workdir, ignore_errors=True)+def _view_text(view: str | None, facing: str | None, facing_fix: str, handed: list[handed_mod.Handed] | None) -> str:+ """`--direction`: the engine's sentence for drawing the still at that view, turned to `facing` (the side+ and diagonal views), then where each `--handed` item is in it (`handedness.text`)."""+ if view is None:+ if handed:+ raise SystemExit("gen: --handed needs --direction: where an item shows depends on the view")+ return ""+ handed_mod.validate_view(view, facing)+ if view not in handed_mod.LATERAL_VIEWS and facing is not None:+ raise SystemExit(f"gen: the {view} view is not turned to a side; drop --facing")+ if handed and facing_fix == "mirror":+ raise SystemExit("gen: --facing-fix mirror turns the picture over and moves every --handed item to the other "+ "side; use regen (it never mirrors with --handed) or none")+ # The view sentences are the video pipeline's (a still is drawn for the clip that starts from it).+ from sprite_gen.video.batch import still_view_text++ text = still_view_text(view, facing or "right")+ text = text[0].upper() + text[1:] + "."+ if handed:+ text += " " + handed_mod.text(handed, view, facing)+ return text++def _run(args: argparse.Namespace) -> int:prompt = args.promptif args.prompt_file:@@ -499,6 +530,8 @@ def _run(args: argparse.Namespace) -> int:refs=args.ref,facing=None if args.facing == "preserve" else args.facing,facing_fix=args.facing_fix,+ view=getattr(args, "direction", None),+ handed=handed_mod.parse_all(list(getattr(args, "handed", None) or [])) or None,model=args.model,aspect_ratio=args.aspect_ratio,quality=args.quality,@@ -625,6 +658,8 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:parser.add_argument("--chroma-key", choices=sorted(chroma_mod.KEYS), default="magenta")parser.add_argument("--facing", choices=(*facing_mod.FACINGS, "preserve"), default="preserve", help="with --ref: required direction; preserve (default) leaves prompt and pixels unchanged")parser.add_argument("--facing-fix", choices=facing_mod.FIXES, default="none", help="with --ref and --facing: record only (none, default), or opt into mirror / one regen")+ parser.add_argument("--direction", choices=handed_mod.VIEWS, help="draw the still at this sprite view: the engine's view sentence is added to the prompt (side and diagonal views also take --facing right|left)")+ parser.add_argument("--handed", action="append", default=[], metavar="ITEM=SIDE [PART]", help="with --direction: an asymmetric item on one of the character's own sides, e.g. 'the black smartwatch=left wrist' (repeatable); the prompt says where it is in this view, and the still is never mirrored")parser.add_argument("--trim-alpha", action="store_true", help="with --transparent: crop the published PNG to its opaque bbox so the bottom edge is the foot line (margins reported)")parser.add_argument("--layout-guide",diff --git a/sprite_gen/gen/facing.py b/sprite_gen/gen/facing.pyindex 1a66041..c58453e 100644--- a/sprite_gen/gen/facing.py+++ b/sprite_gen/gen/facing.py@@ -101,11 +101,13 @@ def inspect(backend, path: Path, workdir: Path) -> dict:return observation-def prepare_correction(backend, request, run, workdir: Path, *, facing: str, fix: str):+def prepare_correction(backend, request, run, workdir: Path, *, facing: str, fix: str, mirror_ok: bool = True):"""Observe raw; recheck one regeneration and mirror a remaining opposite.A non-lateral or failed recheck preserves the regenerated image with anexplicit reason. At most two vision calls and one regeneration are made.+ `mirror_ok=False` (a character with a handed item) never mirrors: a still-opposite+ regeneration is kept as drawn and recorded as unresolved."""observation = inspect(backend, request.raw, workdir)report = {**observation, "requested": facing, "fix": fix, "action": "none",@@ -131,7 +133,9 @@ def prepare_correction(backend, request, run, workdir: Path, *, facing: str, fixfinal_direction_source="regeneration-recheck",regeneration={"model": retry_run.model, "elapsed_seconds": retry_run.elapsed_seconds,"prompt": retry_request.prompt, "extra": retry_run.extra, "recheck": recheck})- if recheck["direction"] == opposite:+ if recheck["direction"] == opposite and not mirror_ok:+ report["reason"] = "regeneration-facing-unresolved:opposite; not mirrored, it would move a handed item"+ elif recheck["direction"] == opposite:report.update(fallback="mirror", final_direction=facing,final_direction_source="mirror-of-recheck")elif recheck["direction"] != facing:diff --git a/sprite_gen/gen/handedness.py b/sprite_gen/gen/handedness.pynew file mode 100644index 0000000..4ed453d--- /dev/null+++ b/sprite_gen/gen/handedness.py@@ -0,0 +1,146 @@+# SPDX-License-Identifier: Apache-2.0+"""Handedness: which of the character's own sides an asymmetric item is on, seen from each view.++A watch on one wrist, a pin on one side of the head, a bag on one shoulder: turned over, the+picture puts the item on the other side. A character like that has its left-facing views drawn,+not mirrored, and each drawing is told where the item goes. The caller names the item and its+side once (`parse`: "the black smartwatch=left wrist"); the engine works out where that side is in+each view (`placement`) and says it in the still and clip prompts (`text`).++Where the character's own left side is, by view and facing (the side view and the three-quarter+views turn to `facing`; front and back have none):++| view | facing right | facing left |+|---|---|---|+| front | the picture's right | (same) |+| back | the picture's left | (same) |+| side | the far side, behind the body | the near side, toward the viewer |+| front_diagonal | the picture's right, on the far side | the picture's right, on the near side |+| back_diagonal | the picture's left, on the far side | the picture's left, on the near side |++A view turned to the right shows the character's right side; turned to the left, its left. The+own right side is the mirror of every row. A side view puts both arms over the middle of the body,+so it has no picture side, only near and far.+"""++from __future__ import annotations++from dataclasses import dataclass++VIEWS = ("side", "front", "back", "front_diagonal", "back_diagonal")+# Views turned toward a side of the picture: each is drawn facing right or left.+LATERAL_VIEWS = frozenset({"side", "front_diagonal", "back_diagonal"})+SIDES = ("left", "right")+SPEC_FORM = "'<item>=<left|right> [body part]', e.g. 'the black smartwatch=left wrist'"+++@dataclass(frozen=True)+class Handed:+ """One asymmetric item: what it is, the character's own side it is on, and where on that side."""++ item: str+ side: str+ part: str = ""++ def where(self, side: str | None = None) -> str:+ side = side or self.side+ return f"{side} {self.part}" if self.part else f"{side} side"++ @property+ def other(self) -> str:+ return "right" if self.side == "left" else "left"+++def parse(spec: str) -> Handed:+ """'<item>=<left|right> [body part]' -> Handed. The side is the character's own, not the picture's."""+ if "=" not in spec:+ raise SystemExit(f"handedness: expected {SPEC_FORM}, got {spec!r}")+ item, rest = (s.strip() for s in spec.rsplit("=", 1))+ words = rest.split()+ if not item or not words or words[0].lower() not in SIDES:+ raise SystemExit(f"handedness: expected {SPEC_FORM}, got {spec!r}")+ return Handed(item=" ".join(item.split()), side=words[0].lower(), part=" ".join(words[1:]))+++def parse_all(specs: list[str] | None) -> list[Handed]:+ return [parse(s) for s in (specs or [])]+++def validate_view(view: str, facing: str | None) -> None:+ if view not in VIEWS:+ raise SystemExit(f"handedness: view must be one of {', '.join(VIEWS)}, got {view!r}")+ if view in LATERAL_VIEWS and facing not in SIDES:+ raise SystemExit(f"handedness: the {view} view is turned right or left; say which (facing right|left)")+++def placement(side: str, view: str, facing: str | None = None) -> dict[str, str | None]:+ """Where the character's own `side` is in `view`: `picture` (left / right of the picture, None in+ a side view) and `depth` (near / far from the viewer, None in a front or back view)."""+ if side not in SIDES:+ raise SystemExit(f"handedness: side must be left or right, got {side!r}")+ validate_view(view, facing)+ flip = {"left": "right", "right": "left"}+ # the own left side; the own right side is its mirror+ picture = {"front": "right", "front_diagonal": "right", "back": "left", "back_diagonal": "left"}.get(view)+ depth = None if view not in LATERAL_VIEWS else ("near" if facing == "left" else "far")+ if side == "right":+ picture = flip[picture] if picture else None+ depth = {"near": "far", "far": "near"}[depth] if depth else None+ return {"picture": picture, "depth": depth}+++def _view_clause(h: Handed, view: str, facing: str | None) -> str:+ at = placement(h.side, view, facing)+ if view == "side":+ if at["depth"] == "near":+ return (f"Facing {facing}, the character's own {h.side} side is toward the viewer: its {h.where()} is the near "+ f"one, in front of the body, and {h.item} on it shows clearly.")+ return (f"Facing {facing}, the character's own {h.other} side is toward the viewer: the near {h.part or 'side'}, in "+ f"front of the body, is its own {h.where(h.other)}, with none; the {h.where()} with {h.item} is on the far "+ f"side, behind the body, so {h.item} is hidden or at most a sliver of it shows.")+ lead = {"front": "Seen from the front", "back": "Seen from behind"}.get(view, "In this view")+ if at["depth"] is None:+ return (f"{lead}, the character's own {h.where()} is the one at the {at['picture']} of the picture, so {h.item} is "+ f"drawn at the {at['picture']} of the picture.")+ near = "nearer the viewer and fully visible" if at["depth"] == "near" else "on the far side of the body"+ other_picture = "left" if at["picture"] == "right" else "right"+ return (f"{lead}, the character's own {h.where()} is the one at the {at['picture']} of the picture, {near}, and it has "+ f"{h.item}; the {h.part or 'side'} at the {other_picture} of the picture is its own {h.where(h.other)}, with none.")+++def _clip_clause(h: Handed, view: str, facing: str | None) -> str:+ """One item in a clip. The clip starts from a still already drawn with the item in place, so the sentence+ anchors to the image and says the item positively, once, where it shows. Where it is hidden (the far side of+ a side view) the item is not named at all, only that the near part stays bare as drawn: a clip prompt that+ names a hidden item, and lists what the near part must not wear, draws it on the near part."""+ at = placement(h.side, view, facing)+ part = h.part or "side"+ if view == "side" and at["depth"] == "far":+ return f"The {part} in front of the body stays bare, exactly as in the image, for the whole clip."+ if view == "side":+ where = f"the {part} in front of the body"+ elif at["depth"] is None:+ where = f"the {part} at the {at['picture']} of the picture"+ else:+ near = "nearer the viewer" if at["depth"] == "near" else "on the far side of the body"+ where = f"the {part} at the {at['picture']} of the picture, {near}"+ item = h.item[0].upper() + h.item[1:]+ return f"{item} stays on {where} for the whole clip, exactly as in the image, and on no other {part}."+++def text(items: list[Handed], view: str, facing: str | None = None, *, clip: bool = False) -> str:+ """The handedness sentences for drawing `view` (a still) or filming it (`clip`). A still: per item, which own+ side it is on and nowhere else, where that side is in this view, and that the sentences outrank a picture.+ A clip: where the item stays, anchored to its first frame (`_clip_clause`)."""+ validate_view(view, facing)+ if clip:+ return " ".join(_clip_clause(h, view, facing) for h in items)+ out = []+ for h in items:+ out.append(f"{h.item[0].upper()}{h.item[1:]} is on the character's own {h.where()} only; the "+ f"{h.where(h.other)} has none, and it never moves to the other side.")+ out.append(_view_clause(h, view, facing))+ if items:+ # a still is often drawn from pictures that disagree with the item's side+ out.append("These sentences decide which side each item is on, whatever an attached picture shows.")+ return " ".join(out)diff --git a/sprite_gen/qa/handed.py b/sprite_gen/qa/handed.pynew file mode 100644index 0000000..485d21a--- /dev/null+++ b/sprite_gen/qa/handed.py@@ -0,0 +1,366 @@+# SPDX-License-Identifier: Apache-2.0+"""`sprite-gen handed-check` — is a colour-marked item on the side its handedness puts it, in every frame?++A still or loop of a character with an asymmetric item (`handedness.parse`: "the black smartwatch=left+wrist") is checked against where that item belongs in the view (`handedness.placement`). The item is+found by its colour: `--marker` is a colour the item has and nothing else on the character has (a+watch's glowing screen, a red ribbon). Per frame, the pixels of that hue are grouped into blobs and+each blob's centre is compared with the body's own centre (the mean x of its opaque pixels):++- a view with a picture side (front, back, the diagonals): every blob must be on that side;+- the item in two places (two blobs farther apart than a link distance, the smaller at least a quarter+ of the larger; smaller ones are specks of compression tint) fails in every view;+- the near side of a side or diagonal view: the item must show in at least half the frames;+- the far side of a side view: the item is hidden or a sliver — no blob may be larger than half the+ item seen whole, measured on `--reference` pictures of the same character (front or back, the item+ in full view). Without a reference this one rule is not checked, and the report says so.++The screen colour cannot see the item's band without its marker — a watch's bare strap on the other arm.+`--strap` names the band's colour (usually dark) and `--zone` the rows the item sits in (black is common:+outlines, a hat, motion smear on the legs); a band of that colour outside every marker blob, wider and+taller than an outline, is another place the item shows. Specks of the marker's hue that a clip's colour+blocks leave on outlines are recorded and not judged.++A picture turned over moves the item: a front view turned over puts it on the wrong side, a side view+facing right (the item on the far arm, hidden) turned over to face left hides it on the near arm. So a+set that made its left-hand views by mirroring fails here (`tests/qa/test_handed_check.py` proves it).+Pixels cannot judge everything — an unmarked item, an item drawn on the wrong hand where it stays hidden —+so `--board` draws every frame with its blobs ringed (green as expected, red not) for a person to look at.+"""++from __future__ import annotations++import argparse+import colorsys+import json+import sys+from collections import deque+from pathlib import Path+from typing import Any++from PIL import Image, ImageDraw++from sprite_gen._deps import np+from sprite_gen.gen import handedness as handed_mod+from sprite_gen.gen.facing import FACINGS+from sprite_gen.spec.runio import atomic_write_text++# Opaque enough to be the character: the body's centre and the marker are read on these pixels.+ALPHA_MIN = 128+# A marker pixel: within HUE_TOL degrees of the marker's hue, at least SAT_MIN saturated (or half the+# marker's own saturation, if that is lower) and at least VAL_MIN bright. A glowing screen keeps its hue+# from its dark edge to its highlight while its brightness changes by half.+HUE_TOL = 20.0+SAT_MIN = 0.45+VAL_MIN = 0.25+# Sizes as fractions of the body's height in the frame: a blob is at least MIN_BLOB_SIDE of it squared,+# and two pieces closer than LINK are one item (an outline or a highlight splits a screen).+MIN_BLOB_SIDE = 0.007+LINK = 0.02+# A blob smaller than this share of the frame's largest is a speck, not a second place: a clip's 4:2:0+# colour blocks tint a white outline or fur edge toward a saturated item's hue, and a strap can cut a+# corner off a screen. Specks are recorded and drawn on the board; they are not judged.+SPECK = 0.25+# A band with no screen (`--strap`): the item's dark band seen without its marker, as when a watch shows+# its bare strap on the other arm. Dark pixels within STRAP_TOL of the strap colour on every channel (a dark+# colour has no hue to match), eroded by STRAP_ERODE of the body height so outlines and thin seams drop out;+# what is left at least STRAP_MIN_SIDE wide and tall, farther than STRAP_GAP from every marker blob, is a+# band of its own: another place the item shows. Black is common (outlines, hair, a hat), so `--zone`+# limits the search to the rows the item sits in.+STRAP_TOL = 55+STRAP_ERODE = 0.004+STRAP_MIN_SIDE = 0.016+STRAP_GAP = 0.024+# At least this share of the frames must show the item on the near side of a side or diagonal view.+NEAR_SHOWN_MIN = 0.5+# On the far side of a side view, a blob larger than this share of the item seen whole is not a sliver.+FAR_MAX = 0.5+++def parse_marker(value: str) -> tuple[int, int, int]:+ text = value.strip().lstrip("#")+ if len(text) != 6:+ raise SystemExit(f"handed-check: --marker is a colour as #RRGGBB, got {value!r}")+ try:+ return int(text[0:2], 16), int(text[2:4], 16), int(text[4:6], 16)+ except ValueError:+ raise SystemExit(f"handed-check: --marker is a colour as #RRGGBB, got {value!r}") from None+++def parse_zone(value: str) -> tuple[float, float]:+ try:+ top, bottom = (float(v) for v in value.split(","))+ except ValueError:+ raise SystemExit(f"handed-check: --zone is TOP,BOTTOM (fractions of the body's height), got {value!r}") from None+ return top, bottom+++def marker_mask(rgba: np.ndarray, marker: tuple[int, int, int], hue_tol: float = HUE_TOL) -> np.ndarray:+ """Opaque pixels of the marker's hue (`HUE_TOL`, `SAT_MIN`, `VAL_MIN`)."""+ mh, ms, _ = colorsys.rgb_to_hsv(*(c / 255 for c in marker))+ if ms < 0.2:+ raise SystemExit("handed-check: --marker must be a saturated colour (a grey, white or black item cannot be told "+ "apart from shading); check that item on the --board by eye")+ rgb = rgba[..., :3].astype(np.float32) / 255+ mx, mn = rgb.max(-1), rgb.min(-1)+ delta = mx - mn+ sat = np.where(mx > 0, delta / np.maximum(mx, 1e-6), 0)+ r, g, b = rgb[..., 0], rgb[..., 1], rgb[..., 2]+ d = np.maximum(delta, 1e-6)+ hue = np.where(mx == r, ((g - b) / d) % 6, np.where(mx == g, (b - r) / d + 2, (r - g) / d + 4)) / 6+ diff = np.abs(hue - mh)+ diff = np.minimum(diff, 1 - diff) * 360+ return (rgba[..., 3] >= ALPHA_MIN) & (diff <= hue_tol) & (sat >= min(SAT_MIN, ms / 2)) & (mx >= VAL_MIN)+++def blobs(mask: np.ndarray, *, link: int, min_area: int) -> list[dict[str, Any]]:+ """Marker pixels grouped into items: pixels within `link` px of each other are one item."""+ ys, xs = np.nonzero(mask)+ pixels = set(zip(ys.tolist(), xs.tolist()))+ offsets = [(dy, dx) for dy in range(-link, link + 1) for dx in range(-link, link + 1) if dy * dy + dx * dx <= link * link]+ out = []+ while pixels:+ seed = pixels.pop()+ queue, members = deque([seed]), [seed]+ while queue:+ y, x = queue.popleft()+ for dy, dx in offsets:+ p = (y + dy, x + dx)+ if p in pixels:+ pixels.remove(p)+ queue.append(p)+ members.append(p)+ if len(members) >= min_area:+ a = np.array(members)+ out.append({"area": len(members), "x": round(float(a[:, 1].mean()), 1), "y": round(float(a[:, 0].mean()), 1),+ "box": [int(a[:, 1].min()), int(a[:, 0].min()), int(a[:, 1].max()), int(a[:, 0].max())]})+ return sorted(out, key=lambda b: -b["area"])+++def erode(mask: np.ndarray, r: int) -> np.ndarray:+ out = mask.copy()+ padded = np.pad(mask, r)+ h, w = mask.shape+ for dy in range(-r, r + 1):+ for dx in range(-r, r + 1):+ out &= padded[r + dy:r + dy + h, r + dx:r + dx + w]+ return out+++def _gap(a: list[int], b: list[int]) -> int:+ return max(a[0] - b[2], b[0] - a[2], a[1] - b[3], b[1] - a[3], 0)+++def measure(image: Image.Image, marker: tuple[int, int, int], *, strap: tuple[int, int, int] | None = None,+ zone: tuple[float, float] = (0.0, 1.0)) -> dict[str, Any]:+ """The body (opaque pixels), the marker blobs and, with `strap`, the bands without a marker of one frame.+ Only the rows in `zone` (fractions of the body's height from its top) are searched."""+ rgba = np.array(image.convert("RGBA"))+ body = rgba[..., 3] >= ALPHA_MIN+ if not body.any():+ raise SystemExit("handed-check: a frame has no opaque pixels")+ if body.all():+ raise SystemExit("handed-check: a frame has no transparent pixels — check keyed frames (video-frames, cutout or "+ "gen --transparent), so the body's centre is the body's")+ ys, xs = np.nonzero(body)+ height = int(ys.max() - ys.min() + 1)+ rows = np.zeros_like(body)+ rows[int(ys.min() + zone[0] * height):int(ys.min() + zone[1] * height) + 1] = True+ found = blobs(marker_mask(rgba, marker) & rows, link=max(2, round(LINK * height)),+ min_area=max(4, round((MIN_BLOB_SIDE * height) ** 2)))+ keep = [b for b in found if b["area"] >= SPECK * found[0]["area"]] if found else []+ straps = []+ if strap is not None:+ near = np.abs(rgba[..., :3].astype(int) - np.array(strap)).max(-1) <= STRAP_TOL+ dark = erode((rgba[..., 3] >= ALPHA_MIN) & near & rows, max(1, round(STRAP_ERODE * height)))+ side, gap = STRAP_MIN_SIDE * height, STRAP_GAP * height+ straps = [b for b in blobs(dark, link=max(2, round(STRAP_ERODE * height)), min_area=4)+ if b["box"][2] - b["box"][0] + 1 >= side and b["box"][3] - b["box"][1] + 1 >= side+ and all(_gap(b["box"], m["box"]) > gap for m in found)]+ return {"body_area": int(body.sum()), "body_height": height, "centre_x": round(float(xs.mean()), 1), "blobs": keep,+ "specks": [b for b in found if b not in keep], "straps": straps}+++def full_ratio(references: list[Image.Image], marker: tuple[int, int, int],+ zone: tuple[float, float] = (0.0, 1.0)) -> float | None:+ """The item seen whole, as a share of the body's area: the median of the largest blob in each reference."""+ ratios = []+ for ref in references:+ m = measure(ref, marker, zone=zone)+ if m["blobs"]:+ ratios.append(m["blobs"][0]["area"] / m["body_area"])+ if references and not ratios:+ raise SystemExit("handed-check: no --reference shows the marker; pass a front or back picture with the item in full view")+ return float(np.median(ratios)) if ratios else None+++def check(frames: list[Image.Image], *, item: handed_mod.Handed, view: str, facing: str | None,+ marker: tuple[int, int, int], references: list[Image.Image] | None = None,+ strap: tuple[int, int, int] | None = None, zone: tuple[float, float] = (0.0, 1.0)) -> dict[str, Any]:+ """Every frame against `handedness.placement(item.side, view, facing)`; `ok` is the verdict. With `strap`,+ a band without its marker counts as a place the item shows (`STRAP_TOL`)."""+ if not 0 <= zone[0] < zone[1] <= 1:+ raise SystemExit(f"handed-check: --zone is TOP,BOTTOM as fractions of the body's height, 0 <= TOP < BOTTOM <= 1, got {zone}")+ if not frames:+ raise SystemExit("handed-check: no frames")+ if view not in handed_mod.LATERAL_VIEWS:+ facing = None+ expect = handed_mod.placement(item.side, view, facing)+ full = full_ratio(references or [], marker, zone)+ rows, fails = [], []+ for i, frame in enumerate(frames):+ m = measure(frame, marker, strap=strap, zone=zone)+ bad = []+ places = len(m["blobs"]) + len(m["straps"])+ if places > 1:+ bare = f" ({len(m['straps'])} a band without its marker)" if m["straps"] else ""+ bad.append(f"the item shows in {places} places{bare}")+ for b in m["straps"]:+ b["side"] = "right" if b["x"] > m["centre_x"] else "left"+ if expect["picture"] and b["side"] != expect["picture"]:+ bad.append(f"a band without its marker on the picture's {b['side']}, expected its {expect['picture']}")+ for b in m["blobs"]:+ b["side"] = "right" if b["x"] > m["centre_x"] else "left"+ b["ratio"] = round(b["area"] / m["body_area"], 6)+ if expect["picture"] and b["side"] != expect["picture"]:+ bad.append(f"on the picture's {b['side']}, expected its {expect['picture']}")+ if view == "side" and expect["depth"] == "far" and full is not None and b["ratio"] > FAR_MAX * full:+ bad.append(f"in full view ({b['ratio'] / full:.0%} of the whole item) on the far side")+ rows.append({**m, "bad": bad})+ if bad:+ fails.append({"frame": i, "why": bad})+ shown = sum(1 for r in rows if r["blobs"])+ rules: dict[str, Any] = {}+ if expect["picture"]:+ rules["picture_side"] = expect["picture"]+ if expect["depth"] == "near":+ rules["near_shown"] = {"min": NEAR_SHOWN_MIN, "shown": shown, "frames": len(rows),+ "ok": shown >= NEAR_SHOWN_MIN * len(rows)}+ if view == "side" and expect["depth"] == "far":+ rules["far_hidden"] = ({"checked": False, "why": "no --reference: the item seen whole is unknown"} if full is None+ else {"checked": True, "full_ratio": round(full, 6), "max": FAR_MAX})+ ok = not fails and rules.get("near_shown", {}).get("ok", True)+ return {+ "kind": "sprite-gen-handed-check",+ "item": vars(item), "view": view, "facing": facing, "expect": expect,+ "marker": "#%02x%02x%02x" % marker, **({"strap": "#%02x%02x%02x" % strap} if strap else {}),+ "zone": list(zone), "rules": rules,+ "frames": len(rows), "frames_shown": shown, "fails": fails, "ok": bool(ok),+ "per_frame": [{k: r[k] for k in ("centre_x", "body_area", "blobs", "specks", "straps", "bad")} for r in rows],+ }+++def board(frames: list[Image.Image], report: dict[str, Any], out: Path, *, height: int = 240) -> Path:+ """Every frame on a light ground, its blobs ringed (green as expected, red not), the verdict on top."""+ cells = []+ for frame, row in zip(frames, report["per_frame"]):+ k = height / frame.height+ cell = Image.new("RGBA", frame.size, (236, 236, 236, 255))+ cell.alpha_composite(frame.convert("RGBA"))+ cell = cell.convert("RGB").resize((max(1, round(frame.width * k)), height), Image.LANCZOS)+ draw = ImageDraw.Draw(cell)+ colour = (200, 0, 0) if row["bad"] else (0, 160, 0)+ for b in row["blobs"]:+ x0, y0, x1, y1 = (c * k for c in b["box"])+ draw.ellipse((x0 - 8, y0 - 8, x1 + 8, y1 + 8), outline=colour, width=3)+ for b in row["straps"]:+ x0, y0, x1, y1 = (c * k for c in b["box"])+ draw.rectangle((x0 - 6, y0 - 6, x1 + 6, y1 + 6), outline=(230, 120, 0), width=3)+ for b in row["specks"]:+ x0, y0, x1, y1 = (c * k for c in b["box"])+ draw.rectangle((x0 - 4, y0 - 4, x1 + 4, y1 + 4), outline=(150, 150, 150), width=1)+ cx = row["centre_x"] * k+ draw.line((cx, 0, cx, 10), fill=(110, 110, 110), width=2)+ cells.append(cell)+ head = 34+ width = sum(c.width for c in cells)+ sheet = Image.new("RGB", (max(width, 480), height + head), (250, 250, 250))+ draw = ImageDraw.Draw(sheet)+ e = report["expect"]+ where = ", ".join(f"{k} {v}" for k, v in (("picture", e["picture"]), ("depth", e["depth"])) if v)+ verdict = "PASS" if report["ok"] else f"FAIL ({len(report['fails'])} frame(s))"+ draw.text((8, 10), f"{report['view']}{' ' + report['facing'] if report['facing'] else ''} | {report['item']['item']} = "+ f"own {report['item']['side']} | expect {where} | shown {report['frames_shown']}/{report['frames']} | {verdict}",+ fill=(0, 120, 0) if report["ok"] else (190, 0, 0))+ x = 0+ for cell in cells:+ sheet.paste(cell, (x, head))+ x += cell.width+ out.parent.mkdir(parents=True, exist_ok=True)+ sheet.save(out)+ return out+++def load_frames(*, images: list[Path], frames_dir: Path | None, strip: Path | None) -> list[Image.Image]:+ """Frames from still or frame PNGs, a folder of PNGs (name order), or a loop strip with its `.strip.json`."""+ given = sum(bool(x) for x in (images, frames_dir, strip))+ if given != 1:+ raise SystemExit("handed-check: give one of --image (repeatable), --frames-dir or --strip")+ if strip:+ meta_path = strip.with_name(strip.name.replace(".strip.png", ".strip.json"))+ if not meta_path.is_file():+ raise SystemExit(f"handed-check: {strip} has no {meta_path.name} beside it (video-loop writes both)")+ meta = json.loads(meta_path.read_text(encoding="utf-8"))+ with Image.open(strip) as im:+ sheet = im.convert("RGBA")+ w, h = int(meta["w"]), int(meta["h"])+ return [sheet.crop((i * w, 0, (i + 1) * w, h)) for i in range(int(meta["frames"]))]+ paths = sorted(frames_dir.glob("*.png")) if frames_dir else images+ if not paths:+ raise SystemExit(f"handed-check: no PNG frames in {frames_dir}")+ out = []+ for p in paths:+ with Image.open(p) as im:+ out.append(im.convert("RGBA"))+ return out+++def add_arguments(parser: argparse.ArgumentParser) -> None:+ parser.add_argument("--image", action="append", type=Path, default=[], help="a keyed still or frame PNG (repeatable)")+ parser.add_argument("--frames-dir", type=Path, help="a folder of keyed frame PNGs (video-frames' keyed/)")+ parser.add_argument("--strip", type=Path, help="a loop strip (<name>.strip.png, with its .strip.json beside it)")+ parser.add_argument("--direction", required=True, choices=handed_mod.VIEWS, help="the view the frames are drawn in")+ parser.add_argument("--facing", choices=FACINGS, help="side and diagonal views: which way they face")+ parser.add_argument("--handed", required=True, metavar="ITEM=SIDE [PART]", help="the item and the character's own side it is on, e.g. 'the black smartwatch=left wrist'")+ parser.add_argument("--marker", required=True, help="#RRGGBB: a saturated colour of the item that nothing else on the character has")+ parser.add_argument("--strap", help="#RRGGBB: the item's band colour (a watch strap, usually dark); a band of it with no marker on it, away from the marker, counts as another place the item shows. Use with --zone")+ parser.add_argument("--zone", default="0,1", help="TOP,BOTTOM: the rows the item sits in, as fractions of the body's height from its top (default 0,1, the whole body); e.g. 0.5,0.9 for a wrist")+ parser.add_argument("--reference", action="append", type=Path, default=[], help="a keyed front or back picture of the same character with the item in full view (repeatable): a side view's far item must stay smaller than half of it")+ parser.add_argument("--report", type=Path, help="write the report JSON here")+ parser.add_argument("--board", type=Path, help="write the review board PNG here")+++def run(**kwargs: object) -> int:+ frames = load_frames(images=list(kwargs.get("image") or []), frames_dir=kwargs.get("frames_dir"), # type: ignore[arg-type]+ strip=kwargs.get("strip")) # type: ignore[arg-type]+ references = load_frames(images=list(kwargs.get("reference") or []), frames_dir=None, strip=None) if kwargs.get("reference") else []+ report = check(frames, item=handed_mod.parse(str(kwargs["handed"])), view=str(kwargs["direction"]),+ facing=kwargs.get("facing"), marker=parse_marker(str(kwargs["marker"])), references=references, # type: ignore[arg-type]+ strap=parse_marker(str(kwargs["strap"])) if kwargs.get("strap") else None,+ zone=parse_zone(str(kwargs.get("zone") or "0,1")))+ if kwargs.get("board"):+ report["board"] = str(board(frames, report, Path(str(kwargs["board"]))))+ if kwargs.get("report"):+ atomic_write_text(Path(str(kwargs["report"])), json.dumps(report, ensure_ascii=False, indent=2) + "\n")+ summary = {k: report[k] for k in ("view", "facing", "expect", "frames", "frames_shown", "ok")}+ summary["fails"] = len(report["fails"])+ if report["rules"].get("far_hidden", {}).get("checked") is False:+ summary["unchecked"] = report["rules"]["far_hidden"]["why"]+ print(json.dumps(summary, ensure_ascii=False))+ if not report["ok"]:+ for f in report["fails"][:10]:+ print(f"handed-check: frame {f['frame']}: {'; '.join(f['why'])}", file=sys.stderr)+ if report["rules"].get("near_shown", {}).get("ok") is False:+ r = report["rules"]["near_shown"]+ print(f"handed-check: on the near side the item shows in {r['shown']} of {r['frames']} frames", file=sys.stderr)+ return 0 if report["ok"] else 1+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(prog="sprite-gen handed-check", description=__doc__)+ add_arguments(parser)+ return run(**vars(parser.parse_args(argv)))+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/sprite_gen/video/batch.py b/sprite_gen/video/batch.pyindex dff933f..a0ee573 100644--- a/sprite_gen/video/batch.py+++ b/sprite_gen/video/batch.py@@ -26,6 +26,8 @@ from PIL import Imagefrom sprite_gen.spec.runio import atomic_write_textfrom sprite_gen.gen.facing import FACINGS, validate as validate_facing+from sprite_gen.gen import handedness as handed_mod+from sprite_gen.gen.handedness import Handedfrom sprite_gen.video import facing as facing_modfrom sprite_gen.video import canvas as canvas_modfrom sprite_gen.video import frames as frames_mod@@ -177,26 +179,27 @@ VIEW_MOTION_TEXT = {# A diagonal says where the character is heading on the screen, the way an isometric game reads, and that it# keeps the image's angle. Asked only to walk "toward the way its body faces in the image", a three-quarter# back walk turned to a side view in 2 of 2 clips; named as a heading up and to the right, in 10 of 10 it- # kept the angle (2026-10-02, five people twice each, pinned).+ # kept the angle (2026-10-02, five people twice each, pinned). `{facing}` is the way the view is turned: a+ # view drawn facing left heads down or up and to the left (it said "to the right" whatever the facing).("walk", "front_diagonal"): (- "walks naturally in place, as if on a treadmill, heading diagonally toward the viewer and to the right, like a "- "character walking down and to the right in an isometric game, without moving across the screen. It keeps the "+ "walks naturally in place, as if on a treadmill, heading diagonally toward the viewer and to the {facing}, like a "+ "character walking down and to the {facing} in an isometric game, without moving across the screen. It keeps the ""exact three-quarter front angle of the image the whole time and never turns into a side view."),("walk", "back_diagonal"): (- "walks naturally in place, as if on a treadmill, heading diagonally away from the viewer toward the upper right, "- "like a character walking up and to the right in an isometric game, without moving across the screen. It keeps "+ "walks naturally in place, as if on a treadmill, heading diagonally away from the viewer toward the upper {facing}, "+ "like a character walking up and to the {facing} in an isometric game, without moving across the screen. It keeps ""the exact three-quarter back angle of the image the whole time: its back stays turned toward the viewer at that ""angle and its face stays hidden. It never turns into a side view."),("run", "front_diagonal"): (- "runs naturally in place, as if on a treadmill, heading diagonally toward the viewer and to the right, like a "- "character running down and to the right in an isometric game, without moving across the screen. It keeps the "+ "runs naturally in place, as if on a treadmill, heading diagonally toward the viewer and to the {facing}, like a "+ "character running down and to the {facing} in an isometric game, without moving across the screen. It keeps the ""exact three-quarter front angle of the image the whole time and never turns into a side view."),("run", "back_diagonal"): (- "runs naturally in place, as if on a treadmill, heading diagonally away from the viewer toward the upper right, "- "like a character running up and to the right in an isometric game, without moving across the screen. It keeps "+ "runs naturally in place, as if on a treadmill, heading diagonally away from the viewer toward the upper {facing}, "+ "like a character running up and to the {facing} in an isometric game, without moving across the screen. It keeps ""the exact three-quarter back angle of the image the whole time: its back stays turned toward the viewer at that ""angle and its face stays hidden. It never turns into a side view."),@@ -273,7 +276,7 @@ def _staggered_start(gap: float) -> None:def build_prompt(direction: str, state: str, character: str | None, facing: str = "right", motion: str | None = None,- pinned: bool | None = None, model: str | None = None) -> str:+ pinned: bool | None = None, model: str | None = None, handed: list[Handed] | None = None) -> str:"""The clip prompt for one (direction, state).`motion` replaces the built-in state sentence with the caller's own description of the@@ -290,6 +293,9 @@ def build_prompt(direction: str, state: str, character: str | None, facing: str`model` is the clip model the prompt is for. A Lite walk (`LITE_VIDEO_MODELS`) gets the calmingclause after the built-in walk sentence (`LITE_WALK_TEXT`; a caller's own motion is left aswritten), and a Lite walk in a view where its head sways gets `LITE_HEAD_TEXT`.++ `handed` lists the character's asymmetric items (`handedness.parse`): the prompt ends with where each+ one stays, anchored to the first frame and never named where it is hidden (`handedness.text(clip=True)`)."""validate_facing(facing)view = VIEW_TEXT.get(direction, f"seen from the {direction}").format(facing=facing)@@ -309,11 +315,20 @@ def build_prompt(direction: str, state: str, character: str | None, facing: strhold += f" {GAIT_HOLD_TEXT[direction].format(facing=facing)}"repeat = f" {REPEAT_TEXT[state]}" if state in REPEAT_TEXT else ""subject = character.strip().rstrip(".") if character else "The character"- return f"2D game sprite animation. {motion}{hold}{repeat} {subject} is {view}." + template[len(head):] + _lite_text(state, direction, model, built_in=False)- built_in = VIEW_MOTION_TEXT.get((state, direction)) or MOTION_TEXT.get(- state, f"performs the '{state}' action in place, repeating at an even rhythm.")+ return (f"2D game sprite animation. {motion}{hold}{repeat} {subject} is {view}." + template[len(head):]+ + _lite_text(state, direction, model, built_in=False) + _handed_text(handed, direction, facing))+ built_in = (VIEW_MOTION_TEXT[(state, direction)].format(facing=facing) if (state, direction) in VIEW_MOTION_TEXT+ else MOTION_TEXT.get(state, f"performs the '{state}' action in place, repeating at an even rhythm."))text = template.format(motion=built_in, view=view)- return (text.replace("The character", character, 1) if character else text) + _lite_text(state, direction, model, built_in=True)+ return ((text.replace("The character", character, 1) if character else text)+ + _lite_text(state, direction, model, built_in=True) + _handed_text(handed, direction, facing))+++def _handed_text(handed: list[Handed] | None, direction: str, facing: str) -> str:+ """Where each asymmetric item is in this view, said last (`handedness.text`); nothing without one."""+ if not handed:+ return ""+ return " " + handed_mod.text(handed, direction, facing if direction in handed_mod.LATERAL_VIEWS else None, clip=True)def _lite_text(state: str, direction: str, model: str | None, *, built_in: bool) -> str:@@ -445,6 +460,7 @@ def run_item(walk_start: str = "redraw",redraw_runner: Callable[..., int] = run_redraw_cli,still_provider: str | None = None,+ handed: list[Handed] | None = None,) -> dict[str, Any]:if walk_start not in WALK_START_MODES:raise SystemExit(f"video-set: --walk-start must be one of {', '.join(WALK_START_MODES)}")@@ -455,12 +471,15 @@ def run_item(validate_facing(facing, facing_fix)if facing_fix not in facing_mod.FIXES:raise SystemExit("video-set: --facing-fix must be mirror or none")+ _refuse_mirror_with_handed(facing_fix, handed)duration = duration_for(state, duration)item_dir = root / itemitem_dir.mkdir(parents=True, exist_ok=True)result: dict[str, Any] = {"item": item, "direction": direction, "state": state, "dir": str(item_dir)}+ if direction in handed_mod.LATERAL_VIEWS:+ result["turned"] = facingtry:- prompt = build_prompt(direction, state, character, facing=facing)+ prompt = build_prompt(direction, state, character, facing=facing, handed=handed)clip = item_dir / "clip.mp4"clip_report = item_dir / "clip.report.json"reuse_clip = clip.exists() and clip_report.exists() and not force@@ -539,7 +558,7 @@ def run_item(result["frames"]["spill"] = fr.get("spill", {}).get("mode")lp = loop_mod.run_loop(Path(fr["keyed_dir"]), item_dir / "loop", fps=float(fr["fps"]), state=state, min_len=None, max_len=None, n_out=None, seam_max=loop_mod.SEAM_RATIO_MAX, name=item, report_path=item_dir / "loop.report.json", anchor=anchor, body_height=body_height,cycle_mode="pinned" if state in PINNED_LOOP_STATES else "auto",- facing=facing if direction == "side" else "right")+ facing=facing if direction in handed_mod.LATERAL_VIEWS else "right")result["loop"] = {"kind": lp["cycle"].get("kind", "periodic"), "cycle": lp["cycle"]["length"], "period": lp["cycle"]["period_global"], "cycle_ratio": round(lp["cycle"]["ratio"], 3), "seam_ratio": lp["resampled_seam_ratio"], "n_out": lp["n_out"], "drift_px": lp["strip"].get("drift_px", 0), "gif": lp["gif"]["file"], "webp": lp["webp"]["file"], "strip": lp["strip"]["path"]}result["loop"]["review_recommended"] = lp["cycle"].get("review_recommended", False)result["loop"]["half_period_guard"] = lp["cycle"].get("half_period_guard")@@ -555,6 +574,53 @@ def run_item(return result+def _refuse_mirror_with_handed(facing_fix: str, handed: list[Handed] | None) -> None:+ if handed and facing_fix == "mirror":+ raise SystemExit("video-set: --facing-fix mirror turns the picture over and moves every --handed item to the "+ "other side; draw the still facing the requested way instead (docs/video-pipeline.md#handedness--an-item-on-one-side)")+++def facings_of(facing: str) -> tuple[str, ...]:+ """`--facing`: right, left, or both as `right,left` — every lateral view is then filmed both ways."""+ out = tuple(dict.fromkeys(f.strip() for f in str(facing).split(",") if f.strip()))+ if not out or any(f not in FACINGS for f in out):+ raise SystemExit(f"video-set: --facing must be right, left or right,left, got {facing!r}")+ return out+++def resolve_bases(bases: dict[str, Path], facings: tuple[str, ...]) -> list[tuple[str, str | None, Path]]:+ """`--base` keys -> (direction, facing, still). A lateral view (`handedness.LATERAL_VIEWS`) takes the set's+ facing, or `view@facing` names it; filmed both ways, every lateral view needs a still for each facing, drawn+ that way: the engine never turns one over for the other. Front and back have no facing."""+ out: list[tuple[str, str | None, Path]] = []+ for key, path in bases.items():+ direction, _, named = key.partition("@")+ if direction not in VIEW_TEXT:+ raise SystemExit(f"video-set: --base direction must be one of {', '.join(sorted(VIEW_TEXT))}, got {direction!r}")+ if direction not in handed_mod.LATERAL_VIEWS:+ if named:+ raise SystemExit(f"video-set: the {direction} view is not turned to a side; drop @{named}")+ out.append((direction, None, path))+ elif named:+ if named not in facings:+ raise SystemExit(f"video-set: --base {key} faces {named}, and the set is filmed facing {','.join(facings)}")+ out.append((direction, named, path))+ elif len(facings) > 1:+ raise SystemExit(f"video-set: filmed facing right and left, the {direction} view needs a still for each: "+ f"--base {direction}@right=… --base {direction}@left=…")+ else:+ out.append((direction, facings[0], path))+ seen = [(d, f) for d, f, _ in out]+ if len(set(seen)) != len(seen):+ raise SystemExit("video-set: a direction is given twice for the same facing")+ for d in {d for d, f, _ in out if f is not None}:+ missing = [f for f in facings if (d, f) not in seen]+ if missing:+ raise SystemExit(f"video-set: the {d} view has no still facing {missing[0]} (--base {d}@{missing[0]}=…); draw "+ f"it that way (gen --direction {d} --facing {missing[0]}) — the engine does not mirror one")+ return out++ALIGN_MODES = ("auto", "off")@@ -595,7 +661,12 @@ def align_gaits(results: list[dict[str, Any]], root: Path, mode: str, *, interporeturn out-def write_table(results: list[dict[str, Any]], path: Path) -> str:+def _view_label(r: dict[str, Any], both: bool) -> str:+ return f"{r['direction']} ({r['turned']})" if both and r.get("turned") else r["direction"]+++def write_table(results: list[dict[str, Any]], path: Path, *, both: bool = False) -> str:+ """`both`: the set is filmed facing right and left, so a lateral view's row names its facing."""lines = ["| direction | state | kind | cycle | period | seam | frames | status |", "|---|---|---|---|---|---|---|---|"]for r in results:if r.get("ok"):@@ -605,9 +676,9 @@ def write_table(results: list[dict[str, Any]], path: Path) -> str:status = "OK (uncorrected; review gait)"if "jump_repair" in lp:status += " (jump not repaired: no RIFE)"- lines.append(f"| {r['direction']} | {r['state']} | {lp.get('kind', 'periodic')} | {lp['cycle']} | {lp['period'] if lp['period'] is not None else '-'} | {lp['seam_ratio']:.2f} | {lp['n_out']} | {status} |")+ lines.append(f"| {_view_label(r, both)} | {r['state']} | {lp.get('kind', 'periodic')} | {lp['cycle']} | {lp['period'] if lp['period'] is not None else '-'} | {lp['seam_ratio']:.2f} | {lp['n_out']} | {status} |")else:- lines.append(f"| {r['direction']} | {r['state']} | - | - | - | - | - | FAIL: {r.get('error', '')[:80]} |")+ lines.append(f"| {_view_label(r, both)} | {r['state']} | - | - | - | - | - | FAIL: {r.get('error', '')[:80]} |")text = "\n".join(lines) + "\n"atomic_write_text(path, text)return text@@ -639,54 +710,65 @@ def run_set(walk_start: str = "redraw",redraw_runner: Callable[..., int] = run_redraw_cli,still_provider: str | None = None,+ handed: list[Handed] | None = None,) -> dict[str, Any]:+ """`bases` maps a view to its still; `facing` is right, left or `right,left` (`facings_of`), and a view filmed+ both ways is keyed `view@right` and `view@left` (`resolve_bases`). `handed` (`handedness.parse`) puts each+ asymmetric item's side into every clip prompt; it refuses `facing_fix` mirror, which would move it."""if align_cycles not in ALIGN_MODES:raise SystemExit(f"video-set: --align-cycles must be one of {', '.join(ALIGN_MODES)}")if anchor == "motion-auto" and any(not loop_mod.profile_for(state).gait for state in states):raise SystemExit("video-set: --anchor motion-auto requires walk/run states")if anchor == "motion":raise SystemExit("video-set: motion anchor requires reviewed regions; use video-loop --cycle fixed")- validate_facing(facing, facing_fix)+ facings = facings_of(facing)+ validate_facing(facings[0], facing_fix)if facing_fix not in facing_mod.FIXES:raise SystemExit("video-set: --facing-fix must be mirror or none")+ _refuse_mirror_with_handed(facing_fix, handed)if fit == "tight" and shape is not None:raise SystemExit("video-set: --fit tight picks each canvas's shape itself; drop --shape")root = root.expanduser().resolve()root.mkdir(parents=True, exist_ok=True)- for direction, base in bases.items():+ views = resolve_bases(bases, facings)+ both = len(facings) > 1+ for direction, turned, base in views:if not base.is_file():raise SystemExit(f"video-set: base still for '{direction}' not found: {base}")- items = [(f"{d}-{s}", d, s) for d in bases for s in states]+ # (item, direction, state, facing, base); a set filmed both ways names a lateral item's facing+ items = [(f"{d}-{f}-{s}" if both and f else f"{d}-{s}", d, s, f or facings[0], b) for d, f, b in views for s in states]results: list[dict[str, Any]] = []# States share a base. A run-local lock ensures exactly one vision call per- # side still, even when several state workers reach it together.- prepared: dict[Path, tuple[Path, dict]] = {}+ # side still and facing, even when several state workers reach it together.+ prepared: dict[tuple[Path, str], tuple[Path, dict]] = {}prepare_lock = threading.Lock()- def prepare_side(base: Path) -> tuple[Path, dict]:- with prepare_lock:- if base not in prepared:- corrected = root / "side.facing.png"- report = facing_mod.prepare_still(base, corrected, facing=facing, fix=facing_fix)- prepared[base] = (corrected, report)- return prepared[base]+ def side_preparer(turned: str) -> Callable[[Path], tuple[Path, dict]]:+ def prepare_side(base: Path) -> tuple[Path, dict]:+ with prepare_lock:+ if (base, turned) not in prepared:+ corrected = root / (f"side-{turned}.facing.png" if both else "side.facing.png")+ report = facing_mod.prepare_still(base, corrected, facing=turned, fix=facing_fix)+ prepared[(base, turned)] = (corrected, report)+ return prepared[(base, turned)]+ return prepare_sidewith ThreadPoolExecutor(max_workers=max(1, concurrency)) as ex:- futures = {ex.submit(run_item, item=i, direction=d, state=s, base=bases[d], root=root, character=character, duration=duration, resolution=resolution, key=key, force=force, gap=gap, video_runner=video_runner, shape=shape, anchor=anchor, spill=spill, facing=facing, facing_fix=facing_fix, prepare_side=prepare_side, body_height=body_height, fit=fit, decontam=decontam, walk_start=walk_start, redraw_runner=redraw_runner, still_provider=still_provider): i for i, d, s in items}+ futures = {ex.submit(run_item, item=i, direction=d, state=s, base=b, root=root, character=character, duration=duration, resolution=resolution, key=key, force=force, gap=gap, video_runner=video_runner, shape=shape, anchor=anchor, spill=spill, facing=f, facing_fix=facing_fix, prepare_side=side_preparer(f), body_height=body_height, fit=fit, decontam=decontam, walk_start=walk_start, redraw_runner=redraw_runner, still_provider=still_provider, handed=handed): i for i, d, s, f, b in items}for fut in as_completed(futures):r = fut.result()results.append(r)print(json.dumps({k: r[k] for k in ("item", "ok") if k in r} | ({"error": r["error"]} if not r.get("ok") else {"seam": r["loop"]["seam_ratio"]}), ensure_ascii=False), flush=True)- results.sort(key=lambda r: [i for i, _, _ in items].index(r["item"]))+ results.sort(key=lambda r: [i for i, *_ in items].index(r["item"]))aligned = align_gaits(results, root, align_cycles, interpolate=interpolate)- table = write_table(results, root / "table.md")+ table = write_table(results, root / "table.md", both=both)failed = [r["item"] for r in results if not r.get("ok")] + [f"cycle-align:{st}" for st, a in aligned.items() if not a.get("ok")]# What the set left undone for want of RIFE — never a failure, never silent.warnings = ([f"{r['item']}: jump frame not repaired — {r['loop']['jump_repair']['why']}" for r in results if r.get("ok") and "jump_repair" in r["loop"]]+ [f"cycle-align:{st}: not aligned — {a['why']}" for st, a in aligned.items() if a.get("applied") is False])if warnings:warnings.append(f"install RIFE with `{rife_mod.INSTALL_COMMAND}` (docs/loop-repair.md)")- payload = {"kind": "sprite-gen-video-set-report", "root": str(root), "states": states, "facing": facing, "facing_fix": facing_fix, "directions": list(bases), "body_height": body_height, "ok": sum(1 for r in results if r.get("ok")), "failed": failed, "warnings": warnings, "items": results, "cycle_align": aligned}+ payload = {"kind": "sprite-gen-video-set-report", "root": str(root), "states": states, "facing": facing, "facing_fix": facing_fix, "directions": list(bases), **({"handed": [vars(h) for h in handed]} if handed else {}), "body_height": body_height, "ok": sum(1 for r in results if r.get("ok")), "failed": failed, "warnings": warnings, "items": results, "cycle_align": aligned}atomic_write_text(root / "set.report.json", json.dumps(payload, ensure_ascii=False, indent=2) + "\n")print(table)return payload@@ -699,7 +781,7 @@ def _parse_bases(values: list[str]) -> dict[str, Path]:raise SystemExit(f"video-set: --base expects direction=path, got {v!r}")d, p = v.split("=", 1)d = d.strip()- if d not in VIEW_TEXT:+ if d.partition("@")[0] not in VIEW_TEXT:raise SystemExit(f"video-set: --base direction must be one of {', '.join(sorted(VIEW_TEXT))}, got {d!r}")bases[d] = Path(p).expanduser().resolve()if not bases:@@ -708,9 +790,10 @@ def _parse_bases(values: list[str]) -> dict[str, Path]:def add_arguments(parser: argparse.ArgumentParser) -> None:- parser.add_argument("--base", action="append", default=[], help="direction=still.png (repeatable: side=..., front=..., back=...)")- parser.add_argument("--facing", choices=FACINGS, default="right", help="side-view facing for both prompt and canvas (default right); ignored for front/back")- parser.add_argument("--facing-fix", choices=facing_mod.FIXES, default="none", help="side inputs: record only (none, default), or opt into mirror")+ parser.add_argument("--base", action="append", default=[], help="direction=still.png (repeatable: side=..., front=..., back=...); filmed facing right,left, a side or diagonal view takes one still per facing: side@right=..., side@left=...")+ parser.add_argument("--facing", default="right", help="which way the side and diagonal views face, for both prompt and canvas: right (default), left, or right,left to film each of them both ways from a still drawn each way (no mirroring); ignored for front/back")+ parser.add_argument("--facing-fix", choices=facing_mod.FIXES, default="none", help="side inputs: record only (none, default), or opt into mirror (refused with --handed)")+ parser.add_argument("--handed", action="append", default=[], metavar="ITEM=SIDE [PART]", help="an asymmetric item on one of the character's own sides, e.g. 'the black smartwatch=left wrist' (repeatable): every clip prompt says where it is in its view and that it stays there")parser.add_argument("--states", default="idle,walk,run,jump,attack", help="comma list of motion states")parser.add_argument("--out-dir", required=True, type=Path, help="batch root; one folder per direction-state")parser.add_argument("--character", help="short subject phrase used in the prompts (e.g. 'The armored knight')")@@ -743,6 +826,7 @@ def run(**kwargs: object) -> int:body_height=(int(kwargs["body_height"]) if kwargs.get("body_height") else None), fit=str(kwargs.get("fit") or "state"),decontam=str(kwargs.get("decontam") or "off"), align_cycles=str(kwargs.get("align_cycles") or "auto"),walk_start=str(kwargs.get("walk_start") or "redraw"), still_provider=kwargs.get("still_provider"), # type: ignore[arg-type]+ handed=handed_mod.parse_all(list(kwargs.get("handed") or [])) or None, # type: ignore[arg-type])return 0 if not payload["failed"] else 1diff --git a/sprite_gen/video/clip_prompt.py b/sprite_gen/video/clip_prompt.pyindex e97883c..276f022 100644--- a/sprite_gen/video/clip_prompt.py+++ b/sprite_gen/video/clip_prompt.py@@ -22,6 +22,8 @@ import sysfrom typing import Anyfrom sprite_gen.gen.facing import FACINGS+from sprite_gen.gen import handedness as handed_mod+from sprite_gen.gen.handedness import Handedfrom sprite_gen.video import batch as batch_modDEFAULT_MODEL = "grok-imagine-video-1.5"@@ -30,8 +32,10 @@ START_STILL_KEYS = ("green", "magenta")def plan_prompt(*, direction: str, state: str, facing: str = "right", character: str | None = None,motion: str | None = None, model: str = DEFAULT_MODEL, last_frame: bool = True,- unpinned: bool = False, duration: int | None = None, key: str = "green") -> dict[str, Any]:- """The prompt `video-set` would send for (direction, state), and how its clip is to be cut."""+ unpinned: bool = False, duration: int | None = None, key: str = "green",+ handed: list[Handed] | None = None) -> dict[str, Any]:+ """The prompt `video-set` would send for (direction, state), and how its clip is to be cut. `handed`+ (`handedness.parse`) adds where each asymmetric item is in this view, as `video-set --handed` does."""if direction not in batch_mod.VIEW_TEXT:raise SystemExit(f"video-prompt: --direction must be one of {', '.join(sorted(batch_mod.VIEW_TEXT))}, got {direction!r}")if key not in START_STILL_KEYS:@@ -51,11 +55,11 @@ def plan_prompt(*, direction: str, state: str, facing: str = "right", character:pinned = Falsewarnings.append(f"{direction} {state} filmed without its end-frame pin: the loop is searched, not cut whole, and may not close")pins = wants_pin and last_frame- prompt = batch_mod.build_prompt(direction, state, character, facing=facing, motion=motion, pinned=pinned, model=model)+ prompt = batch_mod.build_prompt(direction, state, character, facing=facing, motion=motion, pinned=pinned, model=model,+ handed=handed)cycle = "pinned" if pins and state in batch_mod.PINNED_LOOP_STATES else "auto"- # as video-set places and cuts: a diagonal's canvas takes the facing, its loop does not- canvas_facing = facing if direction not in ("front", "back") else "right"- loop_facing = facing if direction == "side" else "right"+ # as video-set places and cuts: a side or diagonal view takes the facing, front and back face right+ canvas_facing = loop_facing = facing if direction in handed_mod.LATERAL_VIEWS else "right"mid_step = batch_mod.starts_mid_step(state, direction)still = "<dir>/walk-start.png" if mid_step else "<still.png>"duration = batch_mod.duration_for(state, duration)@@ -65,6 +69,7 @@ def plan_prompt(*, direction: str, state: str, facing: str = "right", character:"direction": direction,"state": state,"facing": facing,+ **({"handed": [vars(h) for h in handed]} if handed else {}),"model": model,"prompt": prompt,"duration": duration,@@ -90,7 +95,8 @@ def plan_prompt(*, direction: str, state: str, facing: str = "right", character:def add_arguments(parser: argparse.ArgumentParser) -> None:parser.add_argument("--direction", required=True, choices=sorted(batch_mod.VIEW_TEXT), help="view of the still")parser.add_argument("--state", required=True, help="motion state (idle/walk/run/jump/attack/...)")- parser.add_argument("--facing", choices=FACINGS, default="right", help="side view: which way it faces (default right)")+ parser.add_argument("--facing", choices=FACINGS, default="right", help="side or diagonal view: which way it faces (default right)")+ parser.add_argument("--handed", action="append", default=[], metavar="ITEM=SIDE [PART]", help="an asymmetric item on one of the character's own sides, e.g. 'the black smartwatch=left wrist' (repeatable): the prompt says where it is in this view")parser.add_argument("--character", help="short subject phrase used in the prompt (e.g. 'The armored knight')")parser.add_argument("--motion", help="the caller's own motion paragraph in place of the state's sentence (build_prompt(motion=...))")parser.add_argument("--model", default=DEFAULT_MODEL, help=f"clip model the prompt is for (default {DEFAULT_MODEL}); a Lite model calms a walk")@@ -108,6 +114,7 @@ def run(**kwargs: object) -> int:model=str(kwargs.get("model") or DEFAULT_MODEL), last_frame=not kwargs.get("no_last_frame"),unpinned=bool(kwargs.get("unpinned")), duration=(int(kwargs["duration"]) if kwargs.get("duration") else None), # type: ignore[arg-type]key=str(kwargs.get("key") or "green"),+ handed=handed_mod.parse_all(list(kwargs.get("handed") or [])) or None, # type: ignore[arg-type])for line in record["warnings"]:print(f"video-prompt: warning: {line}", file=sys.stderr)diff --git a/tests/gen/test_handedness.py b/tests/gen/test_handedness.pynew file mode 100644index 0000000..8beab19--- /dev/null+++ b/tests/gen/test_handedness.py@@ -0,0 +1,177 @@+# SPDX-License-Identifier: Apache-2.0+"""Handedness: an asymmetric item's side, worked out per view and said in the still and clip prompts.+The table is written out here on its own, not derived from the module, so a wrong placement fails."""+import json+import shutil+from pathlib import Path++import pytest+from PIL import Image++from sprite_gen import gen+from sprite_gen.gen import handedness as h+from sprite_gen.gen.base import ProviderRun+from sprite_gen.video import batch as batch_mod+from sprite_gen.video import clip_prompt++FIXTURES = Path(__file__).parents[1] / "fixtures" / "facing"+WATCH = "the black smartwatch=left wrist"++# Where the character's own LEFT side is: (view, facing) -> (picture side, depth).+OWN_LEFT = {+ ("front", None): ("right", None),+ ("back", None): ("left", None),+ ("side", "right"): (None, "far"),+ ("side", "left"): (None, "near"),+ ("front_diagonal", "right"): ("right", "far"),+ ("front_diagonal", "left"): ("right", "near"),+ ("back_diagonal", "right"): ("left", "far"),+ ("back_diagonal", "left"): ("left", "near"),+}+++def test_parse_reads_item_side_and_part() -> None:+ assert h.parse(WATCH) == h.Handed("the black smartwatch", "left", "wrist")+ assert h.parse(" the star hairpin = Right ") == h.Handed("the star hairpin", "right", "")+ assert h.parse("a bag = right shoulder strap").part == "shoulder strap"+ for bad in ("the watch", "the watch=", "=left wrist", "the watch=upper wrist"):+ with pytest.raises(SystemExit, match="handedness: expected"):+ h.parse(bad)++[email protected]("view,facing", list(OWN_LEFT))+def test_placement_matches_the_table_and_the_right_side_is_its_mirror(view, facing) -> None:+ picture, depth = OWN_LEFT[(view, facing)]+ assert h.placement("left", view, facing) == {"picture": picture, "depth": depth}+ flip = {"left": "right", "right": "left", "near": "far", "far": "near", None: None}+ assert h.placement("right", view, facing) == {"picture": flip[picture], "depth": flip[depth]}+++def test_a_turned_view_needs_its_facing() -> None:+ for view in ("side", "front_diagonal", "back_diagonal"):+ with pytest.raises(SystemExit, match="turned right or left"):+ h.placement("left", view)+ with pytest.raises(SystemExit, match="view must be one of"):+ h.placement("left", "top")+ assert set(h.VIEWS) == set(batch_mod.VIEW_TEXT)++[email protected]("view,facing", list(OWN_LEFT))+def test_the_sentence_says_the_side_and_where_it_is_in_the_view(view, facing) -> None:+ text = h.text([h.parse(WATCH)], view, facing)+ assert text.startswith("The black smartwatch is on the character's own left wrist only;")+ assert "the right wrist has none" in text+ picture, depth = OWN_LEFT[(view, facing)]+ if picture:+ assert f"own left wrist is the one at the {picture} of the picture" in text+ if depth == "far" and view == "side":+ assert "on the far side, behind the body, so the black smartwatch is hidden" in text+ if depth == "near" and view == "side":+ assert "its left wrist is the near one" in text and "shows clearly" in text+ if depth == "near" and view != "side":+ assert "nearer the viewer and fully visible" in text+ assert text.endswith("whatever an attached picture shows.")+++[email protected]("view,facing", list(OWN_LEFT))+def test_the_clip_sentence_anchors_to_the_image_and_never_names_a_hidden_item(view, facing) -> None:+ """A clip starts from a still drawn with the item in place. Named where it is hidden, with what the near+ arm must not wear, a clip grew the item on the near arm; the far side of a side view names nothing."""+ clip = h.text([h.parse(WATCH)], view, facing, clip=True)+ assert "exactly as in the image" in clip and "for the whole clip" in clip and "attached picture" not in clip+ picture, depth = OWN_LEFT[(view, facing)]+ if view == "side" and depth == "far":+ assert clip == "The wrist in front of the body stays bare, exactly as in the image, for the whole clip."+ assert "watch" not in clip+ else:+ assert clip.startswith("The black smartwatch stays on the wrist ")+ assert clip.count("smartwatch") == 1 and "no band" not in clip and "strap" not in clip+ if picture:+ assert f"at the {picture} of the picture" in clip+ if view == "side":+ assert "the wrist in front of the body" in clip+++def test_the_clip_prompt_ends_with_the_handedness_sentence() -> None:+ items = [h.parse(WATCH)]+ plain = batch_mod.build_prompt("front_diagonal", "walk", None, facing="left")+ with_item = batch_mod.build_prompt("front_diagonal", "walk", None, facing="left", handed=items)+ assert with_item == plain + " " + h.text(items, "front_diagonal", "left", clip=True)+ front = batch_mod.build_prompt("front", "walk", None, facing="right", handed=items, motion="It strolls.")+ assert front.endswith(h.text(items, "front", None, clip=True))+ assert batch_mod.build_prompt("side", "walk", None, handed=None) == batch_mod.build_prompt("side", "walk", None)+++def test_video_prompt_carries_handedness_and_turns_a_left_diagonal_loop_left() -> None:+ record = clip_prompt.plan_prompt(direction="back_diagonal", state="walk", facing="left", last_frame=False,+ unpinned=True, handed=[h.parse(WATCH)])+ assert record["handed"] == [{"item": "the black smartwatch", "side": "left", "part": "wrist"}]+ assert "toward the upper left" in record["prompt"] and "upper right" not in record["prompt"]+ assert "stays on the wrist at the left of the picture, nearer the viewer" in record["prompt"]+ assert "--facing left" in record["commands"]["canvas"] and "--facing left" in record["commands"]["loop"]+ front = clip_prompt.plan_prompt(direction="front", state="walk", facing="left", last_frame=False)+ assert "--facing right" in front["commands"]["loop"] and "handed" not in front+++class Backend:+ name = "openai"+ transparency = "native"++ def __init__(self, observed="right", regenerated="right"):+ self.observed, self.regenerated = observed, regenerated+ self.generations = []++ def generate(self, request, workdir):+ self.generations.append(request)+ source = self.regenerated if len(self.generations) > 1 else self.observed+ shutil.copyfile(FIXTURES / f"{source}.png", request.raw)+ return ProviderRun(self.name, 1, model="test-image", extra={})++ def inspect_facing(self, path, workdir):+ direction = self.regenerated if len(self.generations) > 1 else self.observed+ return json.dumps({"direction": direction, "confidence": 0.9}), {"model": "test-vision"}+++def _gen(tmp_path, monkeypatch, backend, **kwargs):+ monkeypatch.setattr(gen, "_make_provider", lambda *a, **kw: backend)+ return gen.generate_image("openai", "a toy robot", tmp_path / "out.png", **kwargs)+++def test_gen_direction_adds_the_view_and_handedness_sentences(tmp_path, monkeypatch) -> None:+ backend = Backend("left")+ items = [h.parse(WATCH)]+ result = _gen(tmp_path, monkeypatch, backend, refs=[FIXTURES / "front.png"], view="front_diagonal",+ facing="left", handed=items)+ prompt = backend.generations[0].prompt+ assert batch_mod.still_view_text("front_diagonal", "left")[1:] in prompt+ assert h.text(items, "front_diagonal", "left") in prompt+ assert result.extra["view"] == {"direction": "front_diagonal", "facing": "left",+ "handed": [{"item": "the black smartwatch", "side": "left", "part": "wrist"}]}++[email protected]("kwargs,error", [+ ({"handed": [h.parse(WATCH)]}, "--handed needs --direction"),+ ({"view": "side", "handed": [h.parse(WATCH)]}, "turned right or left"),+ ({"view": "front", "facing": "right"}, "drop --facing"),+ ({"view": "side", "facing": "left", "facing_fix": "mirror", "handed": [h.parse(WATCH)]}, "moves every --handed item"),+])+def test_gen_refuses_before_generating(tmp_path, monkeypatch, kwargs, error) -> None:+ backend = Backend()+ with pytest.raises(SystemExit, match=error):+ _gen(tmp_path, monkeypatch, backend, refs=[FIXTURES / "front.png"], **kwargs)+ assert backend.generations == []+++def test_a_handed_regeneration_that_still_faces_the_other_way_is_not_mirrored(tmp_path, monkeypatch) -> None:+ backend = Backend(observed="left", regenerated="left")+ result = _gen(tmp_path, monkeypatch, backend, refs=[FIXTURES / "front.png"], view="side", facing="right",+ facing_fix="regen", handed=[h.parse(WATCH)])+ assert len(backend.generations) == 2+ assert Image.open(result.out).tobytes() == Image.open(FIXTURES / "left.png").tobytes()+ report = result.extra["facing"]+ assert "fallback" not in report and "not mirrored" in report["reason"]+ # without an item the same regeneration is mirrored, as before+ plain = _gen(tmp_path, monkeypatch, Backend(observed="left", regenerated="left"), refs=[FIXTURES / "front.png"],+ facing="right", facing_fix="regen")+ assert plain.extra["facing"]["fallback"] == "mirror"diff --git a/tests/qa/test_handed_check.py b/tests/qa/test_handed_check.pynew file mode 100644index 0000000..6565bff--- /dev/null+++ b/tests/qa/test_handed_check.py@@ -0,0 +1,164 @@+# SPDX-License-Identifier: Apache-2.0+"""`handed-check` on drawn figures: a body with two arms and a blue watch screen on its own left wrist.+Each view is drawn as it should look (the table below, written out by hand), passes, and turned over+(as a set that mirrors its left-hand views would) fails — the check catches a mirror by itself."""+import json+import subprocess+import sys+from pathlib import Path++import pytest+from PIL import Image, ImageDraw, ImageOps++from sprite_gen.gen import handedness as h+from sprite_gen.qa import handed++WATCH = h.parse("the black smartwatch=left wrist")+BLUE = (30, 90, 235)+W, H = 200, 320+# Where the watch is drawn for each (view, facing): on the arm at the picture's left / right, on the+# near arm (a side view, in front of the body) or nowhere (a side view, behind the body).+DRAWN = {+ ("front", None): "right", ("back", None): "left",+ ("front_diagonal", "right"): "right", ("front_diagonal", "left"): "right",+ ("back_diagonal", "right"): "left", ("back_diagonal", "left"): "left",+ ("side", "right"): "hidden", ("side", "left"): "near",+}+VIEWS = list(DRAWN)+++def figure(where: str, *, swing: int = 0, screen: int = 12, outline_split: bool = False) -> Image.Image:+ """A keyed figure: head and body, two arms, and the watch screen drawn `where`."""+ im = Image.new("RGBA", (W, H), (0, 0, 0, 0))+ d = ImageDraw.Draw(im)+ d.ellipse((60, 20, 140, 100), fill=(240, 240, 240, 255), outline=(20, 20, 20, 255), width=3)+ d.rounded_rectangle((65, 95, 135, 250), 20, fill=(240, 240, 240, 255), outline=(20, 20, 20, 255), width=3)+ d.rectangle((70, 250, 92, 300), fill=(240, 240, 240, 255))+ d.rectangle((108, 250, 130, 300), fill=(240, 240, 240, 255))+ arms = {"left": (40 + swing, 110, 62 + swing, 210), "right": (138 - swing, 110, 160 - swing, 210)}+ if where == "near":+ arms = {"near": (92 + swing, 120, 112 + swing, 215)}+ for box in arms.values():+ d.rectangle(box, fill=(235, 235, 235, 255), outline=(20, 20, 20, 255), width=2)+ if where in arms:+ x0, _, x1, _ = arms[where]+ cx = (x0 + x1) // 2+ d.rectangle((cx - screen // 2, 185, cx + screen // 2, 185 + screen), fill=BLUE + (255,))+ if outline_split:+ d.line((cx, 185, cx, 185 + screen), fill=(20, 20, 20, 255), width=1)+ return im+++def loop(where: str, n: int = 6) -> list[Image.Image]:+ return [figure(where, swing=s) for s in (0, 2, 4, 6, 4, 2)[:n]]+++def check(frames, view, facing, **kw):+ return handed.check(frames, item=WATCH, view=view, facing=facing, marker=BLUE, **kw)++[email protected]("view,facing", VIEWS)+def test_each_view_drawn_as_its_handedness_says_passes(view, facing) -> None:+ report = check(loop(DRAWN[(view, facing)]), view, facing)+ assert report["ok"], report["fails"]+ assert report["expect"] == h.placement("left", view, facing)++[email protected]("view,facing,as_view,as_facing", [+ ("front", None, "front", None),+ ("back", None, "back", None),+ ("side", "right", "side", "left"), # E turned over for W: the watch stays hidden+ ("front_diagonal", "right", "front_diagonal", "left"), # SE for SW: the watch jumps to the picture's left+ ("back_diagonal", "right", "back_diagonal", "left"), # NE for NW: the watch jumps to the picture's right+ ("side", "left", "side", "right"),+ ("front_diagonal", "left", "front_diagonal", "right"),+ ("back_diagonal", "left", "back_diagonal", "right"),+])+def test_a_mirrored_view_fails(view, facing, as_view, as_facing) -> None:+ """The counterexample: the right-facing view turned over, checked as the left-facing one, fails."""+ mirrored = [ImageOps.mirror(f) for f in loop(DRAWN[(view, facing)])]+ reference = [figure("right")] # the front view: the watch in full view+ report = check(mirrored, as_view, as_facing, references=reference)+ assert not report["ok"]+++def test_the_wrong_wrist_in_a_side_view_needs_a_reference_to_be_caught() -> None:+ """Facing right, the left wrist is the far one: a full screen on the near arm is the wrong wrist.+ Only the item seen whole (a front reference) tells a sliver from a full screen."""+ frames = loop("near")+ unchecked = check(frames, "side", "right")+ assert unchecked["ok"] and unchecked["rules"]["far_hidden"]["checked"] is False+ caught = check(frames, "side", "right", references=[figure("right")])+ assert not caught["ok"] and "on the far side" in caught["fails"][0]["why"][0]+ sliver = check([figure("near", screen=4)], "side", "right", references=[figure("right")])+ assert sliver["ok"]+++def test_the_item_in_two_places_fails_and_a_split_screen_is_one() -> None:+ both = figure("right")+ d = ImageDraw.Draw(both)+ d.rectangle((45, 185, 57, 197), fill=BLUE + (255,))+ report = check([both], "front", None)+ assert not report["ok"] and "2 places" in report["fails"][0]["why"][0]+ assert check([figure("right", outline_split=True)], "front", None)["ok"]+ # a few tinted pixels elsewhere (a clip's colour blocks on an outline) are a speck, not a second watch+ speck = figure("right")+ ImageDraw.Draw(speck).rectangle((45, 185, 49, 189), fill=BLUE + (255,))+ report = check([speck], "front", None)+ assert report["ok"] and len(report["per_frame"][0]["specks"]) == 1+++def test_a_near_item_hidden_in_most_frames_fails() -> None:+ frames = [figure("near")] + [figure("hidden")] * 3+ report = check(frames, "side", "left")+ assert not report["ok"] and report["rules"]["near_shown"] == {"min": 0.5, "shown": 1, "frames": 4, "ok": False}+++def test_unusable_inputs_are_refused() -> None:+ with pytest.raises(SystemExit, match="saturated colour"):+ handed.check([figure("right")], item=WATCH, view="front", facing=None, marker=(128, 128, 128))+ with pytest.raises(SystemExit, match="no transparent pixels"):+ check([Image.new("RGBA", (10, 10), (255, 255, 255, 255))], "front", None)+ with pytest.raises(SystemExit, match="#RRGGBB"):+ handed.parse_marker("blue")+ with pytest.raises(SystemExit, match="no --reference shows the marker"):+ check([figure("hidden")], "side", "right", references=[figure("hidden")])+++def test_cli_reads_a_strip_writes_a_board_and_exits_on_a_mirror(tmp_path) -> None:+ def strip(frames, name):+ sheet = Image.new("RGBA", (W * len(frames), H), (0, 0, 0, 0))+ for i, f in enumerate(frames):+ sheet.paste(f, (i * W, 0))+ path = tmp_path / f"{name}.strip.png"+ sheet.save(path)+ (tmp_path / f"{name}.strip.json").write_text(json.dumps({"frames": len(frames), "w": W, "h": H}))+ return path++ good = strip(loop("right"), "sw")+ bad = strip([ImageOps.mirror(f) for f in loop("right")], "sw-mirrored")+ base = [sys.executable, "-m", "sprite_gen.cli", "handed-check", "--direction", "front_diagonal", "--facing", "left",+ "--handed", "the black smartwatch=left wrist", "--marker", "#1e5aeb"]+ ok = subprocess.run([*base, "--strip", str(good), "--board", str(tmp_path / "ok.png"),+ "--report", str(tmp_path / "ok.json")], capture_output=True, text=True)+ assert ok.returncode == 0, ok.stderr+ assert json.loads(ok.stdout)["ok"] and (tmp_path / "ok.png").is_file()+ assert json.loads((tmp_path / "ok.json").read_text())["frames"] == 6+ no = subprocess.run([*base, "--strip", str(bad)], capture_output=True, text=True)+ assert no.returncode == 1 and "on the picture's left, expected its right" in no.stderr+++def test_a_bare_strap_on_the_far_arm_is_caught_only_with_strap() -> None:+ """Facing left, the watch is on the near arm; its strap alone on the far arm (no screen, behind the body's+ edge) is the item in a second place. The screen colour cannot see it; `strap` can. Outlines stay out."""+ frame = figure("near")+ ImageDraw.Draw(frame).rectangle((128, 186, 142, 200), fill=(15, 15, 15, 255))+ assert check([frame], "side", "left")["ok"]+ caught = check([frame], "side", "left", strap=(20, 20, 20), zone=(0.5, 0.8))+ assert not caught["ok"] and "without its marker" in caught["fails"][0]["why"][0]+ assert check([figure("near")], "side", "left", strap=(20, 20, 20), zone=(0.5, 0.8))["ok"]+ outside = check([frame], "side", "left", strap=(20, 20, 20), zone=(0.0, 0.45))+ # outside the zone nothing is looked at: no strap, and the near screen counts as hidden+ assert outside["per_frame"][0]["straps"] == [] and outside["rules"]["near_shown"]["ok"] is False+ with pytest.raises(SystemExit, match="--zone"):+ check([frame], "side", "left", zone=(0.8, 0.5))diff --git a/tests/video/test_batch_handed.py b/tests/video/test_batch_handed.pynew file mode 100644index 0000000..88fdd5a--- /dev/null+++ b/tests/video/test_batch_handed.py@@ -0,0 +1,117 @@+# SPDX-License-Identifier: Apache-2.0+"""A set filmed facing right and left from stills drawn each way (no mirroring), with an asymmetric+item's side in every clip prompt. Real canvases, an offline video runner, vision and loop."""+import json+from pathlib import Path++import pytest++from sprite_gen.gen import handedness as h+from sprite_gen.video import batch++FIXTURES = Path(__file__).parents[1] / "fixtures" / "facing"+WATCH = [h.parse("the black smartwatch=left wrist")]+++def offline(monkeypatch):+ loops = []+ monkeypatch.setattr(batch.facing_mod.vision, "grok_inspect", lambda path, **kw: (+ "left" if "left" in Path(path).name else "right", {}))+ monkeypatch.setattr(batch.frames_mod, "run_frames", lambda clip, out, **kw: {+ "fps": 24, "frames": 10, "alpha_zero_pct_min": 50, "alpha_zero_pct_max": 60, "keyed_dir": str(out)})++ def run_loop(*a, **kw):+ loops.append((kw["name"], kw["facing"]))+ return {"cycle": {"length": 10, "period_global": 10, "ratio": 0.2}, "resampled_seam_ratio": 0.2, "n_out": 10,+ "gif": {"file": "loop.gif"}, "webp": {"file": "loop.webp"}, "strip": {"path": "strip.png"}}+ monkeypatch.setattr(batch.loop_mod, "run_loop", run_loop)+ monkeypatch.setattr(batch, "_staggered_start", lambda gap: None)+ return loops+++def _video(prompts):+ def video(image, prompt, out, report, **kw):+ prompts[out.parent.name] = prompt+ out.write_bytes(b"test-video")+ report.write_text(json.dumps({"prompt": prompt}))+ return 0+ return video+++def _bases():+ return {"front": FIXTURES / "front.png",+ "side@right": FIXTURES / "right.png", "side@left": FIXTURES / "left.png",+ "front_diagonal@right": FIXTURES / "right.png", "front_diagonal@left": FIXTURES / "left.png"}+++def test_both_facings_film_every_turned_view_twice_from_its_own_still(tmp_path, offline) -> None:+ prompts: dict[str, str] = {}+ result = batch.run_set(bases=_bases(), states=["walk"], root=tmp_path, character=None, duration=3,+ resolution="720p", key="green", concurrency=1, force=False, gap=0, facing="right,left",+ video_runner=_video(prompts), walk_start="as-given", align_cycles="off", handed=WATCH)+ names = [i["item"] for i in result["items"]]+ assert names == ["front-walk", "side-right-walk", "side-left-walk", "front_diagonal-right-walk",+ "front_diagonal-left-walk"]+ assert result["ok"] == 5 and result["handed"] == [vars(WATCH[0])]+ for name, turned in (("side-right-walk", "right"), ("side-left-walk", "left"),+ ("front_diagonal-right-walk", "right"), ("front_diagonal-left-walk", "left")):+ item = next(i for i in result["items"] if i["item"] == name)+ assert item["turned"] == turned+ canvas = json.loads((tmp_path / name / "canvas.report.json").read_text())+ assert canvas["facing"] == turned+ direction = item["direction"]+ assert prompts[name] == batch.build_prompt(direction, "walk", None, facing=turned, handed=WATCH)+ assert prompts[name].endswith(h.text(WATCH, direction, turned, clip=True))+ assert "and to the left" in prompts["front_diagonal-left-walk"]+ assert "to the right" not in prompts["front_diagonal-left-walk"]+ # each side still is inspected for its own facing, into its own copy, never turned over+ side_left = next(i for i in result["items"] if i["item"] == "side-left-walk")["facing"]+ assert side_left["requested"] == "left" and side_left["action"] == "none"+ assert (tmp_path / "side-left.facing.png").read_bytes() == (FIXTURES / "left.png").read_bytes()+ assert (tmp_path / "side-right.facing.png").read_bytes() == (FIXTURES / "right.png").read_bytes()+ assert dict(offline) == {"front-walk": "right", "side-right-walk": "right", "side-left-walk": "left",+ "front_diagonal-right-walk": "right", "front_diagonal-left-walk": "left"}+ table = (tmp_path / "table.md").read_text()+ assert "| side (left) | walk |" in table and "| front | walk |" in table+++def test_one_facing_keeps_the_item_names_and_table(tmp_path, offline) -> None:+ prompts: dict[str, str] = {}+ result = batch.run_set(bases={"front_diagonal": FIXTURES / "left.png"}, states=["attack"], root=tmp_path,+ character=None, duration=2, resolution="720p", key="green", concurrency=1, force=False,+ gap=0, facing="left", video_runner=_video(prompts))+ assert [i["item"] for i in result["items"]] == ["front_diagonal-attack"]+ assert offline == [("front_diagonal-attack", "left")] # a left diagonal is cut as a left one+ assert "| front_diagonal | attack |" in (tmp_path / "table.md").read_text()++[email protected]("bases,facing,error", [+ ({"side": "right.png"}, "right,left", "needs a still for each"),+ ({"side@right": "right.png"}, "right,left", "draw it that way"),+ ({"side@left": "left.png"}, "right", "the set is filmed facing right"),+ ({"front@left": "front.png"}, "right", "not turned to a side"),+ ({"side": "right.png"}, "up", "--facing must be right, left or right,left"),+])+def test_bases_that_would_need_a_mirror_or_make_no_sense_are_refused(tmp_path, bases, facing, error) -> None:+ with pytest.raises(SystemExit, match=error):+ batch.run_set(bases={k: FIXTURES / v for k, v in bases.items()}, states=["walk"], root=tmp_path,+ character=None, duration=3, resolution="720p", key="green", concurrency=1, force=False, gap=0,+ facing=facing, video_runner=_video({}))+++def test_mirror_correction_is_refused_with_an_item(tmp_path) -> None:+ with pytest.raises(SystemExit, match="moves every --handed item"):+ batch.run_set(bases={"side": FIXTURES / "right.png"}, states=["walk"], root=tmp_path, character=None,+ duration=3, resolution="720p", key="green", concurrency=1, force=False, gap=0,+ facing_fix="mirror", video_runner=_video({}), handed=WATCH)+++def test_cli_threads_both_facings_and_items(monkeypatch, tmp_path) -> None:+ seen = []+ monkeypatch.setattr(batch, "run_set", lambda **kw: seen.append(kw) or {"failed": []})+ assert batch.main(["--base", f"side@right={FIXTURES / 'right.png'}", "--base", f"side@left={FIXTURES / 'left.png'}",+ "--states", "walk", "--out-dir", str(tmp_path), "--facing", "right,left",+ "--handed", "the black smartwatch=left wrist"]) == 0+ assert seen[0]["facing"] == "right,left" and seen[0]["handed"] == WATCH+ assert set(seen[0]["bases"]) == {"side@right", "side@left"}diff --git a/tests/video/test_video_pipeline.py b/tests/video/test_video_pipeline.pyindex fdf35d9..9b9bd18 100644--- a/tests/video/test_video_pipeline.py+++ b/tests/video/test_video_pipeline.py@@ -544,7 +544,7 @@ def test_a_diagonal_walk_is_pinned_and_named_as_an_isometric_heading() -> None:for direction, heading in (("front_diagonal", "heading diagonally toward the viewer and to the right"),("back_diagonal", "heading diagonally away from the viewer toward the upper right")):for state in ("walk", "run"):- sentence = batch_mod.VIEW_MOTION_TEXT[(state, direction)]+ sentence = batch_mod.VIEW_MOTION_TEXT[(state, direction)].format(facing="right")p = batch_mod.build_prompt(direction, state, None)assert p == batch_mod.PINNED_LOOP_TEXT.format(motion=sentence, view=batch_mod.VIEW_TEXT[direction])assert heading in sentence and "never turns into a side view" in sentence@@ -558,6 +558,16 @@ def test_a_diagonal_walk_is_pinned_and_named_as_an_isometric_heading() -> None:assert batch_mod.pins_last_frame("attack", "side") and batch_mod.pins_last_frame("idle", "front")[email protected]("direction", ["front_diagonal", "back_diagonal"])[email protected]("state", ["walk", "run"])+def test_a_diagonal_facing_left_heads_left(direction, state) -> None:+ """Regression: a diagonal drawn facing left was filmed with a walk heading "to the right" — the gait+ sentence ignored `facing`. Facing left, it heads down or up and to the left, and says right nowhere."""+ left = batch_mod.build_prompt(direction, state, None, facing="left")+ assert "and to the left" in left and "to the right" not in left and "upper right" not in left+ assert left == batch_mod.build_prompt(direction, state, None, facing="right").replace("right", "left")++def test_a_diagonal_still_is_told_how_far_to_turn() -> None:"""A still at a diagonal is often redrawn from a front or side picture, so its view sentence says theturn (45 degrees), that the head turns with the body and where the feet point, instead of pointing