Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
feat(video-loop): a walk whose body turns inside its clip is read, and the cut search leaves the turn out (--body-turn warn|refuse)
Soohong Kimaf1517c502d2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 202cd3f..6f675c4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,16 @@All notable public changes to `sprite-gen` are recorded here. Versions track the `version:` field in `SKILL.md` and `pyproject.toml`.+## Unreleased++**Upgrading from 3.3.0: a clip whose cut held a turn is now cut where a window without the turn holds a cycle, while clips with no turn, clips that are not read, and clips with a turn and no turn-free cycle under `warn` keep every cut and byte.**++- **New: `video-loop` detects torso turns in walk and run clips and avoids them during the cut search.** A video model asked to walk at the still's angle sometimes turns the body inside the clip: a back-diagonal walk turns to a full back view half way and back. A loop cut across the turn plays the body swinging round. Until now the engine had no reading of this: the cut search could not avoid it, and a clip that held no cycle for it was refused only as `video-loop: no periodic cycle found`, so an app could not name that the body turned as the reason to film it again. The new module `sprite_gen/video/body_turn.py` introduces reading `torso-side-v1` on every walk or run under `--anchor motion-auto`, reading each frame's torso crop against the clip's first frame, the still the clip was filmed from, a standing pose. It does so whether or not the clip opens on a lead-in (the video model reframing the still to the walk's size over the first frames, which the cut search leaves out). It does not read against the first frame after the lead-in: that frame is a stride's pose, and a walk draws the mirror of a stride's pose half a cycle later, so a synthetic walk that does not turn, read against it, read a turn every stride (least -0.24). Read against the still filmed small, the same synthetic walk (its first 8 frames filmed from 0.6 of its size) reads only nearer 0: +0.41 where it does not turn (+0.86 without the lead-in), and its turn -0.14 (-0.30 without the lead-in), at the same frames. The torso crop runs from the neck down half the body below it, centred on the head's centre, as wide as the first frame's torso. The neck is the narrowest row of the first frame between 10 % and 55 % of its height (the topmost on a tie, or row 0.11 on a hooded walker). Each frame's `side` correlation is `(v.s - v.m) / (1 - s.m)`. Under module constants `SIDE_SHOWN_MIN` = 0.10, `TURN_SIDE_MAX` = 0, and `TURN_RUN_MIN` = 4 consecutive frames, candidate windows whose cut holds a frame of a turn are refused with `the body turns (clip frames a-b)`, two-step cuts holding one are left out (`step_count.turned_out`), and held-side windows two lengths long are excluded. A new bound, `HEAD_REACH` = 0.3, re-reads the head's centre (the middle of the solid pixels of the top 15 % of the body) on the pixels within `HEAD_REACH` of the body's height of it until it settles, leaving the plain mass centre as before where no pixel of those rows lies further out. Clips without turns (or unread) are searched once as before with the same cut and bytes. Where no window without the turn holds a cycle, `--body-turn warn` (the default) reruns the cut search as before and keeps the cut with a warning line naming the turn, or refuses as before (`video-loop: no periodic cycle found`) after a warning line if no cut holds a cycle; while `--body-turn refuse` (requiring `--anchor motion-auto`) prints `video-loop: the body turns in the walk` as its first line, prescribes filming it again with the torso and hips kept at the still's angle, hands over nothing, and sets `status: failed`, supporting app retake rules such as `loop-body-turned`.+- Report fields (`<name>.loop.report.json`): every walk or run report under `--anchor motion-auto` adds the `body_turn` object containing `reading` (`torso-side-v1`), `bounds` (`SIDE_SHOWN_MIN`, `TURN_SIDE_MAX`, `TURN_RUN_MIN`), `reference` (0: the frame read against, the clip's first, lead-in or not), `still_side`, `read` (true or false), `why` (where not read), `neck`, `torso_still_side`, `side` (each frame's reading), `turns` (each `{from, to, least, at}`), `mode` (`warn` or `refuse`), `verdict`, `refused` (how many windows were refused for it), `cut` (`frames`, the cut's first and last clip frame, and `holds`, the turned frames it holds), `avoiding` (the search's refusal where the search that avoided the turn found nothing), and `unread` (a list of `{frames, why}`, each reason with the frames it applies to, appearing only where at least one frame was not read). The `verdict` field records one of `none` (read, no turn), `not-read` (a square still, a first frame with no body, or a first frame the reading cannot read (no head to centre on, no solid pixel across its torso rows, or a crop of no width or with nothing in it)), `clear` (a turn, and the cut holds none of it without refusing anything), `avoided` (windows were refused for the turn and the cut leaves it out), `kept` (no cut without the turn holds a cycle; the cut taken before is kept, warned), `unfound` (no cycle with the turn or without it; refused as before, warned), or `refused` (`--body-turn refuse`). The command's JSON summary also gains `body_turn` (`verdict`, `turns`, `cut`) where a turn was read.+- Python callers: new module `sprite_gen.video.body_turn` provides `read(frames)`, `turns(side)`, `turned(reading)`, `neck(body)`, `torso_rows(at)`, class `Turn(reading, skip=0)` (callable as `(start, length)`, returning the refusal reason or None, `held(start, length)`, counter `refused`), `refusal(...)`, `kept(...)`, `unfound(...)`, constants `READING`, `SIDE_SHOWN_MIN`, `TURN_SIDE_MAX`, `TURN_RUN_MIN`, `MODES` (`warn`, `refuse`), `NECK_RANGE` (0.10, 0.55), and `HEAD_REACH` (0.3). Functions `local_cycle.detect`, `local_cycle.by_steps` and `local_cycle.counted` take a new keyword argument `turn` (a `Turn`, default None: as before). Function `loop.run_loop` takes `body_turn` (default `"warn"`).+- Output changes: a new named bound of the reading, `HEAD_REACH` = 0.3, re-reads the head's centre on the pixels within 0.3 of the body's height of it. The full test suite caught why it is needed: its side walker with a 60 px tail on a 45-frame beat (`tests/video/test_walk_steps.py`, the half-step case) read a turn on every swing (frames 6 to 16 and 51 to 61, least -0.21), because the tail swung up into the head's rows and pulled the head's centre aside; the cut search then left those frames out, cut it 17/29 instead of two steps, and the seam gate refused it (2.82). With `HEAD_REACH` it reads no turn (least +0.11) and is cut as before. Where no solid pixel of those rows lies within `HEAD_REACH` of their middle, the top's parts lie apart on either side of the middle (a prop held as high as the head and apart from it, or a body too small for any pixel to lie that near), and the top does not tell which part is the head, so the frame is not read instead of taking the largest part and centring on a prop that can weigh what the head does (on the test suite's 133 px synthetic staff walker, the ornament and the head hold the same number of solid pixels in those rows, 513 each, with no pixel within 39.9 px of the middle) and reading turns the body does not make. Where that frame is the first frame, the clip is not read and the cut search runs once as on any unread clip; cut by `video-loop` under default `--body-turn warn`, that synthetic staff walker is not read and is cut 11/24 (start 11, 24 frames), every byte as 3.3.0 cuts it.+- **Tests**: synthetic tests in new test file `tests/video/test_loop_body_turn.py` verify a 73-frame, 24-frame cycle back-diagonal walker seen from behind (legs side by side swinging half a cycle apart, arms either side swinging opposite, the arm on the facing side bright and the other dim, a light panel on the torso and the cheek toward the facing) whose turn moves its facing over to the still's mirror and back. Tests verify boundary turnovers: a torso reading of exactly 0 is not turned and one just under it is; three turned frames in a row are not a turn and four are; a frame not read ends a run; and `SIDE_SHOWN_MIN` set to the walker's own still side reads the clip and set just above it does not. The walker that turns reads one turn inside the frames it turns over and none elsewhere; the same walker not turning reads none; drawn square from behind it is not read. The same turn drawn on twos reads the same frames as on ones (within a frame), in fewer drawings. On a lead-in where the first 8 frames are filmed from 0.6 of the size (which the search leaves out), the report's `body_turn.reference` is 0, the turn reads at the frames it reads without the lead-in (under -0.1), and the walk where it does not turn stays over +0.1; read from the first frame after the lead-in instead, the same walk not turning reads a turn every stride. A hooded walker with no neck reads its neck at the top row of the range (0.11) and finds the turn too, and finds none where it does not turn. The walker facing past its mirror 3 frames in a row reads no turn (however deep); 4 frames in a row read one turn of 4 frames. The suite's half-step side walker with a 60 px tail reads no turn at `HEAD_REACH` 0.3 and a turn every swing at 0.4. Red to green tests verify that for a walker turning over frames 30 to 40 (read as 32 to 38, least -0.30), 3.3.0 cuts 22/24 (frames 22 to 45) across the turn, while this version refuses the windows that hold it and cuts 41/24 (frames 41 to 64); and turning over frames 14 to 24 and 24 to 34 where 3.3.0 cut 11/24 and 17/24 across the turn, this version cuts 35/24 and 41/24. When a walker turns in every cycle, `warn` keeps the cut the search took before, byte for byte, with the warning line, while `refuse` refuses it with `video-loop: the body turns in the walk` as the first line and hands nothing over. Walkers that do not turn and walkers drawn square are cut byte for byte as the search alone cuts them. The walker that turns (over frames 30 to 40) is cut with the cycle search replaced by one that finds no cycle in any window (as on a clip that holds no repeat), and its feet are not read; `warn` refuses it in the words it was refused in before (`video-loop: no periodic cycle found`), after the warning line naming the turn; `refuse` refuses it with `video-loop: the body turns in the walk`. Passing `--body-turn refuse` without `--anchor motion-auto` is refused. New synthetic tests in `tests/video/test_loop_body_turn.py` verify that the staff walker's still is not read; the staff over frames 20 to 29 and a 2 pixel sliver at frame 40 leave those frames null with their reason, every other frame reading as it reads without them; a pennant apart above the walker leaves the still's torso rows empty and the still unread; the pennant over frames 20 to 29 only leaves those frames' torso crops empty, so they are null, not 0; a head on a pole (one column under the head's centre) gives a crop of no width and the still is not read, and a frame of one solid pixel is null; a clip with no frames is not read; and under the default `warn`, the staff walker and the walker with the pennant in its first frame alone are cut byte for byte as the search alone cuts them, and the report says why they were not read.+## v3.3.0 - PyTorch RIFE backend for CUDA and CPU, executor for a GPU on another machine, and Linux CPU and cloud T4 release lanes**Upgrading from 3.2.0: Defaults stay unchanged, cache keys update once, reports show the backend, install checks model hashes, and schemas are unchanged.** With `SPRITE_GEN_RIFE_BACKEND` unset (the default), RIFE is the `rife-ncnn-vulkan` binary as before. Its frames are the same bytes as 3.2.0. Measured: the binary's frames and sixteen-pass readings through the changed engine equal the old engine's, byte for byte. A `--between-cache` directory kept by 3.2.0 is made again once. The key now names the backend (`backend: "ncnn"`). The engine's `rife.py` changed, and its sha256 is part of the key anyway. Reports take `interpolator.kind` from what made the frames: `rife-ncnn-vulkan` as before for the binary, or `rife-torch` for the new backend. The overlapped wrap's and the seam bridge's records count `binary_calls` for the binary as before, or `runs` for the torch backend. `SPRITE_GEN_RIFE_EXECUTOR` (new) is unset by default, and RIFE runs in this process. `sprite-gen rife install` now checks the model's two files (`rife-v4.6/flownet.param`, `flownet.bin`) against pinned SHA-256 after unpacking, for either backend. A model that differs installs nothing. The line a missing RIFE is reported with (`install` in records, warnings) is `sprite-gen rife install` for the binary. Where the torch backend is chosen, that line is: `pip install "sprite-gen[torch]" && sprite-gen rife install --backend torch`. No command-line flags of `video-loop` / `video-cycle-align` / `video-set` change. No restoration schemas change: `source-restoration-v5`, repair report `schema_version` 4, comparison `schema_version` 6.diff --git a/docs/video-pipeline.md b/docs/video-pipeline.mdindex 6df3e6c..315aa22 100644--- a/docs/video-pipeline.md+++ b/docs/video-pipeline.md@@ -375,6 +375,22 @@ or more in under half a second, then walks at its new size. What it finds, and wevery `start` and `context_pair_range` in the report's `cycle`, refused candidates too, so a cuttaken again from them (`--cycle fixed --start`) is the frames they name. A cut the caller names (`fixed`, `pinned`) is the caller's frames, lead-in or not.+**The body turn is avoided by the cut search.** A video model asked to walk at the still's angle sometimes turns the body inside the clip: a back-diagonal walk turns to a full back view half way and back. A loop cut across the turn plays the body swinging round. Every walk or run with `--anchor motion-auto` reads each frame to find turns. No window whose cut holds a frame of a turn is taken while another window holds a cycle. The search refuses that window with the reason `the body turns (clip frames a-b)`. Two-step cuts by the clip's crossings that hold a turn are left out (`step_count.turned_out` counts them), and so are the held side's windows two lengths long.++The reading (`torso-side-v1` in `sprite_gen/video/body_turn.py`) reads each frame's torso against the clip's first frame: the still the clip was filmed from, a standing pose. It does so whether or not the clip opens on a lead-in, where the video model reframes the still to the walk's size over the first frames, which the cut search leaves out. It does not read against the first frame after the lead-in: that frame is a stride's pose, and a walk draws the mirror of a stride's pose half a cycle later, so a synthetic walk that does not turn, read against it, read a turn every stride (least -0.24). Read against the still filmed small, the same synthetic walk (its first 8 frames filmed from 0.6 of its size) reads only nearer 0: +0.41 where it does not turn (+0.86 without the lead-in), and its turn -0.14 (-0.30 without the lead-in), at the same frames. The torso crop runs from the neck down half the body below it, centred on the head's centre, as wide as the first frame's torso. The neck is the narrowest row of the first frame between 10 % and 55 % of its height, taking the topmost row on a tie. A body with no neck narrower than its head (a hood widening down to the shoulders) has its narrowest row at the top of that range, so its crop holds the head and the chest, which turn with the body. On a synthetic hooded walker the neck reads at 0.11 of the height (the range's top row) and its turn reads as on a walker with a neck (least -0.28; +0.87 where it does not turn). Every crop is centred on the head's centre: the middle of the solid pixels of the top 15 % of the body. Under the fourth named bound, `HEAD_REACH` = 0.3, that middle is now read again on the pixels within `HEAD_REACH` of the body's height of it, until it settles; where no pixel of those rows lies further out, the middle is the plain mass centre as before. A part swung up beside the head (a tail on a beat of its own, a held prop) pulls a plain mass centre aside on every swing, and the torso then reads as turning with it. The test suite's side walker with a 60 px tail on a 45-frame beat read a turn on every swing (least -0.21) and was then cut across it and refused; with `HEAD_REACH` it reads none (least +0.11) and is cut as before (on it, 0.3 reads no turn and 0.4 a turn every swing). Where no solid pixel of those rows lies within `HEAD_REACH` of their middle, the top's parts lie apart on either side of the middle (a prop held as high as the head and apart from it, or a body too small for any pixel to lie that near), and the top does not tell which part is the head, so the frame is not read: its `side` is null and `body_turn` gains `unread`, a list of `{frames, why}` (each reason with the frames it applies to), while a clip whose first frame is not read records `read: false`, a `why`, and verdict `not-read`, running the cut search once for the same cut and bytes as without the reading. The largest part is not taken for the head because a prop can weigh what the head does: on the test suite's synthetic walker holding a staff beside it (its ornament at the head's height and apart from it, its handle in the hand), the ornament and the head hold the same number of solid pixels in those rows, 513 each, with the middle falling between them and no pixel within 39.9 px of it (0.3 of the 133 px body), and a crop centred on a prop would read turns the body does not make, which the cut search would leave out of the cut, or `--body-turn refuse` would refuse. Every other place where the reading would select nothing is also not read, never read as 0 and never centred on a middle no pixel holds: a first frame whose torso rows hold no solid pixel (a part apart above the body tops its box, so its narrowest row lies in the gap; on a synthetic walker with a pennant 240 px above its head, the neck reads at 0.11 and the rows from there down half the box are empty); a crop of no width (a torso one column wide under the head's centre, or a body one pixel high); a crop with nothing in it, which would have read 0, a torso as near the still as its mirror; and a clip with no frames; and a frame that is not read ends a run of turned frames, as a frame with no body already did.++Each frame's `side` = (v.s - v.m) / (1 - s.m), where v is the frame's crop, s the first frame's and m the first frame's mirrored about the head's centre (each a unit vector of luma times alpha and alpha). A value of 1 means the torso shows the side the still shows; 0 means it is as near the still as its mirror (a body seen square from behind or in front); under 0 means it faces nearer the still's mirror. A pose the walk changes moves both correlations alike; a turn moves them apart. Each clip is read only against its own first frame, never against a named motion or direction. Three named module constants define the report field `bounds`, bounding whether the clip is read and what counts as a turn. `SIDE_SHOWN_MIN` = 0.10 sets how far the still's head and shoulders (the top 45 % of its body) lie off their mirror for the clip to be read at all. Under it the still is seen square (a front or back walk) and the facing is not read, because a back walk's far step lays its torso nearer its mirror each step. `TURN_SIDE_MAX` = 0 marks any frame reading under 0 as turned. `TURN_RUN_MIN` = 4 requires 4 turned frames in a row or more to count as a turn. Turns are counted in frames, the time the clip plays them, not in drawings: a walk held on twos holds a turn as long as one drawn on ones, in half the drawings. A shorter dip is the walk's own. A synthetic walker facing past its mirror 3 frames in a row reads no turn even 0.31 under 0; 4 frames in a row read one. A clip with no turn (or one not read) is searched once, exactly as before: the same cut, the same bytes.++Where no window without the turn holds a cycle, the flag `--body-turn` decides the outcome. Under `warn` (the default), the search runs again as before, and the cut it took before is kept with a warning line naming the turned frames, the least reading and its frame, the bound, the cut and the frames of the turn it holds. Where no cut holds a cycle at all, the clip is refused in the words it was refused in before (`video-loop: no periodic cycle found`), after a warning line naming the turn. An app that matches the old refusal lines keeps matching them. Under `refuse` (which needs `--anchor motion-auto`), the clip is refused in a line of its own, the first line the run prints: `video-loop: the body turns in the walk`. That line names the turned frames, the least reading and its frame, the bound, that no cut that leaves those frames out holds two steps that repeat (or, where a cut was found that holds the turn, which cut and which frames), and the prescription to film it again with the torso and hips kept at the still's angle. Nothing is handed over; the report is written with `status: failed`. App builders can attach a retake rule, such as `loop-body-turned`, to this refusal line. Every report on a walk or run under `--anchor motion-auto` includes the `body_turn` field: `reading` (`torso-side-v1`), `bounds` (the three), `reference` (0: the frame read against, the clip's first, lead-in or not), `still_side`, `read` (true or false), `why` (where not read), `neck`, `torso_still_side`, `side` (each frame's reading), `turns` (each `{from, to, least, at}`), `mode` (`warn` or `refuse`), `verdict`, `refused` (how many windows were refused for it), `cut` (`frames`, the cut's first and last clip frame, and `holds`, the turned frames it holds), `avoiding` (the search's refusal where the search that avoided the turn found nothing), and `unread` (a list of `{frames, why}`, each reason with the frames it applies to, appearing only where at least one frame was not read). The `verdict` is one of `none` (read, no turn), `not-read` (a square still, a first frame with no body, or a first frame the reading cannot read (no head to centre on, no solid pixel across its torso rows, or a crop of no width or with nothing in it)), `clear` (a turn, and the cut holds none of it without refusing anything), `avoided` (windows were refused for the turn and the cut leaves it out), `kept` (no cut without the turn holds a cycle; the cut taken before is kept, warned), `unfound` (no cycle with the turn or without it; refused as before, warned), or `refused` (`--body-turn refuse`). The command's JSON summary gains `body_turn` (`verdict`, `turns`, `cut`) where a turn was read.++What it does not see:+- A square still (a front or back walk) is not read, so a front or back walk that turns to a diagonal is not seen.+- A shallow turn: a three-quarter walk that turns to the side each stride reads shallow, and a dip under 4 frames, or one that does not go under 0, is the walk's own.+- It does not make a walk where there is none: where the frames before the turn do not repeat either, avoiding the turn finds no cycle; the reading changes the reason given, not the result.+- A body whose narrowest row in 10 % to 55 % of its height is its waist (no neck and a head narrower than its waist) has its crop start at the waist; no such body has been measured.+- A body whose only side-to-side difference is its swinging arms, drawn symmetric about the head (the test suite's synthetic side walker, two arms either side of the head's centre, a tone apart), reads its own stride as a turn (least -0.50, every half cycle), because its stride is its own mirror. Every window holds such a turn, so `warn` keeps the cut the search took before, byte for byte, but `refuse` would refuse it.+- A clip whose first frame holds a prop as high as the head and apart from it (or a part apart above the body over its torso rows) is not read at all, so a turn in it is not seen.+Gates, all fail loud: no period (profile flat, below the recorded `periodicity_min`), loop seam ratio above `--seam-max` (2.0), GIF/WebP reopened and checked (frame count, `loop=0`, transparent corners, no RGB under alpha 0 in the WebP). On every walk or run loop that plays round, the step gate reads cells between drawings and refuses the loop when its largest step that is not a pixel's jitter, divided by the mean of the other steps, exceeds `STEP_RATIO_MAX` (2.5); a step is a pixel's jitter when aligning its drawing with the previous drawing takes at most `STEP_JITTER_PX` (1.5) pixels of the frames as filmed, measured by coverage so colour has no effect, and the step with that move taken back is within 2.5 of the mean. A fixed cut of a walk or run reads clip foot crossings to judge the cut, refusing an odd step count that would swap legs at the wrap. Both checks are lifted by `--seam-max` past 2.5; see `docs/loop-repair.md` section 3, "The step gate". Every walk or run loop gated by its seam ratio (not a pinned clip) is also refused when the top of its silhouette (the head, or a part held above it) jumps into the loop's first frame more than `--seam-pop-max` times its median step (default 10; `jolt.seam_pop.pop`, read on the loop as it plays); a top that cannot be read is not refused (`seam_pop_gate` says `unreadable`). `--seam-max` does not lift this gate; `--seam-pop-max off` turns it off, leaving a warning line as before; see `docs/loop-repair.md` section 3, "The seam pop gate".See [loop repair](loop-repair.md).diff --git a/sprite_gen/video/body_turn.py b/sprite_gen/video/body_turn.pynew file mode 100644index 0000000..d74a55e--- /dev/null+++ b/sprite_gen/video/body_turn.py@@ -0,0 +1,285 @@+# SPDX-License-Identifier: Apache-2.0+"""A walk whose body turns inside its clip, read frame by frame (`video-loop --anchor motion-auto`, `--body-turn`;+docs/video-pipeline.md section 4, "The body turn").++A clip filmed from a still walks at the still's angle, or should: a back-diagonal walk that turns to a full back view+half way and back holds no two steps in one facing, and a cut across the turn plays the body swinging round. The+reading (`torso-side-v1`) puts each frame's torso between the clip's first frame — the still it was filmed from, a+standing pose, lead-in or not — and that frame mirrored about its head:+`side = (v.s - v.m) / (1 - s.m)`, 1 where the torso shows the side the still's does, 0 where it is as near the still as+its mirror (a body seen square, from behind or in front), under 0 past it. A pose the walk changes moves both+correlations alike; a turn moves them apart. Each clip is read against its own first frame, never against a kind of+motion or a direction's name. Not against the first frame after a lead-in (the video model reframing the still to the+walk's size, which the search leaves out): that frame is a stride's pose, whose mirror the walk draws half a cycle on, so+a walk that does not turn reads a turn every stride (a synthetic one, least -0.24); the still filmed small reads blurred,+but only nearer 0 (a synthetic walk filmed from 0.6 of its size for 8 frames: +0.41 where it does not turn, its turn+-0.14).++Three named bounds:++- SIDE_SHOWN_MIN: how far the still's head and shoulders (the top 45 % of its body) lie off their mirror (1 - s.m) for+ the clip to be read at all. Under it the still is seen square — a front or back walk, whose far step lays the torso+ nearer its mirror each step — and its facing is not read: a square still that turns to a diagonal is not seen.+- TURN_SIDE_MAX: a frame whose torso reads under it is turned.+- TURN_RUN_MIN: a turn is that many turned frames in a row or more, counted in frames — the time the clip plays them —+ not in drawings: a walk held on twos holds a turn as long as one drawn on ones does, in half the drawings. A shorter+ dip is the walk's own.++Each crop is centred on the head: the middle of the solid pixels of the top 15 % of the body (HEAD_SHARE), read again on+those within HEAD_REACH of the body's height of it until it settles. A part swung up beside the head (a tail on a beat of+its own, a held prop) would pull a plain mass centre aside every swing, and the torso would read as turning with it (a+synthetic side walk with a 60 px tail on a 45-frame beat read a turn every swing, least -0.21); where nothing lies that+far out, the middle is the mass centre itself. Where nothing lies within HEAD_REACH of the middle — the top's parts lie+apart either side of it: a prop held as high as the head and apart from it, or a body too small for a pixel to lie that+near — the top does not tell which part is the head, and the frame is not read (None in `side`, its why in `unread`); a+still not read so leaves the clip unread, cut as the search alone cuts it. The largest part is not taken for the head: a+prop can weigh what the head does in those rows (a synthetic staff's ornament beside the head weighs the same), and a+crop about the prop would read turns the body does not make, which the cut search would leave out, or+`--body-turn refuse` refuse.++A crop reads only what it holds. A still with no solid pixel across its torso's rows (a part apart above the body tops+its box, its narrowest row in the gap between), a crop of no width, or one of a single value throughout (an empty crop)+is not read — the still leaving the clip unread, a frame None — never read as a torso at 0, as near the still as its+mirror.++The torso (`torso_rows`) is the rows from the neck — the narrowest row of the first frame between NECK_RANGE of its+height — down half the body below it. A body with no neck narrower than its head (a hood, a robe) has its narrowest row+at the range's top, so its crop starts in the head and holds the head and the chest, which turn with it."""+from __future__ import annotations++from typing import Any++from PIL import Image++from sprite_gen._deps import np++READING = "torso-side-v1"+SIDE_SHOWN_MIN = 0.10+TURN_SIDE_MAX = 0.0+TURN_RUN_MIN = 4+MODES = ("warn", "refuse") # --body-turn: a cut that holds a turn, where none without it holds a cycle, warned of or refused+SOLID = 128 # an alpha at least this is the body+HEAD_SHARE = 0.15 # the head's centre: the middle of the solid pixels of the top 15 % of the body's box+HEAD_REACH = 0.3 # ... of those within this share of the body's height of it, read again until it settles+UPPER = (0.0, 0.45) # the still's head and shoulders, read for SIDE_SHOWN_MIN+NECK_RANGE = (0.10, 0.55) # where the neck is looked for, in shares of the body's height from its top+ROWS = np.arange(0.01, 1.0, 0.02) # the rows the profile is read at, each 2 % of the height tall+CROP = (48, 64) # every crop is read at this size+LUMA = np.array([0.299, 0.587, 0.114])+++def _body(frame: Image.Image) -> tuple[np.ndarray, int, int, float] | str:+ """The frame's solid pixels, its box's top row and height, and its head's centre column (HEAD_SHARE, HEAD_REACH);+ where they are not read, why, said of the frame: no solid pixel, or no head to centre on — the top's parts lie+ apart either side of their middle, none within HEAD_REACH of it."""+ solid = np.asarray(frame.getchannel("A")) >= SOLID+ rows = np.nonzero(solid.any(axis=1))[0]+ if not len(rows):+ return "has no solid body to read"+ top, height = int(rows[0]), int(rows[-1]) - int(rows[0]) + 1+ mass = solid[top:top + max(2, int(HEAD_SHARE * height))].sum(axis=0).astype(np.float64)+ cols = np.arange(len(mass))+ centre = float((mass * cols).sum() / mass.sum())+ for _ in range(20):+ near = np.abs(cols - centre) <= HEAD_REACH * height+ if not mass[~near].any():+ break+ if not mass[near].any():+ return (f"has no head to centre on: the top {HEAD_SHARE * 100:g} % of its body holds parts apart, none "+ f"within {HEAD_REACH:g} of its height of their middle")+ moved = float((mass * near * cols).sum() / (mass * near).sum())+ settled = abs(moved - centre) < 0.25+ centre = moved+ if settled:+ break+ return solid, top, height, centre+++def _unit(*planes: np.ndarray) -> np.ndarray:+ v = np.concatenate([p.ravel() for p in planes])+ v = v - v.mean()+ return v / (np.linalg.norm(v) or 1.0)+++def _crop(frame: Image.Image, body: tuple[np.ndarray, int, int, float], rows: tuple[float, float],+ held: float | None = None) -> tuple[np.ndarray, np.ndarray, float] | str:+ """The crop of `rows` (shares of the body's height from its top) about the head's centre, `held` wide (a share of+ the height; where None, the frame's own extent across those rows, about the head), read at CROP: unit vectors of+ its luma times alpha and its alpha, of the same mirrored about the head's centre, and the width held. Where it+ holds nothing to read, why, said of the frame — no solid pixel across those rows (the width the frame's own), a+ crop of no width, or one of a single value throughout (an empty crop's 0): not read as a torso at 0."""+ solid, top, height, centre = body+ r0 = top + int(rows[0] * height)+ r1 = max(r0 + 2, top + int(rows[1] * height))+ span = f"rows {rows[0]:.2f}-{rows[1]:.2f} of its height"+ if held is None:+ cols = np.nonzero(solid[r0:r1].any(axis=0))[0]+ if not len(cols):+ return f"has no solid pixel in its {span}"+ held = 2 * max(centre - cols.min(), cols.max() - centre) / height+ half = held * height / 2+ box = (int(round(centre - half)), r0, int(round(centre + half)), r1)+ if box[2] <= box[0]:+ return f"has a crop of no width over its {span}"+ y = np.asarray(frame.crop(box).resize(CROP, Image.Resampling.LANCZOS), dtype=np.float64) / 255.0+ luma, alpha = (y[..., :3] @ LUMA) * y[..., 3], y[..., 3]+ v = _unit(luma, alpha)+ if not v.any():+ return f"has nothing to read in its crop of {span}"+ return v, _unit(luma[:, ::-1], alpha[:, ::-1]), held+++def neck(body: tuple[np.ndarray, int, int, float]) -> float:+ """The neck: of the rows in NECK_RANGE, the narrowest (the span holding the middle 96 % of the row's solid pixels,+ over the height), the topmost on a tie — a share of the body's height."""+ solid, top, height, _ = body+ widths = {}+ for f in ROWS:+ if not NECK_RANGE[0] <= f <= NECK_RANGE[1]:+ continue+ lo = top + int((f - 0.01) * height)+ mass = solid[lo:max(lo + 1, top + int((f + 0.01) * height))].sum(axis=0)+ share = np.cumsum(mass) / max(1.0, float(mass.sum()))+ widths[float(f)] = float(np.searchsorted(share, 0.98) - np.searchsorted(share, 0.02)) / height+ return min(widths, key=lambda f: (widths[f], f))+++def torso_rows(at: float) -> tuple[float, float]:+ """The torso's rows: from the neck `at` down half the body below it."""+ return at, at + (1 - at) / 2+++def turns(side: list[float | None]) -> list[dict[str, Any]]:+ """The turns of a clip read `side`: each run of TURN_RUN_MIN frames or more in a row whose side is under+ TURN_SIDE_MAX (a frame not read, None, ends a run), its first and last frame and its least side and where."""+ out = []+ k = 0+ while k < len(side):+ end = k+ while end < len(side) and side[end] is not None and side[end] < TURN_SIDE_MAX:+ end += 1+ if end - k >= TURN_RUN_MIN:+ at = min(range(k, end), key=lambda j: side[j])+ out.append({"from": k, "to": end - 1, "least": side[at], "at": at})+ k = max(end, k + 1)+ return out+++def read(frames: list[Image.Image]) -> dict[str, Any]:+ """The clip's facing against its first frame (`frames`, the clip as keyed, RGBA): the record the loop report keeps+ (`body_turn`) — the reading, its bounds, the frame read against (`reference`), the still's own side (`still_side`),+ whether it was read (`why` where not), the neck, each frame's `side` and the `turns`. A frame not read is None in+ `side`, and `unread` says why, each why with its frames (where any is)."""+ out: dict[str, Any] = {"reading": READING, "bounds": {"SIDE_SHOWN_MIN": SIDE_SHOWN_MIN, "TURN_SIDE_MAX": TURN_SIDE_MAX,+ "TURN_RUN_MIN": TURN_RUN_MIN},+ "reference": 0, "turns": []}+ if not frames:+ return {**out, "read": False, "still_side": None, "why": "the clip has no frames"}+ first = frames[0]+ still = _body(first)+ if isinstance(still, str):+ return {**out, "read": False, "still_side": None, "why": f"the clip's first frame {still}"}+ upper = _crop(first, still, UPPER)+ if isinstance(upper, str):+ return {**out, "read": False, "still_side": None, "why": f"the clip's first frame {upper}"}+ s, m, _ = upper+ out["still_side"] = round(1 - float(s @ m), 4)+ if out["still_side"] < SIDE_SHOWN_MIN:+ return {**out, "read": False,+ "why": f"the still is seen square: its head and shoulders lie {out['still_side']:.2f} off their mirror, under "+ f"{SIDE_SHOWN_MIN:g} (a front or back view), and its facing is not read"}+ at = neck(still)+ out["neck"] = round(at, 2)+ rows = torso_rows(at)+ torso = _crop(first, still, rows)+ if isinstance(torso, str):+ return {**out, "read": False, "why": f"the clip's first frame {torso}, its torso's from the neck down"}+ s, m, held = torso+ shown = 1 - float(s @ m)+ out["torso_still_side"] = round(shown, 4)+ if shown <= 1e-6:+ return {**out, "read": False, "why": "the still's torso is its own mirror: no side to read it by"}+ side: list[float | None] = []+ unread: dict[str, list[int]] = {}+ for k, frame in enumerate(frames):+ body = _body(frame)+ crop = body if isinstance(body, str) else _crop(frame, body, rows, held)+ if isinstance(crop, str):+ side.append(None)+ unread.setdefault(crop, []).append(k)+ continue+ v, _, _ = crop+ side.append(round((float(v @ s) - float(v @ m)) / shown, 4))+ out = {**out, "read": True, "side": side, "turns": turns(side)}+ if unread:+ out["unread"] = [{"frames": ks, "why": why} for why, ks in unread.items()]+ return out+++def spans(frames: list[int]) -> str:+ """Frames in runs, in words: `40-42`, `22-23 and 36-45`."""+ runs: list[list[int]] = []+ for k in sorted(frames):+ if runs and k == runs[-1][1] + 1:+ runs[-1][1] = k+ else:+ runs.append([k, k])+ return " and ".join(f"{a}-{b}" if b > a else f"{a}" for a, b in runs)+++def turned(reading: dict[str, Any]) -> set[int]:+ """The clip frames inside the reading's turns."""+ return {k for turn in reading["turns"] for k in range(turn["from"], turn["to"] + 1)}+++class Turn:+ """A cut's word on the turn, for the cut search (`local_cycle.detect`'s, `by_steps`' and `counted`'s `turn`): why+ the cut s/L (in the search's frames, the clip's after its first `skip`) is refused — it holds a frame of a turn —+ or None. Each refusal is counted (`refused`)."""++ def __init__(self, reading: dict[str, Any], skip: int = 0):+ self.frames = turned(reading)+ self.skip = skip+ self.refused = 0++ def held(self, start: int, length: int) -> list[int]:+ """The turned frames of the clip a cut s/L in the search's frames holds."""+ return sorted(self.frames & set(range(start + self.skip, start + self.skip + length)))++ def __call__(self, start: int, length: int) -> str | None:+ held = self.held(start, length)+ if not held:+ return None+ self.refused += 1+ return f"the body turns (clip frames {spans(held)})"+++def _over(reading: dict[str, Any]) -> str:+ spans = [f"{t['from']}-{t['to']}" for t in reading["turns"]]+ least = min(reading["turns"], key=lambda t: t["least"])+ return (f"its torso faces nearer the still's mirror than the still over frames {' and '.join(spans)} (least "+ f"{least['least']:+.2f} at frame {least['at']}; a turn is a torso under {TURN_SIDE_MAX:g} for {TURN_RUN_MIN} "+ "frames or more)")+++def refusal(reading: dict[str, Any], *, cut: tuple[int, int] | None = None, held: list[int] | None = None) -> str:+ """The refusal of `--body-turn refuse`, after `video-loop: `: the turn, and that no cut without it holds two steps+ that repeat — or, where a cut was found that holds it (`cut`, in the clip's frames, and its turned frames `held`),+ which — and the clip to be filmed again at the still's angle."""+ found = (f", and the cut {cut[0]}/{cut[1]} holds frames {spans(held)} of it" if cut is not None and held+ else ", and no cut that leaves those frames out holds two steps that repeat")+ return f"the body turns in the walk — {_over(reading)}{found}: film it again with the torso and hips kept at the still's angle"+++def kept(reading: dict[str, Any], *, cut: tuple[int, int], held: list[int]) -> str:+ """The warning of `--body-turn warn` over a cut that holds the turn (in the clip's frames), where no cut without it+ holds two steps that repeat."""+ return (f"the body turns in the walk — {_over(reading)}, and the cut {cut[0]}/{cut[1]} holds frames {spans(held)} "+ "of it: no cut that leaves those frames out holds two steps that repeat — kept as cut; --body-turn refuse "+ "refuses such a clip, to be filmed again at the still's angle")+++def unfound(reading: dict[str, Any]) -> str:+ """The warning of `--body-turn warn` where no cut holds two steps that repeat, with the turn or without it."""+ return (f"the body turns in the walk — {_over(reading)}: no cut holds two steps that repeat, with those frames or "+ "without them; --body-turn refuse names the turn as the reason, to be filmed again at the still's angle")diff --git a/sprite_gen/video/local_cycle.py b/sprite_gen/video/local_cycle.pyindex d1d5535..572a876 100644--- a/sprite_gen/video/local_cycle.py+++ b/sprite_gen/video/local_cycle.py@@ -92,7 +92,7 @@ def _held(measured):return {'skipped': measured['skipped']} if 'skipped' in measured else {'seam': measured['seam'], 'closes': measured['closes']}-def _held_rank(candidates, calm, chosen, wrap_pop, held_edge, length_cap=None, double=True):+def _held_rank(candidates, calm, chosen, wrap_pop, held_edge, length_cap=None, double=True, turn=None):"""Below the top band (`held_edge`, repair.held_edge on the side the popping first choice holds itspart): among the calm candidates, those whose held side closes, the same score tolerance, then thesmallest held seam. When no candidate closes it, windows twice a candidate's length: the candidate@@ -101,7 +101,7 @@ def _held_rank(candidates, calm, chosen, wrap_pop, held_edge, length_cap=None, dstep). Such a window is two lengths of a repeat the search confirmed, not itself seen repeating; itis taken when its held side closes and its top does not pop, the smallest held seam first. A window longer than `length_cap`(an explicit --max-len) is not one, and none is read without `double` (the steps were counted,- `video-loop --steps`). Returns (picked or None, record)."""+ `video-loop --steps`), nor one `turn` refuses (`detect`). Returns (picked or None, record)."""side = held_edge.side(chosen['start'], chosen['length'])if 'skipped' in side:return None, {'method': 'held-side-edge-v1', 'skipped': side['skipped']}@@ -139,6 +139,8 @@ def _held_rank(candidates, calm, chosen, wrap_pop, held_edge, length_cap=None, dcounts = {'measured': 0, 'unread': 0, 'top_pops': 0}for length in lengths:for start in range(held_edge.frames-length+1):+ if turn is not None and turn(start, length) is not None:+ continuemeasured = held_edge.seam(start, length, side)if 'skipped' in measured:counts['unread'] += 1@@ -163,7 +165,7 @@ def _held_rank(candidates, calm, chosen, wrap_pop, held_edge, length_cap=None, dreturn None, record-def _shape_rank(candidates, chosen, wrap_pop, held_edge=None, length_cap=None, double=True):+def _shape_rank(candidates, chosen, wrap_pop, held_edge=None, length_cap=None, double=True, turn=None):"""Choose again when the chosen cut's top pops at the wrap (`wrap_pop`, repair.seam_pop on theanalysed frames): among the candidates whose top was read and does not pop, the same scoretolerance, then the smallest pop. Nothing is measured past the first choice when it does not pop,@@ -193,7 +195,7 @@ def _shape_rank(candidates, chosen, wrap_pop, held_edge=None, length_cap=None, drecord.update(measured=len(candidates)-unread, unread=unread)held = Noneif held_edge is not None:- picked, held = _held_rank(candidates, calm, chosen, wrap_pop, held_edge, length_cap, double)+ picked, held = _held_rank(candidates, calm, chosen, wrap_pop, held_edge, length_cap, double, turn)record['held_edge'] = heldif picked is not None:record.update(applied=True, chosen={'start': picked['start'], 'length': picked['length'], 'pop': picked['seam_pop'],@@ -248,17 +250,20 @@ def _pop_gate(chosen, rest, pop_gate):return picked, record-def counted(distances, trajectory, *, min_len, max_len, periodicity_min, signals=None, pop_gate=None):+def counted(distances, trajectory, *, min_len, max_len, periodicity_min, signals=None, pop_gate=None, turn=None):"""A cut of a length someone counted (`video-loop --steps`) where the clip is too short to see awindow that long repeat (`detect` found none): the counted length stands for the repeat. Everywindow [min_len, max_len] long with two clip frames before it is read, and the one whose wrap isnearest the clip's own way on there is taken (`_closure`, the earliest on a tie); whether it closesis the seam gate's word. With `pop_gate`, a window the seam pop gate would refuse gives way to the next nearest- (`_pop_gate`, `seam_pop_gate`). Raises ValueError where no window has room."""+ (`_pop_gate`, `seam_pop_gate`), and none `turn` refuses is read (`detect`). Raises ValueError where no window has+ room."""n = len(distances)rows = []for length in range(min_len, max_len+1):for start in range(2, n-length+1):+ if turn is not None and turn(start, length) is not None:+ continuemeasured = _closure(distances, start, length)if measured is None:continue@@ -307,7 +312,7 @@ def judged(rows, judge):def detect(distances, trajectory, *, min_len, max_len, gait_floor,periodicity_min, double_tolerance, double_search, max_fraction=.5, signals=None, wrap_pop=None,- held_edge=None, length_cap=None, double=True, closure=False, judge=None, pop_gate=None):+ held_edge=None, length_cap=None, double=True, closure=False, judge=None, pop_gate=None, turn=None):"""`wrap_pop(start, length)`, when given, is the top band's jump at that cut's wrap(repair.seam_pop): a chosen cut that pops is chosen again (`_shape_rank`), and a search that findsnothing raises with the windows it refused, popping ones last (`ValueError.diagnostics`).@@ -332,7 +337,11 @@ def detect(distances, trajectory, *, min_len, max_len, gait_floor,`judge(start, length)` (crossings.Reading.judge), when given, refuses a window whose steps the clip'scrossings count as other than two ('one step', 'three steps': `refuted`), and a search that finds- nothing names each refused window's count (`step_count`), those the crossings refute last."""+ nothing names each refused window's count (`step_count`), those the crossings refute last.++ `turn(start, length)` (body_turn.Turn), when given, refuses a window whose cut holds a frame of a body turn, where+ the judge would read it, with its words ('the body turns (clip frames a-b)'), and so does the held side's window+ two lengths long (`_held_rank`); every candidate holds none."""n = len(distances)# A cycle has to be seen repeating: half the clip by default, more for the gait fallback, and as# long as the caller's own ceiling allows.@@ -389,6 +398,11 @@ def detect(distances, trajectory, *, min_len, max_len, gait_floor,if min(first_motion, second_motion) < .25*step:refuse('a still segment')continue+ if turn is not None:+ why = turn(start, length)+ if why is not None:+ refuse(why)+ continueif judge is not None:counted = judge(start, length)if counted['verdict'] == 'refuted':@@ -445,7 +459,7 @@ def detect(distances, trajectory, *, min_len, max_len, gait_floor,chosen = min(equivalent, key=lambda row: (row['start'], row['score'], row['length']))shape = Noneif wrap_pop is not None:- chosen, shape = _shape_rank(candidates, chosen, wrap_pop, held_edge, length_cap, double)+ chosen, shape = _shape_rank(candidates, chosen, wrap_pop, held_edge, length_cap, double, turn)gate = Noneif pop_gate is not None:rest = sorted((row for row in candidates if (row['start'], row['length']) != (chosen['start'], chosen['length'])),@@ -536,7 +550,7 @@ def _gates(tried, seam_max):def by_steps(distances, trajectory, reading, *, found, refused, min_len, max_len, seam_flow, wrap_pop, seam_gate, flow_limit,- seam_max, gait_floor, periodicity_min, signals, pop_gate=None):+ seam_max, gait_floor, periodicity_min, signals, pop_gate=None, turn=None):"""The cut the clip's own steps choose (`reading`, crossings.Reading), after the pixel search: `found`, its cut,or `refused`, why it found none. Returns (the cut, or None where the search's word stands and it found none;`step_count`, the record).@@ -571,7 +585,10 @@ def by_steps(distances, trajectory, reading, *, found, refused, min_len, max_lenA cut taken on two steps records `steps` (count 2, by crossings): `video-cycle-align` reads a return half wayas its step, and the step screen's pixel suspicion of one step (`step_screen`) is settled, kept as- `pixel_suspect`."""+ `pixel_suspect`.++ With `turn` (body_turn.Turn), a two-step cut that holds a frame of a body turn is not one of them (`turned_out`+ counts those left out), as the search refused such a window."""record = reading.record()record['search'] = ({'cut': [found['start'], found['length']]} if found is not None else {'refused': str(refused)})if not reading.readable:@@ -593,6 +610,10 @@ def by_steps(distances, trajectory, reading, *, found, refused, min_len, max_lenrecord.update(chosen_by='search', cut=counted)return found, recordtwos = reading.twos(min_len, max_len)+ if turn is not None:+ kept = [counted for counted in twos if turn(*counted['cut']) is None]+ record['turned_out'] = len(twos)-len(kept)+ twos = keptrecord['two_cuts'] = len(twos)if not twos:record['chosen_by'] = 'search'@@ -695,6 +716,7 @@ def step_verdict(cycle):f"seam {declined['seam']:g}): the search's cut {s}/{L} stands, {counted['cut']['verdict']} by the count "f"({counted['cut']['why']})")elif 'two_cuts' in counted and counted['two_cuts'] == 0:- out.append(f"the clip shows its steps (crossings {counted['crossings']}) but no cut of two: the cut {s}/{L} is "+ turned = f" that leaves the body's turn out ({counted['turned_out']} hold it)" if counted.get('turned_out') else ''+ out.append(f"the clip shows its steps (crossings {counted['crossings']}) but no cut of two{turned}: the cut {s}/{L} is "f"{counted['cut']['verdict']} ({counted['cut']['why']}) — count its steps")return outdiff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.pyindex 28cda9b..4cf2190 100644--- a/sprite_gen/video/loop.py+++ b/sprite_gen/video/loop.py@@ -51,6 +51,7 @@ from sprite_gen.util.resample import resize_cellfrom sprite_gen.video import motion_anchor, auto_motion, local_cycle, gait_fallback, nonloop, effectfrom sprite_gen.video import crossings as crossings_modfrom sprite_gen.video import held as held_mod+from sprite_gen.video import body_turn as body_turn_modfrom sprite_gen.video import legs as legs_modfrom sprite_gen.video import period as period_modfrom sprite_gen.video import repair as repair_mod@@ -1556,14 +1557,15 @@ def cycle_apart(files: list[Path], *, start: int, length: int, skip: int, analysdef _by_steps(cycle: dict[str, Any] | None, refused: ValueError | None, *, frames: list[Image.Image], analysis: dict[str, Any],D: np.ndarray, trajectory: np.ndarray, window: CutWindow, searched: dict[str, Any], detect: dict[str, Any],- seam_max: float, cells: CutOnCells) -> dict[str, Any]:+ seam_max: float, cells: CutOnCells, turn: body_turn_mod.Turn | None = None) -> dict[str, Any]:"""The cut the clip's own steps choose (`local_cycle.by_steps`, the crossings of the frames the search read,sprite_gen/video/crossings.py), recorded `step_count`, from the search's cut or its refusal (`refused`).`cells` reads a cut of `frames` before it is cut as the seam gate and the seam pop gate read the loop.Where the clip shows its steps but no cut of two, and the search's cut is one they refute (one step, three), thesearch runs again on the window it searched (`searched`) refusing such cuts (`detect`'s `judge`). A search that- finds nothing names each refused window's count, those the crossings refute last, and raises."""+ finds nothing names each refused window's count, those the crossings refute last, and raises. With `turn`, no cut+ that holds a frame of a body turn is taken, a two-step cut or the search's again."""signals = leg_signals(frames)try:reading = crossings_mod.read(crossings_mod.foot_signals(frames, gap=signals["gap"] if signals else None))@@ -1574,12 +1576,13 @@ def _by_steps(cycle: dict[str, Any] | None, refused: ValueError | None, *, frameD, trajectory, reading, found=cycle, refused=refused, min_len=window.lo, max_len=window.max_len or len(frames),seam_flow=SeamFlow(frames, analysis), wrap_pop=wrap_pop_on(moved), seam_gate=cells.seam, pop_gate=cells.gate,flow_limit=repair_mod.FLOW_LIMIT, seam_max=seam_max,- gait_floor=detect["gait_floor"], periodicity_min=detect["periodicity_min"], signals=signals)+ gait_floor=detect["gait_floor"], periodicity_min=detect["periodicity_min"], signals=signals, turn=turn)if picked is not None and record.get("cut", {}).get("verdict") == "refuted":first = record["cut"]try:picked = local_cycle.detect(D, trajectory, signals=signals, wrap_pop=wrap_pop_on(moved), held_edge=HeldEdge(moved),- length_cap=window.max_len, judge=reading.judge, pop_gate=cells.gate, **searched, **detect)+ length_cap=window.max_len, judge=reading.judge, pop_gate=cells.gate, turn=turn,+ **searched, **detect)except ValueError as exc:picked, refused = None, excrecord["searched_again"] = {"refuted": first, "why": f"no cut of two steps, and the search's cut is {first['why']}: "@@ -1609,7 +1612,8 @@ def _by_steps(cycle: dict[str, Any] | None, refused: ValueError | None, *, framedef _counted(cycle: dict[str, Any], steps: int, *, window: CutWindow, D: np.ndarray, trajectory: np.ndarray,- frames: list[Image.Image], moved: list[np.ndarray], detect: dict[str, Any], cells: CutOnCells) -> dict[str, Any]:+ frames: list[Image.Image], moved: list[np.ndarray], detect: dict[str, Any], cells: CutOnCells,+ turn: body_turn_mod.Turn | None = None) -> dict[str, Any]:"""The cut once its steps are counted (`--steps`): 2 keeps it; 1 cuts again in the window two ofits lengths long, [2L-1, 2L+1], inside the caller's bounds (`window.within`) — not half the clip —with the same search (a repeat seen in the clip, the top band and the held side read again) save that@@ -1618,7 +1622,8 @@ def _counted(cycle: dict[str, Any], steps: int, *, window: CutWindow, D: np.ndarbounds disagree: a failure, neither followed. Where they leave part of it, that part is read(`steps.window`, beside `steps.counted_window`). A clip too short to see such a window repeat is cutall the same, the count standing for the repeat (`local_cycle.counted`, `unseen` says why);- `cycle.coverage` and the seam gate say the rest. Recorded `steps` (`first_cut`: the cut counted)."""+ `cycle.coverage` and the seam gate say the rest. Recorded `steps` (`first_cut`: the cut counted). With `turn`, no cut+ that holds a frame of a body turn is taken."""first = {"start": cycle["start"], "length": cycle["length"]}if steps == 2:cycle["steps"] = {"count": 2, "by": "given", "given": 2}@@ -1638,12 +1643,12 @@ def _counted(cycle: dict[str, Any], steps: int, *, window: CutWindow, D: np.ndartry:found = local_cycle.detect(D, trajectory, min_len=lo, max_len=hi, length_cap=hi, signals=signals,wrap_pop=wrap_pop_on(moved), held_edge=HeldEdge(moved), double=False, closure=True,- pop_gate=cells.gate, **detect)+ pop_gate=cells.gate, turn=turn, **detect)except ValueError as unseen:# Too short a clip to see the cycle repeat: the count stands for it (`cycle.coverage` says how short).try:found = local_cycle.counted(D, trajectory, min_len=lo, max_len=hi, periodicity_min=detect["periodicity_min"],- signals=signals, pop_gate=cells.gate)+ signals=signals, pop_gate=cells.gate, turn=turn)except ValueError as exc:failed = ValueError(f"--steps 1: the cut of {first['length']} frames from {first['start']} is one step, and the clip "f"({len(D)} frames) has no window {lo}-{hi} frames long to cut: {exc}")@@ -1654,6 +1659,75 @@ def _counted(cycle: dict[str, Any], steps: int, *, window: CutWindow, D: np.ndarreturn found+def _motion_auto(frames: list[Image.Image], files: list[Path], D: np.ndarray, trajectory: np.ndarray, analysis: dict[str, Any],+ *, fps: float, window: CutWindow, prof: LoopProfile, steps: int | None, seam_max: float,+ seam_pop_max: float | None, scratch: _Scratch, said: dict[str, Any],+ turn: body_turn_mod.Turn | None = None) -> tuple[dict[str, Any], list[Path], dict[str, Any]]:+ """`--anchor motion-auto`'s cut of `frames` — the clip after its lead-in, held, `files` written of them and `D`,+ `trajectory` and `analysis` read on them (auto_motion.analyse): the search, the gait fallback after a first search+ that finds nothing, then the count, given (`steps`, `_counted`) or the clip's crossings (`_by_steps`). Returns the+ cut, and the files and the analysis it was read on (the gait fallback's, where it scaled the frames back); `said`+ takes what the report adds (`automatic_motion_analysis` read again, `gait_fallback`), whether a cut is found or the+ search raises. With `turn` (body_turn.Turn), no cut that holds a frame of a body turn is taken."""+ lo, hi = window.lo, window.hi+ detect = dict(gait_floor=round(prof.min_seconds*fps), periodicity_min=PERIODICITY_MIN,+ double_tolerance=GAIT_DOUBLE_TOL, double_search=GAIT_DOUBLE_SEARCH)+ searched: dict[str, Any] = {"min_len": lo, "max_len": hi}+ refused: ValueError | None = None+ cycle = None+ # The cuts the search chooses among, read before one is cut as the seam gate and the seam pop gate read the loop.+ cells = CutOnCells(frames, pop_max=seam_pop_max)+ try:+ moved = moved_alpha(frames, analysis)+ cycle = local_cycle.detect(D, trajectory, min_len=lo, max_len=hi, signals=leg_signals(frames),+ wrap_pop=wrap_pop_on(moved), held_edge=HeldEdge(moved), length_cap=window.max_len,+ pop_gate=cells.gate, turn=turn, **detect)+ except ValueError as first:+ # A front or back gait that walked toward the camera, or a slow one: one more+ # search, recorded (`gait_fallback`), and only after the first found nothing.+ drift = gait_fallback.cycle_drift(frames, min_lag=lo, max_lag=hi)+ fallback = {"reason": str(first), "scale_drift": {k: drift[k] for k in ("height_first_px", "height_last_px", "drift", "method")},+ "scale_drift_min": gait_fallback.SCALE_DRIFT_MIN, "scale_undone": False}+ if abs(drift["drift"]) >= gait_fallback.SCALE_DRIFT_MIN:+ fallback["padding_ltrb"] = list(gait_fallback.undo_padding(frames, drift))+ frames = gait_fallback.undo_scale(frames, drift, pad=tuple(fallback["padding_ltrb"]))+ files = gait_fallback.write_frames(frames, [f.name for f in files], scratch.new())+ D, trajectory, analysis = auto_motion.analyse(frames, fps=fps)+ said["automatic_motion_analysis"] = analysis+ fallback["scale_undone"] = True+ cells = CutOnCells(frames, pop_max=seam_pop_max)+ # An explicit --max-len is the caller's ceiling and stays one.+ hi_long = window.past(gait_fallback.long_window(lo, len(files), fps))+ fallback["window"] = [lo, hi_long]+ said["gait_fallback"] = fallback+ searched = {"min_len": lo, "max_len": hi_long, "max_fraction": gait_fallback.LONG_CYCLE_FRACTION}+ try:+ moved = moved_alpha(frames, analysis)+ cycle = local_cycle.detect(D, trajectory, min_len=lo, max_len=hi_long,+ max_fraction=gait_fallback.LONG_CYCLE_FRACTION,+ signals=leg_signals(frames), wrap_pop=wrap_pop_on(moved),+ held_edge=HeldEdge(moved), length_cap=window.max_len, pop_gate=cells.gate, turn=turn,+ **detect)+ except ValueError as second:+ failed = ValueError(f"{second} (also with the gait fallback: window [{lo}, {hi_long}], "+ f"scale drift {drift['drift']:+.1%}{', undone' if fallback['scale_undone'] else ''})")+ # The windows the wider search measured and refused go into the report's `cycle`.+ if hasattr(second, "diagnostics"):+ failed.diagnostics = second.diagnostics # type: ignore[attr-defined]+ failed.__cause__ = first+ refused, cycle = failed, None+ if steps is not None:+ # A count given is the word on the search's cut; the crossings are not asked.+ if refused is not None:+ raise refused+ cycle = _counted(cycle, steps, window=window, D=D, trajectory=trajectory, frames=frames, moved=moved,+ detect=detect, cells=cells, turn=turn)+ else:+ cycle = _by_steps(cycle, refused, frames=frames, analysis=analysis, D=D, trajectory=trajectory,+ window=window, searched=searched, detect=detect, seam_max=seam_max, cells=cells, turn=turn)+ return cycle, files, analysis++def _from_lead_in(record: Any, lead: int) -> Any:"""A search's record (a cut, or the windows a refusal measured) in the clip's own frame numbers: thesearch read the clip after its first `lead` frames, so every `start` and `context_pair_range` it wrote@@ -1820,6 +1894,7 @@ def _cut_loop(wrap_blend: str = "auto",unfixed: str = "warn",seam_pop_max: float | None = repair_mod.SEAM_POP_REFERENCE,+ body_turn: str = "warn",) -> dict[str, Any]:state = state.strip().lower() if state else stateif state == effect.STATE:@@ -1857,6 +1932,8 @@ def _cut_loop(raise SystemExit(f"video-loop: unknown --facing {facing!r}; expected one of {', '.join(FACINGS)}")if seam_pop_max is not None and not (math.isfinite(seam_pop_max) and seam_pop_max > 0):raise SystemExit(f"video-loop: --seam-pop-max {seam_pop_max}: a bound over 0, or off")+ if body_turn not in body_turn_mod.MODES:+ raise SystemExit(f"video-loop: unknown --body-turn {body_turn!r}; expected one of {', '.join(body_turn_mod.MODES)}")if anchor is None:# gaits drift a few pixels over a cycle and the wrap shows it; in-place states do notanchor = "body" if profile_for(state).gait else "none"@@ -1871,6 +1948,9 @@ def _cut_loop(raise SystemExit("video-loop: --anchor motion-auto requires walk/run with automatic or periodic selection; no fixed cut")if steps is not None and anchor != "motion-auto":raise SystemExit("video-loop: --steps counts the steps in the cut --anchor motion-auto takes; pass --anchor motion-auto")+ if body_turn == "refuse" and anchor != "motion-auto":+ raise SystemExit("video-loop: --body-turn refuse reads the body's turn in the walk --anchor motion-auto searches; "+ "pass --anchor motion-auto")if cycle_mode not in CYCLE_MODES:raise SystemExit(f"video-loop: unknown --cycle {cycle_mode!r}; expected one of {', '.join(CYCLE_MODES)}")given = frames_dir@@ -1936,59 +2016,58 @@ def _cut_loop(report_base["size_hold"] = {"applied": False, "why": "--size-hold off"}D, trajectory, analysis = auto_motion.analyse(source_frames, fps=fps)report_base["automatic_motion_analysis"] = analysis- detect = dict(gait_floor=round(prof.min_seconds*fps), periodicity_min=PERIODICITY_MIN,- double_tolerance=GAIT_DOUBLE_TOL, double_search=GAIT_DOUBLE_SEARCH)- searched: dict[str, Any] = {"min_len": lo, "max_len": hi}- refused: ValueError | None = None- # The cuts the search chooses among, read before one is cut as the seam gate and the seam pop gate read the loop.- cells = CutOnCells(source_frames, pop_max=seam_pop_max)- try:- moved = moved_alpha(source_frames, analysis)- cycle = local_cycle.detect(D, trajectory, min_len=lo, max_len=hi, signals=leg_signals(source_frames),- wrap_pop=wrap_pop_on(moved), held_edge=HeldEdge(moved), length_cap=window.max_len,- pop_gate=cells.gate, **detect)- except ValueError as first:- # A front or back gait that walked toward the camera, or a slow one: one more- # search, recorded (`gait_fallback`), and only after the first found nothing.- drift = gait_fallback.cycle_drift(source_frames, min_lag=lo, max_lag=hi)- fallback = {"reason": str(first), "scale_drift": {k: drift[k] for k in ("height_first_px", "height_last_px", "drift", "method")},- "scale_drift_min": gait_fallback.SCALE_DRIFT_MIN, "scale_undone": False}- if abs(drift["drift"]) >= gait_fallback.SCALE_DRIFT_MIN:- fallback["padding_ltrb"] = list(gait_fallback.undo_padding(source_frames, drift))- source_frames = gait_fallback.undo_scale(source_frames, drift, pad=tuple(fallback["padding_ltrb"]))- files = gait_fallback.write_frames(source_frames, [f.name for f in files], scratch.new())- D, trajectory, analysis = auto_motion.analyse(source_frames, fps=fps)- report_base["automatic_motion_analysis"] = analysis- fallback["scale_undone"] = True- cells = CutOnCells(source_frames, pop_max=seam_pop_max)- # An explicit --max-len is the caller's ceiling and stays one.- hi_long = window.past(gait_fallback.long_window(lo, len(files), fps))- fallback["window"] = [lo, hi_long]- report_base["gait_fallback"] = fallback- searched = {"min_len": lo, "max_len": hi_long, "max_fraction": gait_fallback.LONG_CYCLE_FRACTION}+ search = partial(_motion_auto, source_frames, files, D, trajectory, analysis, fps=fps, window=window, prof=prof,+ steps=steps, seam_max=seam_max, seam_pop_max=seam_pop_max, scratch=scratch)+ # The body's turn (sprite_gen/video/body_turn.py), read on the clip as keyed against its first frame, the still,+ # lead-in or not: a cut that holds a frame of one is not taken while another holds a cycle. Where none does,+ # --body-turn warn takes the cut the search takes with the turn in, and says so; refuse refuses the clip in a line+ # of its own. A clip that turns nowhere is searched once, as before.+ turning = {**body_turn_mod.read(gait_frames), "mode": body_turn}+ report_base["body_turn"] = turning+ turn = body_turn_mod.Turn(turning, skip) if turning["turns"] else None+ if turn is None:+ turning["verdict"] = "none" if turning["read"] else "not-read"+ said: dict[str, Any] = {}+ found = avoided = None+ if turn is not None:try:- moved = moved_alpha(source_frames, analysis)- cycle = local_cycle.detect(D, trajectory, min_len=lo, max_len=hi_long,- max_fraction=gait_fallback.LONG_CYCLE_FRACTION,- signals=leg_signals(source_frames), wrap_pop=wrap_pop_on(moved),- held_edge=HeldEdge(moved), length_cap=window.max_len, pop_gate=cells.gate, **detect)- except ValueError as second:- failed = ValueError(f"{second} (also with the gait fallback: window [{lo}, {hi_long}], "- f"scale drift {drift['drift']:+.1%}{', undone' if fallback['scale_undone'] else ''})")- # The windows the wider search measured and refused go into the report's `cycle`.- if hasattr(second, "diagnostics"):- failed.diagnostics = second.diagnostics # type: ignore[attr-defined]- failed.__cause__ = first- refused, cycle = failed, None- if steps is not None:- # A count given is the word on the search's cut; the crossings are not asked.- if refused is not None:- raise refused- cycle = _counted(cycle, steps, window=window, D=D, trajectory=trajectory, frames=source_frames, moved=moved,- detect=detect, cells=cells)- else:- cycle = _by_steps(cycle, refused, frames=source_frames, analysis=analysis, D=D, trajectory=trajectory,- window=window, searched=searched, detect=detect, seam_max=seam_max, cells=cells)+ found = search(said=said, turn=turn)+ except ValueError as exc:+ avoided = exc+ turning["refused"] = turn.refused+ if found is None and body_turn == "refuse":+ report_base.update(said)+ turning["verdict"] = "refused"+ failed = ValueError(body_turn_mod.refusal(turning))+ if hasattr(avoided, "diagnostics"):+ failed.diagnostics = avoided.diagnostics # type: ignore[attr-defined]+ raise failed from avoided+ if found is None:+ said = {}+ try:+ found = search(said=said)+ except ValueError:+ report_base.update(said)+ if turn is not None:+ turning.update(verdict="unfound", avoiding=str(avoided))+ print(f"video-loop: warning: {body_turn_mod.unfound(turning)}", file=sys.stderr)+ raise+ report_base.update(said)+ cycle, files, analysis = found+ if turn is not None:+ cut = (cycle["start"] + skip, cycle["length"])+ holds = turn.held(cycle["start"], cycle["length"])+ turning["cut"] = {"frames": [cut[0], cut[0] + cut[1] - 1], "holds": holds}+ if avoided is not None:+ turning["avoiding"] = str(avoided)+ if not holds:+ turning["verdict"] = "avoided" if avoided is None and turn.refused else "clear"+ elif body_turn == "refuse":+ turning["verdict"] = "refused"+ raise ValueError(body_turn_mod.refusal(turning, cut=cut, held=holds))+ else:+ turning["verdict"] = "kept"+ print(f"video-loop: warning: {body_turn_mod.kept(turning, cut=cut, held=holds)}", file=sys.stderr)elif cycle_mode == "once":source_frames = [Image.open(f).convert("RGBA") for f in files]cycle = nonloop.select_cut(D, masses, fps=fps, ending=partial(@@ -2616,6 +2695,14 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:"not bounded by half the clip but held inside --min-len/--max-len: a window that leaves none of it ""fails), recorded `cycle.steps`; 2: the cut is kept, recorded. Either way the strip ""metadata says `steps: 2`, which `video-cycle-align` reads")+ parser.add_argument("--body-turn", choices=body_turn_mod.MODES, default="warn",+ help="--anchor motion-auto: the body's turn in the walk — each frame's torso read between the clip's first "+ "frame and that frame mirrored (`body_turn`, docs/video-pipeline.md section 4, \"The body turn\"; a "+ f"square still, a front or back view, is not read): a turn is the torso under {body_turn_mod.TURN_SIDE_MAX:g} "+ f"for {body_turn_mod.TURN_RUN_MIN} frames or more, and no cut that holds a frame of one is taken while "+ "another holds a cycle. Where none does: warn (default), the cut the search takes with the turn in, "+ "and a warning line; refuse, the clip is refused in a line of its own (`video-loop: the body turns "+ "in the walk`), to be filmed again at the still's angle")parser.add_argument("--name", default="loop", help="basename for strip/gif/webp outputs")parser.add_argument("--report", type=Path)@@ -2637,6 +2724,7 @@ def run(**kwargs: object) -> int:overlap_wrap=str(kwargs.get("overlap_wrap") or "on"), wrap_blend=str(kwargs.get("wrap_blend") or "auto"),unfixed=str(kwargs.get("unfixed") or "warn"),seam_pop_max=kwargs.get("seam_pop_max", repair_mod.SEAM_POP_REFERENCE), # type: ignore[arg-type]+ body_turn=str(kwargs.get("body_turn") or "warn"),)summary = {k: payload[k] for k in ("state", "frames_total", "window", "cycle_seconds", "n_out", "delay_ms", "resampled_seam_ratio", "specks_dropped", "report")}summary["cycle"] = {k: payload["cycle"].get(k) for k in ("kind", "start", "length", "period_global", "ratio", "review_recommended", "half_period_guard", "fundamental")}@@ -2666,6 +2754,8 @@ def run(**kwargs: object) -> int:if "step_count" in payload["cycle"]:counted = payload["cycle"]["step_count"]summary["cycle"]["step_count"] = {k: counted[k] for k in ("mode", "readable", "chosen_by", "cut", "why") if k in counted}+ if payload.get("body_turn", {}).get("turns"):+ summary["body_turn"] = {k: payload["body_turn"][k] for k in ("verdict", "turns", "cut") if k in payload["body_turn"]}if payload.get("ghost_screen", {}).get("ghosts") or payload.get("ghost_screen", {}).get("reads") is False:summary["ghost_screen"] = payload["ghost_screen"]for key in ("ghost_given_way", "ghost_kept"):diff --git a/tests/video/test_loop_body_turn.py b/tests/video/test_loop_body_turn.pynew file mode 100644index 0000000..1781621--- /dev/null+++ b/tests/video/test_loop_body_turn.py@@ -0,0 +1,463 @@+# SPDX-License-Identifier: Apache-2.0+"""A walk whose body turns inside its clip (docs/video-pipeline.md section 4, "The body turn";+sprite_gen/video/body_turn.py): each frame's torso is read between the clip's first frame and that frame mirrored+(`torso-side-v1`), a turn is the torso under TURN_SIDE_MAX for TURN_RUN_MIN frames or more, and `video-loop --anchor+motion-auto` takes no cut that holds a frame of one while another holds a cycle. Where none does, `--body-turn warn` (the+default) takes the cut it took before and says so; `--body-turn refuse` refuses the clip in a line of its own.++The walker is a back diagonal seen from behind: legs side by side swinging half a cycle apart, arms either side swinging+opposite, the arm on the facing side bright and the other dim, a light panel on the torso and the cheek on the head+toward the facing. Over a turn the facing goes over to the still's mirror and back (`facing` 1 the still's three-quarter+view, 0 square from behind, under 0 past it), the arms' tones crossing. A walker drawn square from behind (`square`) is+the back walk whose still shows no side. A frame the reading cannot read — no head to centre on, no solid pixel across+the still's torso rows, a crop of no width or with nothing in it, no frames — is not read, never read as 0 or as a+middle no pixel holds. Synthetic frames only."""++from __future__ import annotations++import json+import math+from pathlib import Path++import pytest+from PIL import Image, ImageDraw++from conftest import feet_unseen+from sprite_gen.video import local_cycle, loop++FRAMES = 73+CYCLE = 24+W, H = 300, 240+TURN = (30, 40) # the frames the turning walker turns over, the still's mirror reached at their middle+LOW = -0.6 # the facing the turn reaches+APART = 240 # how much lower the walker is drawn, on a canvas as much taller, where a part is apart above it+++def _facing(turns, t: float, low: float = LOW, edge: int = 3) -> float:+ """1 outside the turns; inside each (a, b), down to `low` over `edge` frames either end."""+ f = 1.0+ for a, b in turns:+ if a <= t <= b:+ f = min(f, 1.0 - (1.0 - low) * min(1.0, (min(t - a, b - t) + 1) / (edge + 1)))+ return f+++def _walker(k: int, *, turns=(), every: tuple[int, int] | None = None, hold: int = 1, square: bool = False,+ hood: bool = False, lead: int = 0, staff=(), apart=None) -> Image.Image:+ """The walker's frame `k`: turning over `turns`, or `every` (at, span) frames of each cycle; drawn on `hold`s; square+ from behind (`square`); hooded, its head and shoulders one shape that widens downward with no neck (`hood`); filmed+ smaller over its first `lead` frames, from 0.6 of its size, about its feet (a lead-in); over the frames in `staff`,+ holding a staff beside it that bobs with it, its ornament as high as the head and apart from it, the handle in its+ hand; where `apart` is given, drawn APART px lower on a canvas as much taller, a pennant apart above it at the top+ over the frames in `apart`."""+ t = k - k % hold+ ph = 2 * math.pi * t / CYCLE+ if square:+ f = 0.0+ elif every is not None:+ f = _facing([(every[0] + c * CYCLE, every[0] + c * CYCLE + every[1]) for c in range(-1, FRAMES // CYCLE + 2)], t)+ else:+ f = _facing(turns, t)+ im = Image.new("RGBA", (W, H))+ d = ImageDraw.Draw(im)+ x, y = 150, 40 + round(3 * math.cos(2 * ph))+ sw = 6 * math.sin(ph)+ for sign in (1, -1):+ lx = x + 14 * sign * math.sin(ph)+ d.rectangle((lx - 5, y + 86, lx + 5, y + 132), fill=(60, 60, 70, 255))+ for side in (1, -1):+ tone = round(150 + 75 * (1 + side * f) / 2)+ ay = y + 36 + round(side * sw)+ d.rectangle((x + side * 20 - 4, ay, x + side * 20 + 4, ay + 38), fill=(tone, tone, tone, 255))+ d.rectangle((x - 16, y + 32, x + 16, y + 90), fill=(200, 80, 80, 255))+ px = x + round(9 * f)+ d.rectangle((px - 5, y + 36, px + 5, y + 86), fill=(240, 170, 150, 255))+ fx = x + round(8 * f)+ if hood:+ d.polygon([(x - 13, y), (x + 13, y), (x + 17, y + 34), (x - 17, y + 34)], fill=(70, 90, 140, 255))+ d.rectangle((fx - 5, y + 8, fx + 5, y + 26), fill=(230, 200, 170, 255))+ else:+ d.rectangle((x - 5, y + 26, x + 5, y + 34), fill=(210, 180, 150, 255))+ d.rectangle((x - 13, y, x + 13, y + 28), fill=(90, 60, 40, 255))+ d.rectangle((fx - 5, y + 6, fx + 5, y + 24), fill=(230, 200, 170, 255))+ d.point((x - 10, y + 44 + int(t) % 11), fill=(250, 250, 250, 255)) # no two drawings the same picture+ if k in staff:+ d.rectangle((267, y, 293, y + 28), fill=(90, 60, 40, 255))+ d.rectangle((278, y + 28, 282, y + 90), fill=(140, 90, 40, 255))+ d.rectangle((170, y + 70, 282, y + 74), fill=(140, 90, 40, 255))+ if k < lead:+ s = 0.6 + 0.4 * k / lead+ small = im.resize((round(W * s), round(H * s)), Image.Resampling.LANCZOS)+ im = Image.new("RGBA", (W, H))+ im.paste(small, (round(150 - 150 * s), round(172 - 172 * s)), small)+ if apart is not None:+ tall = Image.new("RGBA", (W, H + APART))+ tall.paste(im, (0, APART))+ if k in apart:+ ImageDraw.Draw(tall).polygon([(130, 0), (170, 0), (130, 20)], fill=(250, 220, 90, 255))+ im = tall+ return im+++def _speck(n: int) -> Image.Image:+ """A frame that holds nothing but `n` solid pixels in a row."""+ im = Image.new("RGBA", (W, H))+ ImageDraw.Draw(im).rectangle((150, 100, 149 + n, 100), fill=(200, 80, 80, 255))+ return im+++def _keyed(root: Path, **drawn) -> Path:+ keyed = root / "keyed"+ keyed.mkdir(parents=True)+ for k in range(FRAMES):+ _walker(k, **drawn).save(keyed / f"{k:03}.png")+ return keyed+++def _frames(**drawn) -> list[Image.Image]:+ return [_walker(k, **drawn) for k in range(FRAMES)]+++def _cut(out: Path, keyed: Path, *extra: str) -> dict:+ assert loop.main(["--frames-dir", str(keyed), "--out-dir", str(out), "--state", "walk", "--anchor", "motion-auto",+ "--repair", "off", *extra]) == 0+ return json.loads((out / "loop.loop.report.json").read_text())+++def _refused(out: Path, keyed: Path, capsys, *extra: str) -> tuple[str, dict]:+ capsys.readouterr()+ with pytest.raises(SystemExit) as refused:+ loop.main(["--frames-dir", str(keyed), "--out-dir", str(out), "--state", "walk", "--anchor", "motion-auto",+ "--repair", "off", *extra])+ report = json.loads((out / "loop.loop.report.json").read_text())+ assert report["status"] == "failed"+ return str(refused.value.code), report+++def _same_cut(a: Path, b: Path) -> None:+ for name in ("loop.strip.png", "loop.gif", "loop.webp"):+ assert (a / name).read_bytes() == (b / name).read_bytes(), name+ frames = sorted(p.name for p in (a / "cycle").glob("*.png"))+ assert frames and frames == sorted(p.name for p in (b / "cycle").glob("*.png"))+ assert all((a / "cycle" / f).read_bytes() == (b / "cycle" / f).read_bytes() for f in frames)+++def _unread(monkeypatch) -> None:+ """The body turn read as nowhere: the search as it was before the reading."""+ from sprite_gen.video import body_turn++ real = body_turn.read+ monkeypatch.setattr(body_turn, "read", lambda frames: {**real(frames), "turns": []})+++def _holds(report: dict, frames: range) -> bool:+ s, L = report["cycle"]["start"], report["cycle"]["length"]+ return bool(set(range(s, s + L)) & set(frames))+++# --- the reading ---------------------------------------------------------------------------------------------------+++def test_a_turn_is_four_frames_in_a_row_under_zero():+ """TURN_SIDE_MAX 0 and TURN_RUN_MIN 4, each where it turns over: a torso at 0 is not turned, one under it is; three+ frames in a row are the walk's own dip, four a turn; a frame not read ends a run."""+ from sprite_gen.video import body_turn++ assert body_turn.TURN_SIDE_MAX == 0.0 and body_turn.TURN_RUN_MIN == 4+ at = lambda side: [(t["from"], t["to"]) for t in body_turn.turns(side)]+ assert at([0.5, 0.0, 0.0, 0.0, 0.0, 0.5]) == []+ assert at([0.5, -1e-4, -1e-4, -1e-4, -1e-4, 0.5]) == [(1, 4)]+ assert at([0.5, -0.3, -0.3, -0.3, 0.5]) == []+ assert at([0.5, -0.3, -0.3, None, -0.3, -0.3, 0.5]) == []+ turn = body_turn.turns([0.5, -0.1, -0.2, -0.3, -0.1, 0.5])+ assert turn == [{"from": 1, "to": 4, "least": -0.3, "at": 3}]+++def test_the_frames_a_cut_holds_of_a_turn_are_named_in_runs():+ from sprite_gen.video import body_turn++ assert body_turn.spans([36, 22, 23, 37, 38]) == "22-23 and 36-38" and body_turn.spans([40]) == "40"+++def test_the_turning_walker_reads_a_turn_where_it_turns_and_nowhere_else():+ from sprite_gen.video import body_turn++ read = body_turn.read(_frames(turns=[TURN]))+ assert read["read"] and read["still_side"] >= body_turn.SIDE_SHOWN_MIN and read["side"][0] == 1.0+ (turn,) = read["turns"]+ assert TURN[0] <= turn["from"] and turn["to"] <= TURN[1] and turn["to"] - turn["from"] + 1 >= body_turn.TURN_RUN_MIN+ assert turn["least"] < -0.2+ steady = body_turn.read(_frames())+ assert steady["read"] and steady["turns"] == [] and min(steady["side"]) > 0.5++[email protected]("turns, frames", [((12, 18), 0), ((12, 19), 4)], ids=["three-frames", "four-frames"])+def test_a_dip_of_three_frames_is_the_walks_own_and_four_are_a_turn(turns, frames):+ """The walker facing past its mirror three frames in a row reads no turn, however deep; four in a row, one."""+ from sprite_gen.video import body_turn++ read = body_turn.read(_frames(turns=[turns]))+ under = [k for k, v in enumerate(read["side"]) if v < body_turn.TURN_SIDE_MAX]+ assert len(under) == (frames or 3) and min(read["side"]) < -0.2+ assert [t["to"] - t["from"] + 1 for t in read["turns"]] == ([frames] if frames else [])+++def test_a_square_still_is_not_read_and_the_bound_turns_over_at_the_stills_own_side(monkeypatch):+ """SIDE_SHOWN_MIN: the still's head and shoulders off their mirror under it, the clip is not read (a back walk's far+ step lays its torso nearer its mirror each step); at it, read."""+ from sprite_gen.video import body_turn++ square = body_turn.read(_frames(square=True))+ assert square["read"] is False and square["still_side"] < body_turn.SIDE_SHOWN_MIN and "square" in square["why"]+ shown = body_turn.read(_frames(turns=[TURN]))["still_side"]+ monkeypatch.setattr(body_turn, "SIDE_SHOWN_MIN", shown)+ assert body_turn.read(_frames(turns=[TURN]))["read"] is True+ monkeypatch.setattr(body_turn, "SIDE_SHOWN_MIN", shown + 1e-4)+ assert body_turn.read(_frames(turns=[TURN]))["read"] is False+++def test_a_turn_is_counted_in_frames_however_the_walk_is_held():+ """Counted in frames, not drawings: the same turn drawn on twos is the same frames as on ones — counted in drawings+ it would be half as long, and a walk held on twos would need a turn twice as long to be one."""+ from sprite_gen.video import body_turn++ ones = body_turn.read(_frames(turns=[TURN]))["turns"]+ twos = body_turn.read(_frames(turns=[TURN], hold=2))["turns"]+ assert len(ones) == len(twos) == 1+ assert abs(ones[0]["from"] - twos[0]["from"]) <= 1 and abs(ones[0]["to"] - twos[0]["to"]) <= 1+ drawings = len({k - k % 2 for k in range(twos[0]["from"], twos[0]["to"] + 1)})+ assert drawings < twos[0]["to"] - twos[0]["from"] + 1+++def test_a_lead_in_is_read_against_the_still(tmp_path):+ """The reference is the clip's first frame, the still, lead-in or not (the first 8 frames filmed from 0.6 of the+ size, which the search leaves out): the turn reads where it reads without the lead-in, and the walk where it does+ not turn stays clear of 0. Read from the first frame after the lead-in — a stride's pose, whose mirror the walk+ draws half a cycle on — a walk that does not turn reads a turn every stride."""+ from sprite_gen.video import body_turn++ report = _cut(tmp_path / "out", _keyed(tmp_path, turns=[TURN], lead=8))+ turn = report["body_turn"]+ skip = report["lead_in"]["search_from"]+ assert skip > 0 and turn["reference"] == 0+ (led,), (want,) = turn["turns"], body_turn.read(_frames(turns=[TURN]))["turns"]+ assert (led["from"], led["to"]) == (want["from"], want["to"]) and led["least"] < -0.1+ assert min(v for k, v in enumerate(turn["side"]) if k >= skip and not led["from"] - 2 <= k <= led["to"] + 2) > 0.1+ steady = _frames(lead=8)+ assert body_turn.read(steady)["turns"] == []+ assert len(body_turn.read(steady[skip:])["turns"]) >= 2+++def test_a_part_swung_up_beside_the_head_does_not_pull_its_centre(monkeypatch):+ """HEAD_REACH: the side walker with a 60 px tail on a 45-frame beat (tests/video/test_walk_steps.py, the half step),+ its tail swung up into the head's rows every swing. The head's centre read within 0.3 of the body's height of it,+ the walker reads no turn; within 0.4 the tail pulls the centre aside and the torso reads a turn every swing (the+ search then took a cut that does not close)."""+ from sprite_gen.video import body_turn+ from tests.video.test_walk_steps import _side++ frames = [_side(k, cycle=29, tail_cycle=45, tail=60, arms=False) for k in range(FRAMES)]+ assert body_turn.HEAD_REACH == 0.3+ read = body_turn.read(frames)+ assert read["read"] and read["turns"] == [] and min(read["side"]) > 0+ monkeypatch.setattr(body_turn, "HEAD_REACH", 0.4)+ assert len(body_turn.read(frames)["turns"]) == 2+++def test_a_body_with_no_neck_reads_its_head_and_chest():+ """A hood widening down to the shoulders has no neck narrower than the head: the narrowest row is the top of the+ range, the crop holds the head and the chest, and the turn reads as on a body with a neck."""+ from sprite_gen.video import body_turn++ hooded = body_turn.read(_frames(turns=[TURN], hood=True))+ assert hooded["neck"] == round(min(float(f) for f in body_turn.ROWS if f >= body_turn.NECK_RANGE[0]), 2)+ assert len(hooded["turns"]) == 1 and TURN[0] <= hooded["turns"][0]["from"] and hooded["turns"][0]["to"] <= TURN[1]+ assert body_turn.read(_frames(hood=True))["turns"] == []+++# --- what the reading cannot read ----------------------------------------------------------------------------------+++def _gone(read: dict) -> list[int]:+ return [k for k, v in enumerate(read["side"]) if v is None]+++def test_a_prop_as_high_as_the_head_and_apart_from_it_leaves_the_still_unread():+ """HEAD_REACH, where nothing lies within it: a staff held beside the walker, its ornament as high as the head and as+ heavy in the top 15 % of the body, puts the middle of those rows between the two, no pixel within 0.3 of the body's+ height of it. The top does not tell which is the head, and the still is not read — not centred on the middle no+ pixel holds (0/0), nor on the larger part (the two weigh the same)."""+ from sprite_gen.video import body_turn++ read = body_turn.read(_frames(staff=range(FRAMES)))+ assert read["read"] is False and read["still_side"] is None and read["turns"] == []+ assert read["why"].startswith("the clip's first frame has no head to centre on: the top 15 % of its body holds "+ "parts apart, none within 0.3 of its height of their middle")+++def test_a_frame_with_no_head_to_centre_on_is_not_read_and_the_rest_read_as_before():+ """The staff over frames 20-29 only, and frame 40 a sliver of 2 pixels (too small a body for a pixel to lie within+ reach of their middle): those frames are None, `unread` says why, and every other frame reads what it reads without+ them."""+ from sprite_gen.video import body_turn++ frames = _frames(staff=range(20, 30))+ frames[40] = _speck(2)+ read, plain = body_turn.read(frames), body_turn.read(_frames())+ gone = [*range(20, 30), 40]+ assert read["read"] and read["turns"] == [] and _gone(read) == gone+ assert all(read["side"][k] == plain["side"][k] for k in range(FRAMES) if k not in gone)+ (unread,) = read["unread"]+ assert unread["frames"] == gone and unread["why"].startswith("has no head to centre on")+++def test_a_still_whose_torso_rows_hold_no_pixel_is_not_read():+ """A pennant apart above the walker tops the still's box, 240 px over its head: the narrowest row in NECK_RANGE is+ the gap's first, and the torso's rows, from there down half the box, hold no solid pixel. No width is measured+ across them; the still is not read."""+ from sprite_gen.video import body_turn++ read = body_turn.read(_frames(apart=range(FRAMES)))+ assert read["read"] is False and read["neck"] == 0.11 and read["turns"] == []+ assert read["why"].startswith("the clip's first frame has no solid pixel in its rows 0.11-")+++def test_a_frame_whose_torso_crop_holds_nothing_is_not_read_as_0():+ """The pennant over frames 20-29 only: those frames' boxes run from it, and their torso crops, the still's rows of a+ box three times the body's height, hold nothing — read, they were a torso at 0, as near the still as its mirror.+ They are None, `unread` says why, and every other frame reads what it reads without them."""+ from sprite_gen.video import body_turn++ read, plain = body_turn.read(_frames(apart=range(20, 30))), body_turn.read(_frames(apart=()))+ gone = list(range(20, 30))+ assert read["read"] and _gone(read) == gone+ assert all(read["side"][k] == plain["side"][k] for k in range(FRAMES) if k not in gone)+ (unread,) = read["unread"]+ assert unread["frames"] == gone and unread["why"].startswith("has nothing to read in its crop of rows")+++def test_a_crop_of_no_width_is_not_read():+ """A still whose torso's rows hold one column, under its head's centre (a head on a pole): its torso is 0 wide and+ the still is not read. A frame of one solid pixel, its crop as wide as the still's torso but over a body 1 pixel+ high, crops no column either: it is None."""+ from sprite_gen.video import body_turn++ pole = Image.new("RGBA", (W, H))+ d = ImageDraw.Draw(pole)+ d.rectangle((140, 100, 149, 120), fill=(0, 0, 0, 255))+ d.rectangle((150, 100, 160, 120), fill=(255, 255, 255, 255))+ d.line((150, 121, 150, 220), fill=(255, 255, 255, 255))+ read = body_turn.read([pole] * 8)+ assert read["read"] is False and read["still_side"] >= body_turn.SIDE_SHOWN_MIN+ assert read["why"].startswith("the clip's first frame has a crop of no width over its rows")+ frames = _frames()+ frames[40] = _speck(1)+ read = body_turn.read(frames)+ assert read["read"] and _gone(read) == [40] and read["unread"][0]["why"].startswith("has a crop of no width")+++def test_a_clip_with_no_frames_is_not_read():+ from sprite_gen.video import body_turn++ read = body_turn.read([])+ assert read["read"] is False and read["why"] == "the clip has no frames" and read["turns"] == []+++# --- the cut -------------------------------------------------------------------------------------------------------++[email protected]("turned", [(14, 24), (24, 34), TURN], ids=["14-24", "24-34", "30-40"])+def test_a_cut_that_holds_the_turn_gives_way_to_one_that_does_not(tmp_path, monkeypatch, turned):+ """The walker turns over frames 14-24, 24-34 or 30-40: the search took a cut across the turn (11/24, 17/24, 22/24:+ the body swinging round in the loop). Read, the turn's windows are refused and the cut is one that leaves it out."""+ keyed = _keyed(tmp_path, turns=[turned])+ report = _cut(tmp_path / "read", keyed)+ assert not _holds(report, range(*turned))+ turn = report["body_turn"]+ assert turn["verdict"] == "avoided" and turn["refused"] > 0 and turn["cut"]["holds"] == []+ with monkeypatch.context() as m:+ _unread(m)+ before = _cut(tmp_path / "unread", keyed)+ assert _holds(before, range(*turned)) # the cut as the search took it before+++def test_a_turn_every_cycle_keeps_the_cut_with_a_warning_or_is_refused(tmp_path, monkeypatch, capsys):+ """A walker that turns in every cycle (as a three-quarter walk that turns to the side each stride): no cut leaves+ the turn out. warn keeps the cut the search took before, byte for byte, and a warning line names the turn; refuse+ refuses the clip in a line of its own, before any other."""+ keyed = _keyed(tmp_path, every=(6, 8))+ capsys.readouterr()+ report = _cut(tmp_path / "warn", keyed)+ err = capsys.readouterr().err+ assert "video-loop: warning: the body turns in the walk — " in err and "--body-turn refuse" in err+ assert report["body_turn"]["verdict"] == "kept" and report["body_turn"]["cut"]["holds"]+ with monkeypatch.context() as m:+ _unread(m)+ _cut(tmp_path / "unread", keyed)+ _same_cut(tmp_path / "warn", tmp_path / "unread")+ said, refused = _refused(tmp_path / "refuse", keyed, capsys, "--body-turn", "refuse")+ assert said.startswith("video-loop: the body turns in the walk — its torso faces nearer the still's mirror")+ assert "film it again with the torso and hips kept at the still's angle" in said+ assert refused["body_turn"]["verdict"] == "refused"+ assert capsys.readouterr().err == "" # the refusal is the first line the run says+ assert not (tmp_path / "refuse" / "loop.strip.png").exists()++[email protected]("drawn", [{}, {"square": True}], ids=["diagonal", "square"])+def test_a_walk_that_does_not_turn_is_cut_as_before(tmp_path, monkeypatch, drawn):+ """No turn — read and none found, or a square still not read — and the cut is every byte the search alone made."""+ keyed = _keyed(tmp_path, **drawn)+ report = _cut(tmp_path / "read", keyed)+ assert report["body_turn"]["verdict"] == ("none" if not drawn else "not-read")+ with monkeypatch.context() as m:+ _unread(m)+ _cut(tmp_path / "unread", keyed)+ _same_cut(tmp_path / "read", tmp_path / "unread")++[email protected]("drawn", [{"staff": range(FRAMES)}, {"apart": (0,)}], ids=["staff", "apart"])+def test_a_walk_whose_still_is_not_read_is_cut_as_before(tmp_path, monkeypatch, drawn):+ """warn, the default, where the still cannot be read — the staff's ornament as high as the head (3.3.0 cut it+ 11/24; the reading's 0/0 on it ended the run, `cannot convert float NaN to integer`), or the pennant apart above the+ body in the still alone (over every frame, the box's upper half is the empty gap, where the motion anchor finds no+ textured region to follow): the loop is cut, every byte the search alone cuts, and the report says why the clip+ was not read."""+ keyed = _keyed(tmp_path, **drawn)+ report = _cut(tmp_path / "read", keyed)+ turn = report["body_turn"]+ assert turn["read"] is False and turn["verdict"] == "not-read"+ assert turn["why"].startswith("the clip's first frame has ")+ with monkeypatch.context() as m:+ _unread(m)+ _cut(tmp_path / "unread", keyed)+ _same_cut(tmp_path / "read", tmp_path / "unread")+++def test_a_walk_with_no_cycle_keeps_its_refusal_and_names_the_turn(tmp_path, monkeypatch, capsys):+ """The walker turns and the search finds no cycle with the turn or without it (every window refused, as on a clip+ that holds no repeat; its feet not read). warn refuses it in the words it was refused in before, after a warning line+ naming the turn; refuse names the turn."""+ def nothing(*args, **kwargs):+ raise ValueError("no periodic cycle found — no supported local two-step repeat after drift analysis")++ keyed = _keyed(tmp_path, turns=[TURN])+ monkeypatch.setattr(local_cycle, "detect", nothing)+ with feet_unseen():+ said, report = _refused(tmp_path / "warn", keyed, capsys)+ err = capsys.readouterr().err+ assert said.startswith("video-loop: no periodic cycle found")+ assert report["body_turn"]["verdict"] == "unfound" and "video-loop: warning: the body turns in the walk" in err+ said, report = _refused(tmp_path / "refuse", keyed, capsys, "--body-turn", "refuse")+ assert said.startswith("video-loop: the body turns in the walk") and report["body_turn"]["verdict"] == "refused"+++def test_refuse_needs_motion_auto(tmp_path, capsys):+ keyed = _keyed(tmp_path)+ with pytest.raises(SystemExit, match="--body-turn refuse reads the body's turn"):+ loop.main(["--frames-dir", str(keyed), "--out-dir", str(tmp_path / "out"), "--state", "walk", "--body-turn", "refuse"])