Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
feat(video): cut a walk whose feet meet once a cycle one cycle long, name a walk that starts or stops in its take, and cut a set's searched walk or run with motion-auto
Soohong Kim46cd5f1f713a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 900ce27..d85c373 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,29 @@All notable public changes to `sprite-gen` are recorded here. Versions track the `version:` field in `SKILL.md` and `pyproject.toml`.+## Unreleased - A walk whose feet meet once a cycle is cut one cycle long, a walk that starts or stops in its take is named to film again, and video-set cuts a searched walk or run with motion-auto by default++**Upgrading from 3.5.0: `video-set` now cuts searched walk and run loops with `--anchor motion-auto` and their view by default, and `video-loop --anchor motion-auto` recognises crossings that mark cycles where feet hide or step apart instead of cutting two cycles.** Every walk or run item whose loop is searched is now cut with `motion-auto` and its view, producing a different cut and different bytes; `--anchor none` gives the old cut, its pictures and reports byte for byte apart from the engine hash (`producer.implementation_sha256`). Idle, attack, once-hold, lifetime, and once-return items are cut as before. In `video-loop --anchor motion-auto` without `--view`, a walk whose feet are seen together over half the interval at a pass (`crossings.HIDE_SHARE`, 0.5) and whose picture repeats each interval is now counted on cycles: where the parent engine cut two cycles, the loop is now one cycle with new bytes; where the parent engine kept the search's cut with no `steps`, the cut is the same and the strip and report now record `steps: 2`. A walk whose crossings mark steps (brief passes, or from the side) is cut to the same bytes. With `--view` (or through `video-set`), a front, back, or diagonal walk is evaluated even with brief passes. Every report whose clip stands still gains `stands` and `run_limit`, and reports where cycle reading is asked gain `cycles`.++- **New: crossing cycle detection (`local_cycle.read_cycles`, `crossings.HIDE_SHARE`, `CYCLE_SLACK`, `CUE_SWAPPED`).** In gap mode on a readable reading, when feet can hide behind one another (`reading.overlap` over `crossings.HIDE_SHARE`, 0.5) or when the view is given and is not `side`, crossing intervals are checked to see if they mark full cycles rather than single steps. `repeat_at(distances, span)` reads the mean distance of frames to those lagged by `span` over the clip's mean step from frame to frame. Comparing distances at half, one, and two intervals, crossings mark cycles when `one < half` and `one <= two + CYCLE_SLACK` (0.5), unless the directional foot cue (`legs.shade_cue` from the side or diagonal, `legs.depth_cue` from the front or back) indicates the other leg leads one interval on (`crossings.correlation_on` at or below `CUE_SWAPPED`, −0.2). When cycles are marked, `Reading.mark_cycles` sets `per` to 2 and halves `step` and `step_range`: a cut one interval long is two steps, and the search's cut (`--anchor motion-auto`) taken on it writes `steps: {count: 2, by: crossings}`. A fixed cut (`--cycle fixed`, `fixed_count`) and the loop as it plays round (`ring_steps`) read the same; a fixed cut one interval long is counted two steps and not refused, and still writes no `steps`.+- **Removed: the same-picture rule (`local_cycle.same_picture`, `local_cycle.same_picture_count`, `local_cycle.SAME_PICTURE_MAX`, count code `same-picture`, report fields `step_count.search.same_picture` and `step_count.same_picture`).** It kept the search's cut, with no `steps`, where the count said one step; it never cut one cycle where the search had found two. `local_cycle.read_cycles` takes its place.+- **New: walk start-stop retake reporting (`loop.stand_retake`, `crossings.Reading.stands`).** In gap mode, runs where the feet stay together longer than `run_limit` (√2 times the median whole pass run) are recorded in `Reading.stands`. Where a clip shows its steps, contains `stands`, and the cut kept does not count two steps (`verdict` is not `two`) with no two-step cut closing between the standing frames, `loop.stand_retake` emits a `retake` report (`reason: "start-stop"`, `remedy: "retake"`), keeping the cut as cut without refusal under `--unfixed refuse`. Where a part also pops, one `retake` names both (`loop.retakes`): the first reason's record, `reasons: ["part-pop", "start-stop"]`, and each reason's numbers under its own key (`part_pop`, `start_stop`).+- **Changed: `video-set` defaults gait anchoring to `motion-auto` (`batch.anchor_for`).** Without an explicit `--anchor`, `video-set` cuts each walk and run item whose loop is searched (`cycle_for` returns `auto` or `periodic`) with `motion-auto`, and assigns `none` to idle, attack, once-hold, lifetime, and once-return items; explicit `--anchor` options are applied to every item as before. `video-set` passes each item's view to `video-loop`. Any item whose loop names a retake carries `loop.retake`, appears in the set's `warnings`, and appends ` (film again: <reasons>)` to `table.md`.+- **Changed: cycle alignment leaves out start-stop retake loops (`batch.align_gaits`, `video-set --align-cycles auto`).** Takes flagged with `start-stop` retakes loop no two steps and are excluded from gait cycle alignment, keeping their loops as cut while aligning the remaining directions. Excluded items are recorded under `left_out` (`{item: reasons}`) with a stderr warning and a set warning; if fewer than two directions remain, alignment is skipped (`applied: false`, `why: "fewer than two directions left to align"`).+- CLI: `video-loop --view front|back|side|front_diagonal|back_diagonal` (default none) sets the clip view for cycle detection and foot cue selection.+- Report fields: `cycle.step_count.cycles` (`{asked, interval, overlap, half, one, two, slack, cue: {one, swapped}, cycles, why}`); `step_count.stands` and `step_count.run_limit`; `loop.retake` (`{reason: "start-stop", reasons, start_stop: {stands, run_limit, crossings, cut, verdict, code, why}, remedy: "retake"}`); the set report's item `loop.retake` (`{reason, reasons, remedy}`) and its state's `cycle_align.<state>.left_out` (`{item: reasons}`).+- Python callers: new `local_cycle.read_cycles(reading, distances, view=None, cue=None)`, `local_cycle.repeat_at(distances, span)`, `batch.anchor_for(state, cut, anchor)`, `loop.stand_retake(cycle)`, `loop.retakes(*records)`, `loop.STAND_REASON`; `crossings._alternation` is now public `crossings.correlation_on(values, span)`; `align._feet`, `align._depth_cue`, `align._shade_cue`, and `align.SHADE_BAND` are moved to `legs.feet_halves`, `legs.depth_cue`, `legs.shade_cue`, and `legs.SHADE_BAND` (`align` keeps `_depth_cue` and `_shade_cue` aliases); `crossings.Reading` gains `interval`, `per`, `cycles`, and `mark_cycles(said)`.+- **Tests**: `tests/video/test_walk_steps.py` covers these synthetic walker cases:+ - a walker seen from behind whose far foot hides behind the near one (feet together over half the interval) across cycles of 20 frames on twos, 24 on threes, and 17.5 and 18.5 on ones is cut to one cycle within a frame, with `cycles` true and `steps: 2`;+ - a side walker whose two steps are one silhouette (46-frame cycle, near and far legs one or four tones apart) is not asked with no view or `--view side`, keeping two steps at 46 frames;+ - a front-diagonal walker stepping toward the camera with feet passing apart (feet together under half the interval, cycle 16 and 18) cuts one cycle (16, 18) with `--view front_diagonal`, and cuts two cycles (32, 36) without a view;+ - a 46-frame front-diagonal walker with legs four tones apart asked with `--view front_diagonal` sees one interval on as near as two on, but keeps two steps at 46 frames because the foot cue alternates one interval on;+ - synthetic units meeting every 15 frames verify that repeating every 15 frames with 9 frames overlap marks cycles, repeating every 30 frames marks steps, brief meetings with no view or `side` are not asked, and front diagonals defer to the cue;+ - synthetic start-stop clips with feet together for 15 frames at the head and 14 at the tail alongside passes of 8 and 3 frames flag retakes when the cut is uncertain, omit retakes when counted as two steps, and report no `stands` when feet only pass.+- **Tests**: `tests/video/test_gait_guard_anchor_wide.py` and `tests/video/test_cycle_align.py` cover batch anchoring and cycle alignment:+ - `batch.anchor_for` assigns `motion-auto` to walk and run loops while assigning `none` to cheer, walk with `--anchor none`, and pinned idle items, propagating loop retakes to item records, warnings, and markdown tables;+ - `batch.align_gaits` excludes loops with `start-stop` retakes, aligns remaining directions, records omissions under `left_out`, and leaves the state unaligned when fewer than two directions remain.+## v3.5.0 - Widened square canvas framing for side walk and run stride and trailing parts, measured background matte cutout for flat backgrounds of any colour, and failure when a cutout removes nothing**Upgrading from 3.4.0: `video-set` now frames a walk or run filmed from the side on a square widened by the room its still lacks, and a background the chroma engine did not recognise, which used to come out with nothing removed, is now cut out.** A still that leaves less than `GAIT_ROOM` clear in front of its silhouette (0.15 of the silhouette's height) or behind it (0.25) gains the columns it lacks on that side; the square gains the same number of rows above the still. A still that leaves the room keeps its canvas to the byte. Every other state, a front, back or diagonal view, `--shape` and `--fit tight` are framed as before. Each side walk or run's `canvas.report.json`, and its item in `set.report.json`, gains `room`. `video-canvas` gains `--view` and reads the room only with `--view side`. Backgrounds the chroma engine already recognised key byte for byte as before. A pure or recognised magenta/green background still goes to the chroma engine and a bright achromatic one to the white matte, with the same bytes.diff --git a/docs/loop-repair.md b/docs/loop-repair.mdindex 4745222..39a8a46 100644--- a/docs/loop-repair.md+++ b/docs/loop-repair.md@@ -943,6 +943,8 @@ A take to film again: where a part pops on the loop as it plays, the report's to`--unfixed refuse` refuses a loop with such a `retake`, whatever `--repair` says (the repair makes no frame for a part pop and the cut stays, so whatever `--repair` says the pop plays as filmed). `--unfixed warn` (the default) keeps it with a warning line.+A take to film again where the walk starts or stops: where the clip shows its steps, it stands still somewhere (`stands`), and the cut kept is not counted two steps (its `verdict` is not `two`), no cut of two steps closes between the stands: `loop.stand_retake` sets the report's `retake` to `{reason: "start-stop", reasons: ["start-stop"], start_stop: {stands, run_limit, crossings, cut, verdict, code, why}, remedy: "retake"}`. Where a part also pops, one `retake` names both: the first reason's record, `reasons` lists both (`["part-pop", "start-stop"]`), and each reason's numbers sit under its own key (`part_pop`, `start_stop`) (`loop.retakes`). The cut is kept as cut (nothing else changes in the loop). `--unfixed refuse` does not refuse a `start-stop` loop (it refuses jump-repair leftovers and `part-pop` only, as before); the loop is kept and named.+A loop is cut to the same bytes whether a part pops in it or not (`cycle/`, the strip, the GIF, the WebP); every walk and run report gains `part_pop` and `retake` (`retake` is `null` where no part pops).Cost: the reading is NumPy on the CPU, about a second a loop; nothing else is read.@@ -1266,7 +1268,9 @@ crossings, joined at the wrap where the walk itself goes on, is one cycle (`cros| `unconfirmed` | frames no reading confirms: a run of feet together cut by the clip's first or last frame that its twin does not confirm, the frames before the first side is seen, a change the clip ends on || `step_range` | the clip's own step (the median between crossings) and the range a step must lie in, a factor of √2 either way || `readable`, `why`, `alternation` | whether the clip shows its steps: three crossings or more, and in sign mode a lean that turns over a step on (correlation one step on at most **−0.7**, `crossings.ALTERNATION_MAX`) |-| `cut`, `search` | the cut taken and the pixel search's own cut (or why it found none), each with its `verdict`, `code`, `k` (steps covered), `phase` and `ring`; the search's cut counted an odd number of steps where a pass can hide also with `same_picture` (the clip a cut on, in its playback steps, and `overlap`, the feet together at a pass over the step) |+| `cut`, `search` | the cut taken and the pixel search's own cut (or why it found none), each with its `verdict`, `code`, `k` (steps covered), `phase` and `ring` |+| `cycles` | whether crossings mark cycles: `asked`, `interval`, `overlap`, `half`, `one`, `two`, `slack`, `cue` (`one`, `swapped`), `cycles` (`true` or `false`), and `why`; absent where not asked |+| `stands`, `run_limit` | gap mode, the runs of the feet together longer than any pass (over `run_limit`, √2 times the median run the clip shows whole: whole, or cut by the first or last frame), recorded as pairs of frames; only where there is one || `chosen_by` | `search` (kept), `two steps` (chosen on the count), and the search again where the count refutes its cut (`searched_again`) || `declined` | the best two-step cut, where none closed and the search's cut stood: its `cut`, `phase`, whether it passed the gates (`gated`) and its `seam` |@@ -1283,32 +1287,57 @@ with the loop as played showing exactly two crossings as well (`ring`); **refuteseen (`one step`, `three steps`); anything else is **uncertain** and never taken as two. `phase` is howfar the wrap is from joining the same point of the walk, in frames, the worst over the bounds.+**Crossings that mark cycles.** In gap mode (side and diagonal views) the step count reads a crossing+where the feet meet on the screen, taking one crossing interval to be one step. That is wrong where the+feet do not meet on the screen at every pass: the far foot passes hidden behind the near one (seen from+behind on a diagonal), or a foot steps toward or away from the camera and passes the other apart (a front+diagonal, a front view). There the feet meet once a cycle, the engine called a cycle one step, and two+steps were two cycles: a loop twice as long as the walk's cycle, which then plays at half the walk's+speed beside the rest of a set. Before any cut is judged,+`local_cycle.read_cycles(reading, distances, view=None, cue=None)` asks whether the crossings mark cycles+instead of steps. It is asked only in gap mode, on a readable reading, and only where a pass can hide+(`reading.overlap` over `crossings.HIDE_SHARE`, 0.5: the feet seen together over half the interval at a+pass) or where the clip's view is given (`--view front|back|side|front_diagonal|back_diagonal`, default+none) and is not `side`. From the side the legs a step on are one silhouette, as near as a cycle on, and+the picture cannot tell; so a side clip with brief passes, or a clip with no view and brief passes, is+not asked (the count stands exactly as before). `repeat_at(distances, span)` measures how far the clip+lies from itself `span` frames on: the mean distance of every frame to the one a lag on, over the clip's+mean step from one frame to the next, the nearer of the two whole lags about `span` (none where the clip+holds under half a lag of frames past it). It is read at half the crossing interval (`half`), one+interval (`one`) and two intervals (`two`). The crossings mark cycles where `one < half` (one interval on+is nearer than the pose a half interval on) and `one <= two + CYCLE_SLACK` (`CYCLE_SLACK` = 0.5 of the+mean step: one interval on is as near as two on, so the same leg leads one interval on). Then the view's+foot cue is asked: `legs.shade_cue` (the near foot's shade against the far one's) from the side or a+diagonal, `legs.depth_cue` (the picture's right foot drawn lower than its left) from the front or back,+per frame; its correlation one interval on is read with `crossings.correlation_on(values, span)` (trend+removed). At `CUE_SWAPPED` (-0.2) or under, the other leg leads one interval on: the interval is a step,+and the count stands. A cue that does not follow the feet reads near 0 and decides nothing. Where they+mark cycles the reading holds two steps an interval (`Reading.mark_cycles`: `per` 2, `step` half the+interval, `step_range` halved): a cut one interval long is two steps (one cycle) and is taken as such+(`steps: {count: 2, by: crossings}` written). Recorded in `cycle.step_count.cycles`:+`{asked, interval, overlap, half, one, two, slack, cue: {one, swapped}, cycles: true|false, why}`; absent+where not asked. The same reading is used for the search's cut (`--anchor motion-auto`), a fixed cut+(`--cycle fixed`, `fixed_count`), and the loop as it plays round (`ring_steps`, told the clip's `cycles`+since a loop alone is too short to read two intervals on). `video-set` passes each item's view. On the+synthetic walkers of `tests/video/test_walk_steps.py`, a walker seen from behind whose far foot hides+behind the near one (feet seen together over half the interval) has a cycle of 20 frames drawn on twos,+24 on threes, and 17.5 and 18.5 frames on ones (a cycle not a whole number of frames): cut one cycle+(within a frame of it), `cycles` true, `steps` 2. A side walker whose two steps are one silhouette+(46-frame cycle, near and far a tone or four apart) is not asked with no view or with `--view side`, and+is cut two steps (46 frames) as before. A front-diagonal walker whose near foot steps out toward the+camera and passes the far one apart (feet together under half the interval), cycle 16 and 18 frames: with+`--view front_diagonal` cut one cycle (16, 18 frames); without a view it is not asked and is cut as+before (32, 36 frames: two cycles, as the engine cannot tell without the view). The same 46-frame walker+filmed as a front diagonal, its far leg four tones off the near one, is asked with+`--view front_diagonal`: one interval on is as near as two on, but the foot cue turns over one interval+on: two steps (46 frames), the count stands.+**Choosing the cut.**- The clip does not show its steps (no feet seen, a legless body, a lean that does not turn over, underthree crossings): the search's cut, exactly as before. Only `cycle.step_count` is new.- The search's cut is a two within **1.5** frames of phase (`crossings.PHASE_TOLERANCE`): kept, everyimage and frame as the search alone cuts it.-- The count says the search's cut is an odd number of steps — one or three, the legs swapped a cut on —- where a pass can hide, and the clip a cut on is the same picture. A pass is brief; seen from behind on- a diagonal the far foot stands hidden behind the near one through part of the step, so the feet are- seen together for most of it, its pass among them, and apart once a cycle. Gap mode, the feet seen- together at a pass over more than **0.5** of a step (`crossings.Reading.overlap`, the median of the runs- the clip shows whole over the step; `crossings.HIDE_SHARE`), and frame by frame along the cut its frame- a cut on at most **1.0** of the cut's playback steps off (`local_cycle.same_picture`,- `SAME_PICTURE_MAX`; both in `step_count.search.same_picture`): a step on, the legs are swapped, and a- swap that draws nearer than the next frame is none — the count missed a crossing, and proves nothing.- The search's cut is kept, every image as the search alone cuts it, its count `uncertain`- (`same-picture`), and no `steps` is written: the set alignment screens it as any loop. Both are asked- because neither tells alone: from the side, with the legs drawn alike, a step on can draw as near as- the next frame — the very half step the count was made for — but there the feet pass briefly and the- count stands; where the feet stand together through a step, a lookalike step a cut on still draws- further off than a frame. On the synthetic walkers of `tests/video/test_walk_steps.py` the frame a cut- on lies 0.03 and 0.27 playback steps off where the far foot hides (on twos and on threes, the feet- together 0.60 and 0.63 of a step), and 2.12 on the half step drawn with a tail on its own beat. The side- walker whose two steps are one silhouette, near and far a tone apart, reads 0.89 a step on — under the- bound, so the picture alone kept its half step — and 1.04 at two tones; its feet pass briefly, and it is- cut two steps.- Otherwise the cut is among the cuts that cover two steps — any start, any length the count allows,inside an explicit `--min-len`/`--max-len` but not the state's window, half the clip or the gaitfallback's ceiling (a walk slower than the window is cut two steps long). Those in phase, if any, are@@ -1362,22 +1391,22 @@ crossings are not asked.**What crossings cannot see**: a hold the step range absorbs (a 13-frame step held to 17), a still run ofthe feet together inside the clip as long as a pass, and a wobble that reaches the reading's sides at a-step's beat read as steps; a narrow step that opens the feet only just past the reading's threshold-reads at that threshold. A pass hidden behind the other foot leaves one crossing a cycle, and the count-reads a cycle as one step: the clip's own repeat overrules it where the pixel search found it and the feet-stand together through most of a step (the same picture a cut on, above); where the search found no cycle,-the cut is two cycles long and says `steps: 2`. A pass that falls between two drawings with the feet seen-together only briefly is not overruled: from there the same picture a cut on is what a side walk with its-legs drawn alike does. And a walk whose feet do stand together through most of a step, its two steps drawn-nearer than a frame apart, is cut as the search cuts it — one step long, as before the count: neither the-pixels nor the crossings tell its step from its cycle there, and only someone who counts the steps (`--steps`)-settles it. Four-legged gaits are read as one foot band (`legs.strike_signals`), as before.+step's beat read as steps; a narrow step that opens the feet only just past the reading's threshold reads+at that threshold. Where a pass is hidden behind the other foot, or where the view is given and is not+`side`, the cycles reading (`local_cycle.read_cycles`) sees whether the crossings mark cycles: where the+clip repeats one interval on as near as two on, and the foot cue does not show the legs swapped, the+reading marks cycles and cuts one cycle as two steps. What it still cannot tell: a side walk with brief+passes whose two steps are one silhouette is not asked, because from the side the legs a step on are one+silhouette, as near as a cycle on, and the picture cannot tell; a clip with no view and brief passes is+not asked, so a front diagonal whose near foot steps out apart is then cut two cycles, so give `--view`;+and a cue that does not follow the feet reads near 0 and decides nothing. Four-legged gaits are read as+one foot band (`legs.strike_signals`), as before.### The step gate: every step between drawings, and a fixed cut's countOn every walk or run loop that plays round (not a single play cut), after the seam gate passes, the strip cells are read between their drawings: a loop drawn on twos or threes shows each drawing for two or three frames (`repair.flow_drawings` finds them), so read frame by frame it steps nothing and then two or three steps at each drawing, making its largest step two or three times its mean even when playing evenly. Each drawing first cell is read on analysis features the seam gate reads (`loop._small_features`), taking the step from each drawing to the next and from the last drawing into the first across the wrap. The largest of these steps, wrap included, over the mean of the others must be at most `STEP_RATIO_MAX` (2.5) (`loop.drawing_steps`). Because a pixel of jitter can look large against a tiny mean step, a step over 2.5 is exempt from the bound when it is a pixel's jitter (`loop.step_jitter`): the move that aligns its drawing with the previous drawing while producing the least coverage difference (`stop.register`, read on alpha so colour has no effect) is at most `STEP_JITTER_PX` (1.5) pixels of the frames as filmed. Each such pixel is the strip's `scale` in cell pixels, and the allowed move is never less than one cell pixel. With that move taken back, the step must also be within 2.5 of the mean. The gate holds the largest step that is not a pixel's jitter to the bound. On synthetic frames, a walk going away from the camera has a step where the feet rise a whole crop row that measures 2.5 to 3.6 times the mean as drawn, black or grey. Its move is one pixel, the step taken back is at most 1.3 times the mean, and the loop passes. A frame of a walk cut 400 px tall moved 2 px and back moves 6 cell pixels, or 2.0 pixels of the frames as filmed, and fails in every colour. Measured instead as a mean RGBA difference, that jump reads 0.057 in colour, 0.025 in a grey near the backdrop and 0.021 in black. Past the bound, the loop fails with `video-loop: loop step ratio <ratio> exceeds 2.5 (<kind> length <L> frames from <start>, into frame <frame>, read between its <n> drawings); the loop jumps inside — regenerate the clip`. Where jump repair says why the step jumps, the line says it before ` — regenerate the clip`: `: frame <frame> lies off the walk's flow, and the jump repair's frame there was refused (<faults>), so it plays as filmed`, or `: frame <frame> lies off the walk's flow, and no group of up to 2 drawings brings it back`. The report records `step_gate` on every walk or run loop, passed or failed: `read` (`drawings`), `drawings`, `hold`, `mean_step`, `largest_ratio`, `largest_from` and `largest_into` (the cut frames from and into which the largest step that is not a pixel's jitter runs, each the first frame of its drawing), `wrap_ratio`, `max` (the bound used), `jitter` for steps over 2.5 that are a pixel's jitter (each step's `from` and `into` frames, its `ratio`, its `move` in cell pixels and `ratio_moved_back`, with the larger first), `lifted`, and `kept` when a lifted gate kept a loop over 2.5; a loop with fewer than three drawings records `skipped` instead.-`--cycle fixed --start S --length L` of a walk or run now reads clip foot crossings (`crossings.read`) and judges the cut (`Reading.judge`), as `--anchor motion-auto` already does for the cut it takes. The report records this as `cycle.step_count` (the reading record, `chosen_by: caller`, and `cut` with `verdict`, `code`, `k`, `phase`, `ring`). A walk loops on two steps; a cut whose crossings count an odd number of steps (one, three) swaps legs at the wrap however close frames look, failing with `video-loop: loop step count refutes the fixed cut <start>/<L> — the clip's crossings count one step, each seen where a walk loops on two, and an odd count swaps the legs at the wrap; cut it again two steps long (about <2 steps> frames)`. An even count of four steps is not refused. The exemption from `--anchor motion-auto` applies (`local_cycle.same_picture_count`, shared by both now): where feet are seen together over half a step at a pass (`crossings.HIDE_SHARE`) and the clip one cut on is the same picture (at most `local_cycle.SAME_PICTURE_MAX`, 1.0 playback steps along the cut), the count missed a crossing; verdict reads `uncertain`, code `same-picture`, recorded with `same_picture`, and the cut is not refused. A fixed cut gets no `steps` field and leaves its strip unchanged.+`--cycle fixed --start S --length L` of a walk or run now reads clip foot crossings (`crossings.read`) and judges the cut (`Reading.judge`), as `--anchor motion-auto` already does for the cut it takes. The report records this as `cycle.step_count` (the reading record, `chosen_by: caller`, and `cut` with `verdict`, `code`, `k`, `phase`, `ring`). A walk loops on two steps; a cut whose crossings count an odd number of steps (one, three) swaps legs at the wrap however close frames look, failing with `video-loop: loop step count refutes the fixed cut <start>/<L> — the clip's crossings count one step, each seen where a walk loops on two, and an odd count swaps the legs at the wrap; cut it again two steps long (about <2 steps> frames)`. An even count of four steps is not refused. The fixed cut's count reads the same cycles reading (`fixed_count`, with the view), so a cut one interval long where the crossings mark cycles counts two steps and is not refused. A fixed cut gets no `steps` field and leaves its strip unchanged.The step gate stands where the seam gate does. Its bound is the larger of 2.5 and `--seam-max`. Setting `--seam-max` past 2.5 lifts it with the seam: every step bound is then `--seam-max`, a loop whose largest step is over 2.5 is kept with the warning line `video-loop: warning: the loop's largest step between drawings is <ratio>x their mean (into frame <frame>), over 2.5: it jumps inside — kept, as --seam-max <seam-max> lifts the step gate` (and `step_gate.kept`, `step_gate.lifted: true`), and a fixed cut counted an odd number of steps is kept with `video-loop: warning: the clip's crossings count the fixed cut <start>/<L> one step, each seen: a walk loops on two steps, and an odd count swaps the legs at the wrap — kept, as --seam-max <seam-max> lifts the step gate` (and `cycle.step_count.lifted`, which records `seam_max`). A forced delivery with `--seam-max 1000` therefore passes as before, with these lines.diff --git a/docs/loop-review.md b/docs/loop-review.mdindex 63ffa8c..dca5065 100644--- a/docs/loop-review.md+++ b/docs/loop-review.md@@ -162,9 +162,12 @@ sprite-gen video-loop --frames-dir frames/keyed/ --out-dir loop/ \--state walk --fps <measured-source-fps> --anchor motion-auto```-`video-set --states walk,run --anchor motion-auto` uses the same path. Other-states and fixed/manual cuts are rejected before generation. The defaults above-remain unchanged. This mode accepts no supplied regions or frame indices.+`video-set` takes the same path by default: each walk or run item whose loop is+searched is cut with `motion-auto` and its view, every other item with `none`,+and `--anchor none` cuts every item as before. Given explicitly,+`--anchor motion-auto` is used for every item, and other states and fixed/manual+cuts are rejected before generation. The defaults above remain unchanged. This+mode accepts no supplied regions or frame indices.The script searches a grid in the upper part of the foreground for two separated,textured regions. It ranks their normalized cross-correlation across time and@@ -216,11 +219,12 @@ A walk whose two steps look alike — its legs drawn alike, from the side or a done step long (or, past a tail on its own beat, three), and the search has nothing to refuse it on:the step repeats. Where the clip shows its feet pass, the cut is counted on those crossings and istwo steps long — any length the count allows, past the window for a slow walk — joined at the walk's-own point (`cycle.step_count`; [loop repair](loop-repair.md) section 3, "The step count"). The search's-cut stands where the clip a cut on is the same picture though the count says one step and the feet stand-together through most of a step (a pass hidden behind the other foot), and where no cut of two steps closes in-its place. Where it-does not, the cut is screened the other way, over the whole clip (`cycle.step_screen`): where twice it+own point (`cycle.step_count`; [loop repair](loop-repair.md) section 3, "The step count"). Where the far+foot passes hidden behind the near one, or the clip's view is given (`--view`) and is not `side`, the+crossings are asked whether they mark cycles instead of steps (`local_cycle.read_cycles`); where they do,+one crossing interval is two steps and the cut is one cycle long. The search's cut stands where no cut of+two steps closes in its place. Where the clip does not show its feet pass, the cut is screened the other+way, over the whole clip (`cycle.step_screen`): where twice itrepeats better than it, the report names it a suspect and nothing else changes. Look at the loop andcount its steps (how often each foot lands); `video-loop --steps 1` cuts it again two of its lengthslong, `--steps 2` keeps it and says so ([loop repair](loop-repair.md) section 3, "The step screen").diff --git a/docs/video-pipeline.md b/docs/video-pipeline.mdindex d87ef0b..25b8ee5 100644--- a/docs/video-pipeline.md+++ b/docs/video-pipeline.md@@ -174,7 +174,7 @@ sprite-gen video-prompt --direction side --state walk --facing right --no-last-f# duration, the credits shown to the user and approved, create_generation with that quote, query_zcre# status until it succeeds, the output saved as item/clip.mp4sprite-gen video-frames --clip item/clip.mp4 --out-dir item/frames --spill auto --reference item/canvas.png-sprite-gen video-loop --frames-dir item/frames/keyed --out-dir item/loop --fps <fps in item/frames/frames.report.json> --state walk --cycle auto --anchor motion-auto --facing right --name side-walk+sprite-gen video-loop --frames-dir item/frames/keyed --out-dir item/loop --fps <fps in item/frames/frames.report.json> --state walk --cycle auto --anchor motion-auto --view side --facing right --name side-walk# a set, once the walk is cut in every direction (each as above, in its own folder):sprite-gen video-cycle-align --loop-dir front/loop --loop-dir side/loop --loop-dir back/loop --view front --view side@right --view back --report walk.cycle-align.json```@@ -184,7 +184,10 @@ back to its first frame's size, and `motion-auto` is the anchor that measures thand holds it before the cycle search([section 4](#4-loop--period-first-seam-second-then-the-gait-floor)); `video-loop`'s own default for awalk or run, `body`, does not. A jump takes no `--anchor`: `motion-auto` is refused for a state that-is not a walk or run. `--fps` is the frames report's own, never a number written in by hand.+is not a walk or run. `--fps` is the frames report's own, never a number written in by hand. Give the+clip's view (`--view`) so a front, back or diagonal walk is read for crossings that mark cycles;+`video-set` passes each item's view and cuts every walk or run whose loop is searched this way by+default.The set stage is the same step `video-set` runs after its loops are cut (`--align-cycles auto`, itsdefault): one `--loop-dir` per direction of the same walk or run, one `--view` each in the same@@ -206,6 +209,10 @@ named in the warnings with whether any other cut of its clip would alternate; `-stops the set before anything is rewritten instead (both are explained in[loop repair](loop-repair.md) section 4).+`video-set`'s own alignment (`batch.align_gaits`) leaves out a loop named a take to film again for+`start-stop`: its loop is kept as cut, the rest are aligned without it, and the state's record names+it under `left_out`.+`video-prompt --json` also gives the duration (the state's own, as `video-set`), whether the clipends on the canvas (`last_frame`), the loop cut (`cycle`) and the canvas, clip, frames and loopcommands with placeholders; a front or back walk adds `start_still`, the mid-step redraw `video-set`diff --git a/sprite_gen/video/align.py b/sprite_gen/video/align.pyindex 1c085bf..b9f1b64 100644--- a/sprite_gen/video/align.py+++ b/sprite_gen/video/align.py@@ -115,9 +115,8 @@ RATE_TOLERANCE = 0.002 # frame rates read back from the strip metadata agree wi# The foot-strike turn (docs/loop-repair.md section 4) reads the legs as the two-cycle screen# records them (sprite_gen/video/legs.py). With a view the view picks the signal and the swings only# say whether there are legs to read (`foot_strike`).-LOW_ALPHA, STRIDE_MIN, REACH_MIN, BODY_RUN = legs_mod.LOW_ALPHA, legs_mod.STRIDE_MIN, legs_mod.REACH_MIN, legs_mod.BODY_RUN+STRIDE_MIN, REACH_MIN, BODY_RUN = legs_mod.STRIDE_MIN, legs_mod.REACH_MIN, legs_mod.BODY_RUNSTART_FOOT = "right" # every loop of a set starts as this own foot lands, where its view can tell-SHADE_BAND = 0.15 # the shade cue reads the feet and lower legs: the lowest 15 % of the body# The two strikes must differ by this to name a foot (`strike_foot`): shade in luma (0..1), depth in# body heights. A smaller difference is the drawing as much as the feet, and the foot is left unnamed# (`low-margin`) for whoever looks (`unnamed_feet`): a foot named wrong turns the loop half a cycle off@@ -664,36 +663,7 @@ def _keep_the_beat(frames: list[Image.Image], out: list[Image.Image], provenancestrike_signals = legs_mod.strike_signals-def _feet(frame: Image.Image) -> tuple[np.ndarray, np.ndarray, int]:- """(solid mask, the picture's right half of the feet as a column mask, body height): the halves- split at the middle of the foot band (the lowest FOOT_BAND of the frame's own height)."""- solid = np.asarray(frame.getchannel("A")) >= LOW_ALPHA- rows = np.nonzero(solid.any(axis=1))[0]- y1, height = int(rows[-1]), int(rows[-1] - rows[0] + 1)- xs = np.nonzero(solid[y1 + 1 - max(1, round(height * legs_mod.FOOT_BAND)) : y1 + 1].any(axis=0))[0]- return solid, np.arange(solid.shape[1]) >= (xs[0] + xs[-1]) / 2, height---def _depth_cue(frame: Image.Image) -> float:- """How much lower the picture's right foot is drawn than its left, as a fraction of the body's- height (the lowest solid row of each half)."""- solid, right, height = _feet(frame)- low = [int(np.nonzero(solid[:, half].any(axis=1))[0].max()) if solid[:, half].any() else 0 for half in (~right, right)]- return (low[1] - low[0]) / height---def _shade_cue(frame: Image.Image, facing: str) -> float:- """How much lighter the front foot is drawn than the back one (mean luma 0..1 of the lowest- SHADE_BAND of the body, front half against back half; the front is the side faced)."""- solid, right, height = _feet(frame)- rows = np.nonzero(solid.any(axis=1))[0]- band = np.zeros_like(solid)- band[rows[-1] + 1 - max(1, round(height * SHADE_BAND)) : rows[-1] + 1] = True- rgb = np.asarray(frame.convert("RGB"), dtype=np.float32) / 255.0- luma = rgb @ np.array([0.299, 0.587, 0.114], dtype=np.float32)- front = right if facing == "right" else ~right- parts = [luma[solid & band & cols[None, :]] for cols in (front, ~front)]- return float(parts[0].mean() - parts[1].mean()) if all(p.size for p in parts) else 0.0+_depth_cue, _shade_cue = legs_mod.depth_cue, legs_mod.shade_cuedef strike_foot(frames: list[Image.Image], strikes: tuple[int, int], view: str, facing: str | None) -> dict[str, Any]:diff --git a/sprite_gen/video/batch.py b/sprite_gen/video/batch.pyindex 54ba644..dba19dc 100644--- a/sprite_gen/video/batch.py+++ b/sprite_gen/video/batch.py@@ -366,6 +366,15 @@ def pins_last_frame(state: str, direction: str, play: str | None = None) -> boolreturn state in PIN_LAST_FRAME_STATES or (state in GAIT_STATES and direction in PINNED_GAIT_VIEWS)+def anchor_for(state: str, cut: str, anchor: str | None = None) -> str:+ """The `video-loop --anchor` an item's loop is cut with: the request's (`anchor`, `--anchor`), else `motion-auto` for+ a walk or run whose loop is searched (`cut`, `cycle_for`: `auto` or `periodic`) — the anchor that holds its size and+ counts its steps before the cut (docs/video-pipeline.md, loop-repair.md section 4) — and `none` for any other item."""+ if anchor is not None:+ return anchor+ return "motion-auto" if loop_mod.profile_for(state).gait and cut in ("auto", "periodic") else "none"++def cycle_for(state: str, direction: str, play: str | None = None, *, pinned: bool | None = None) -> str:"""The `video-loop --cycle` that cuts the clip of (state, direction): `pinned` says whether that clip was filmedending on its first frame (None: as `pins_last_frame` films it; False: a source that could not pin it).@@ -704,7 +713,7 @@ def run_item(gap: float,video_runner: Callable[..., int] = run_video_cli,shape: str | None = None,- anchor: str = "none",+ anchor: str | None = None,spill: str = "auto",facing: str = "right",facing_fix: str = "none",@@ -722,11 +731,12 @@ def run_item(motion: str | None = None,) -> dict[str, Any]:"""One (direction, state) item, canvas to loop. `play` is the request's play mode for it (`play.MODES`; None, the- state's preset) and `motion` the caller's own motion text in place of the state's sentence."""+ state's preset) and `motion` the caller's own motion text in place of the state's sentence. `anchor` is the+ request's `--anchor`; None cuts the loop with the item's own (`anchor_for`)."""mode = play_mod.resolve(state, play, prog="video-set")if end_frame is not None and mode != play_mod.ONCE_HOLD:raise SystemExit("video-set: --end-frame requires a once-hold item (a non-loop state, or --play once-hold)")- if mode == play_mod.ONCE_HOLD and (fit == "tight" or anchor != "none"):+ if mode == play_mod.ONCE_HOLD and (fit == "tight" or anchor not in (None, "none")):raise SystemExit("video-set: non-loop states need --fit state and --anchor none to preserve the terminal pose")if walk_start not in WALK_START_MODES:raise SystemExit(f"video-set: --walk-start must be one of {', '.join(WALK_START_MODES)}")@@ -857,9 +867,10 @@ def run_item(if decontam_note:# the set report lists it under `warnings`result["frames"]["decontam_warning"] = decontam_note- lp = loop_mod.run_loop(Path(fr["keyed_dir"]), item_dir / "loop", fps=float(fr["fps"]), state=state, min_len=None, max_len=None, n_out=None, seam_max=loop_mod.SEAM_RATIO_MAX, name=item, report_path=item_dir / "loop.report.json", anchor=anchor, body_height=body_height,- cycle_mode=cycle_for(state, direction, play, pinned=pins),- facing=facing if direction in handed_mod.LATERAL_VIEWS else "right")+ cut = cycle_for(state, direction, play, pinned=pins)+ lp = loop_mod.run_loop(Path(fr["keyed_dir"]), item_dir / "loop", fps=float(fr["fps"]), state=state, min_len=None, max_len=None, n_out=None, seam_max=loop_mod.SEAM_RATIO_MAX, name=item, report_path=item_dir / "loop.report.json", anchor=anchor_for(state, cut, anchor), body_height=body_height,+ cycle_mode=cut,+ facing=facing if direction in handed_mod.LATERAL_VIEWS else "right", view=direction)result["loop"] = {"kind": lp["cycle"].get("kind", "periodic"), "cycle": lp["cycle"]["length"], "period": lp["cycle"]["period_global"], "cycle_ratio": round(lp["cycle"]["ratio"], 3), "seam_ratio": lp["resampled_seam_ratio"], "n_out": lp["n_out"], "drift_px": lp["strip"].get("drift_px", 0), "gif": lp["gif"]["file"], "webp": lp["webp"]["file"], "strip": lp["strip"]["path"]}result["loop"]["review_recommended"] = lp["cycle"].get("review_recommended", False)result["loop"]["half_period_guard"] = lp["cycle"].get("half_period_guard")@@ -876,6 +887,9 @@ def run_item(result["loop"]["step_screen"] = {k: lp["cycle"]["step_screen"][k] for k in ("lag", "ratio", "depth", "coverage")}if lp.get("motion_anchor", {}).get("applied") is False:result["loop"]["motion_anchor"] = lp["motion_anchor"]+ if lp.get("retake"):+ # a take to film again (a part that pops at the wrap, a walk that starts or stops in the take), named+ result["loop"]["retake"] = {k: lp["retake"][k] for k in ("reason", "reasons", "remedy")}if "rife" in (lp.get("jump_repair") or {}):# cut as filmed for want of RIFE: the set report lists it under `warnings` (a wrap the seam bridge read carries# its `seam`, not the flow's `off_max_before`)@@ -959,6 +973,9 @@ def align_gaits(results: list[dict[str, Any]], root: Path, mode: str, *, interposaying why (`reason`) and a warning line naming what settles it: a frame is to be made and noRIFE is installed (`rife-not-installed`), or a loop may hold two or three cycles and nobody hascounted them (`cycle-suspects`, the loops under `suspects`; `video-cycle-align --cycles`).+ A loop whose take is to be filmed again because the walk starts or stops in it (`retake` reason+ `start-stop`, loop.stand_retake) loops no two steps and has no cycle to match: it is left out, its+ loop kept as cut, the rest aligned without it, and its state names it under `left_out`.`feet` maps an item to the own foot that lands on its loop's first strike (`--align-foot`,`video-cycle-align --foot`), handed to its state's alignment. A state that names loops whose foot@@ -970,8 +987,13 @@ def align_gaits(results: list[dict[str, Any]], root: Path, mode: str, *, interpoif mode == "off":return outby_state: dict[str, list[dict[str, Any]]] = {}+ left_out: dict[str, dict[str, list[str]]] = {}for r in results:if r.get("ok") and loop_mod.profile_for(r["state"]).gait:+ reasons = (r["loop"].get("retake") or {}).get("reasons") or []+ if loop_mod.STAND_REASON in reasons:+ left_out.setdefault(r["state"], {})[r["item"]] = reasons+ continueby_state.setdefault(r["state"], []).append(r)for state, rows in by_state.items():if len(rows) < 2:@@ -1016,6 +1038,10 @@ def align_gaits(results: list[dict[str, Any]], root: Path, mode: str, *, interpor["loop"]["cycle_align"] = {k: row[k] for k in ("from", "to", "made_by_rife", "turned_by", "turned_on", "start_foot", "start_foot_source","seam_ratio", "retake")}r["loop"]["n_out"] = row["strip"]["frames"]+ for state, items in left_out.items():+ out.setdefault(state, {"ok": True, "applied": False, "why": "fewer than two directions left to align"})["left_out"] = items+ print(f"video-set: warning: {state}: {', '.join(items)} left out of the cycle alignment — a take to film again "+ f"({loop_mod.STAND_REASON}): the walk starts or stops in it, and its loop is kept as cut", file=sys.stderr)# a foot told for an item no alignment took (its state not aligned, or the item failed) is never dropped quietlyfor state, told_items in asked.items():if told_items and not out[state].get("applied"):@@ -1024,7 +1050,9 @@ def align_gaits(results: list[dict[str, Any]], root: Path, mode: str, *, interpor = next((r for r in results if r["item"] == item), None)if r is None:raise SystemExit(f"video-set: --align-foot {item}={foot} names no item of the set")- why = f"{item} failed" if not r.get("ok") else f"{r['state']} was not aligned (filmed in fewer than two directions)"+ why = (f"{item} failed" if not r.get("ok") else+ f"{item} was left out of the alignment, a take to film again ({loop_mod.STAND_REASON})" if item in left_out.get(r["state"], {}) else+ f"{r['state']} was not aligned (filmed in fewer than two directions)")out.setdefault(r["state"], {"ok": True, "applied": False, "why": why}).setdefault("feet_unused", {})[item] = footfor state, a in out.items():if a.get("feet_unused"):@@ -1048,6 +1076,8 @@ def write_table(results: list[dict[str, Any]], path: Path, *, both: bool = Falsestatus = "OK (uncorrected; review gait)"if "jump_repair" in lp:status += " (jump not repaired: no RIFE)"+ if lp.get("retake"):+ status += f" (film again: {', '.join(lp['retake']['reasons'])})"# a cut whose steps are known is two of them; one the step screen suspects may be onecycle = f"{lp['cycle']}" + (f" ({lp['steps']} steps)" if lp.get("steps") else " (one step?)" if lp.get("step_screen") else "")lines.append(f"| {_view_label(r, both)} | {r['state']} | {lp.get('kind', 'periodic')} | {cycle} | {lp['period'] if lp['period'] is not None else '-'} | {format(lp['seam_ratio'], '.2f') if lp['seam_ratio'] is not None else '-'} | {lp['n_out']} | {status} |")@@ -1072,7 +1102,7 @@ def run_set(gap: float,video_runner: Callable[..., int] = run_video_cli,shape: str | None = None,- anchor: str = "none",+ anchor: str | None = None,spill: str = "auto",facing: str = "right",facing_fix: str = "none",@@ -1128,7 +1158,7 @@ def run_set(for item, path in (end_frames or {}).items():if item not in modes or modes[item] != play_mod.ONCE_HOLD or not path.is_file():raise SystemExit(f"video-set: --end-frame {item} needs a non-loop item (a once-hold) and an existing image")- if play_mod.ONCE_HOLD in modes.values() and (fit == "tight" or anchor != "none"):+ if play_mod.ONCE_HOLD in modes.values() and (fit == "tight" or anchor not in (None, "none")):raise SystemExit("video-set: non-loop states need --fit state and --anchor none")aligned_items = [i for i, _, s, _, _ in items if align_cycles == "auto" and loop_mod.profile_for(s).gaitand sum(1 for _, _, s2, _, _ in items if s2 == s) >= 2]@@ -1174,6 +1204,11 @@ def run_set(warnings += [f"cycle-align:{st}: {line}" for st, a in aligned.items() for line in a.get("warnings", [])]warnings += [f"{r['item']}: {r['frames']['decontam_warning']}" for r in resultsif r.get("ok") and "decontam_warning" in r.get("frames", {})]+ # A take to film again its loop named (`retake`) — never a failure, never silent — and one the alignment left out.+ warnings += [f"{r['item']}: film this direction again ({', '.join(r['loop']['retake']['reasons'])}) — {r['dir']}/loop.report.json `retake`"+ for r in results if r.get("ok") and r["loop"].get("retake")]+ warnings += [f"cycle-align:{st}: {item} left out — a take to film again ({', '.join(reasons)}), its loop kept as cut"+ for st, a in aligned.items() for item, reasons in a.get("left_out", {}).items()]warnings += [f"cycle-align:{st}: --align-foot {item}={foot} not applied ({a.get('why') or a.get('error') or 'the item failed'})"for st, a in aligned.items() for item, foot in a.get("feet_unused", {}).items()]# A start still `gen` asked about instead of drawing (codex cannot run, and the choice is to ask): the set ends@@ -1266,7 +1301,7 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:parser.add_argument("--concurrency", type=int, default=3, help="parallel clip generations (starts are staggered regardless)")parser.add_argument("--start-gap", type=float, default=START_GAP_SECONDS, help="seconds between clip request starts")parser.add_argument("--shape", choices=canvas_mod.SHAPES, help="force one canvas shape for every state (e.g. wide for a costume or arms that leave a 1:1 frame; square keeps a side walk or run square whatever room its still leaves)")- parser.add_argument("--anchor", choices=tuple(a for a in loop_mod.ANCHOR_MODES if a != "motion"), default="none", help="motion-auto: automatic regions, local period and XY correction (walk/run only); feet: remove in-canvas drift")+ parser.add_argument("--anchor", choices=tuple(a for a in loop_mod.ANCHOR_MODES if a != "motion"), default=None, help="default: motion-auto for a walk or run whose loop is searched, none for every other state; motion-auto: automatic regions, local period and XY correction (walk/run only); feet: remove in-canvas drift")parser.add_argument("--spill", choices=frames_mod.SPILL_MODES, default="auto", help="auto: judge key reflections from each item's canvas still (default); small / full: force")parser.add_argument("--fit", choices=canvas_mod.FITS, default="state", help="state: each state's room for the motion (default); tight: no room, the subject fills the frame and a motion that leaves it is clipped (use with --body-height at a low --resolution)")parser.add_argument("--body-height", type=int, default=None, help="scale every state's loop so the standing height is this many px (video-loop --body-height): one value for the whole set keeps the character the same size across states")@@ -1292,7 +1327,7 @@ def run(**kwargs: object) -> int:duration=(int(kwargs["duration"]) if kwargs.get("duration") else None), resolution=str(kwargs.get("resolution") or "720p"), key=str(kwargs.get("key") or "auto"),concurrency=int(kwargs.get("concurrency") or 3), force=bool(kwargs.get("force")), gap=float(kwargs.get("start_gap") or START_GAP_SECONDS),facing=str(kwargs.get("facing") or "right"), facing_fix=str(kwargs.get("facing_fix") or "none"),- shape=(str(kwargs["shape"]) if kwargs.get("shape") else None), anchor=str(kwargs.get("anchor") or "none"), spill=str(kwargs.get("spill") or "auto"),+ shape=(str(kwargs["shape"]) if kwargs.get("shape") else None), anchor=(str(kwargs["anchor"]) if kwargs.get("anchor") else None), spill=str(kwargs.get("spill") or "auto"),body_height=(int(kwargs["body_height"]) if kwargs.get("body_height") else None), fit=str(kwargs.get("fit") or "state"),decontam=str(kwargs.get("decontam") or frames_mod.DECONTAM_DEFAULT), align_cycles=str(kwargs.get("align_cycles") or "auto"),align_between=str(kwargs.get("align_between") or align_mod.DEFAULT_BETWEEN),diff --git a/sprite_gen/video/crossings.py b/sprite_gen/video/crossings.pyindex db91c09..93ab3af 100644--- a/sprite_gen/video/crossings.py+++ b/sprite_gen/video/crossings.py@@ -37,6 +37,13 @@ the loop as played showing exactly two crossings as well; `refuted` is k steps,`three steps`); everything else is `uncertain`, never taken as two. `phase` is delta in frames (delta x m), theworst over the bounds: how far the wrap is from joining the same point of the walk.+Crossings that mark cycles (`Reading.mark_cycles`, read by `local_cycle.read_cycles`): in gap mode a crossing is+where the feet meet on the screen, and they need not meet at every pass. The far foot can pass behind the near one+inside a run of the feet together (a pass hidden), or a foot can step toward or away from the camera and pass the+other apart on the screen. The feet then meet once a cycle, and the interval between two crossings holds two steps.+Every count then reads two steps an interval (`per`): the step is half the interval, a cut's advance is twice the+crossings it covers, and the loop as played shows two steps a crossing. The step range is still read on the intervals.+What crossings cannot see: a hold the step range absorbs (a 13-frame step held to 17), a still run of the feettogether as long as a pass, a wobble that reaches the reading's sides at a step's beat. They read as steps."""@@ -204,24 +211,46 @@ class Reading:whole = [b - a + 1 for a, b in self.runs if a > 0 and b < n - 1]self.run_limit = ROOT2 * float(np.median(whole)) if whole else Nonemiddles = [(lo + hi) / 2 for lo, hi in self.crossings]- self.step = float(np.median(np.diff(middles))) if len(middles) >= 3 else None+ self.interval = float(np.median(np.diff(middles))) if len(middles) >= 3 else None # between two crossings+ self.per = 1 # steps an interval holds: 2 where the crossings mark cycles (`mark_cycles`)+ self.cycles: dict[str, Any] | None = None # whether they do, as read (`mark_cycles`); None where not askedself.alternation: float | None = None # sign mode: the lean's correlation one step on (`read`)- self.why = why if why is not None else (None if self.step is not None else+ self.why = why if why is not None else (None if self.interval is not None elsef"{len(middles)} crossing{'s' if len(middles) != 1 else ''} in the clip: under two steps, no step range")+ @property+ def step(self) -> float | None:+ """The walk's step, in frames: the interval between two crossings, or half of it where they mark cycles."""+ return None if self.interval is None else self.interval / self.per++ def mark_cycles(self, said: dict[str, Any]) -> None:+ """Whether the crossings mark cycles, not steps, as read (`said`, kept in the record; `local_cycle.read_cycles`).+ Where `said['cycles']` holds, the feet are seen to meet once a cycle — the other pass hidden, or made apart on the+ screen — and every count is two steps an interval (`judge`, `ring_count`, `lengths`)."""+ self.cycles = said+ self.per = 2 if said.get("cycles") else 1++ @property+ def stands(self) -> list[tuple[int, int]]:+ """Gap mode: the runs of the feet together longer than any pass (over `run_limit`, ROOT2 times the median run+ the clip shows whole), whole or cut by its first or last frame — the walk standing still."""+ if self.run_limit is None:+ return []+ return [(a, b) for a, b in self.runs if b - a + 1 > self.run_limit + EPS]+@propertydef readable(self) -> bool:return self.why is None@propertydef overlap(self) -> float | None:- """Gap mode: how long the feet are seen together at a pass, over the step — the median of the runs the clip- shows whole. A pass is brief; past HIDE_SHARE the far foot stands behind the near one through part of the- step, and a pass can hide in the run. None in sign mode, or without a step or a whole run."""+ """Gap mode: how long the feet are seen together at a pass, over the interval between two crossings — the median+ of the runs the clip shows whole. A pass is brief; past HIDE_SHARE the far foot stands behind the near one+ through part of the step, and a pass can hide in the run. None in sign mode, or without a step or a whole run."""whole = [b - a + 1 for a, b in self.runs if a > 0 and b < self.n - 1]- if self.mode != "gap" or self.step is None or not whole:+ if self.mode != "gap" or self.interval is None or not whole:return None- return float(np.median(whole)) / self.step+ return float(np.median(whole)) / self.intervaldef record(self) -> dict[str, Any]:"""The reading as the report keeps it."""@@ -230,6 +259,11 @@ class Reading:"unconfirmed": [list(r) for r in self.unconfirmed]}if self.step is not None:out["step_range"] = [round(self.step / ROOT2, 2), round(self.step, 2), round(self.step * ROOT2, 2)]+ if self.stands:+ out["stands"] = [list(r) for r in self.stands]+ out["run_limit"] = round(self.run_limit, 2)+ if self.cycles is not None:+ out["cycles"] = self.cyclesif self.alternation is not None:out["alternation"] = self.alternationif self.why is not None:@@ -243,25 +277,28 @@ class Reading:yield sorted(pick)def ring_count(self, s: int, L: int) -> int | None:- """Crossings on the loop cut s/L plays, its wrap included: a check that the loop shows what the clip counts."""+ """Steps on the loop cut s/L plays, its wrap included — a crossing each, two where the crossings mark cycles: a+ check that the loop shows what the clip counts."""if self.sides is not None:w = self.sides[s:s + L]- return sum(1 for j in range(1, L) if w[j] != w[j - 1]) + (1 if w[L - 1] != w[0] else 0)+ return self.per * (sum(1 for j in range(1, L) if w[j] != w[j - 1]) + (1 if w[L - 1] != w[0] else 0))if self.together is None:return Nonet = list(self.together[s:s + L])if all(t) or not any(t):return 0r = t.index(False)- return len(_runs(t[r:] + t[:r]))+ return self.per * len(_runs(t[r:] + t[:r]))def _scenario(self, c: list[float], s: int, L: int) -> tuple[str, str, str, list[int], list[float], float | None]:- """One scenario (every bounded crossing placed): (verdict, code, why, ks, deltas, m)."""+ """One scenario (every bounded crossing placed): (verdict, code, why, ks, deltas, the step). The step range is+ read on the intervals between crossings, and the count is `per` steps an interval."""e, last = s + L, s + L - 1if len(c) < 3:return "uncertain", "no-range", "under two steps in the clip: no step range", [], [], Nonem = float(np.median(np.diff(c)))lo, hi = m / ROOT2, m * ROOT2+ step = m / self.perdef played(a: float, b: float) -> bool:return max(math.floor(a) + 1, s) <= min(math.ceil(b) - 1, last)@@ -269,24 +306,24 @@ class Reading:partial = [(a, b) for a, b in self.unconfirmed if a <= last and b >= s]if partial:what = ", ".join(f"{a}..{b}" for a, b in partial)- return "uncertain", "partial", f"plays frames no crossing confirms ({what}): a stance, a pass the clip cut or a change it ended on", [], [], m+ return "uncertain", "partial", f"plays frames no crossing confirms ({what}): a stance, a pass the clip cut or a change it ended on", [], [], stephead_played, tail_played = s < c[0], last > c[-1]before = (c[0] - hi, min(c[0] - lo, self.head_limit))after = (max(c[-1] + lo, self.tail_limit), c[-1] + hi)if head_played and before[0] > before[1] + EPS:- return "uncertain", "head-stall", f"plays the clip's head: {c[0] - self.head_limit:.1f}+ frames with no crossing, over {hi:.1f}", [], [], m+ return "uncertain", "head-stall", f"plays the clip's head: {c[0] - self.head_limit:.1f}+ frames with no crossing, over {hi:.1f}", [], [], stepif tail_played and after[0] > after[1] + EPS:- return "uncertain", "tail-stall", f"plays the clip's tail: {self.tail_limit - c[-1]:.1f}+ frames with no crossing, over {hi:.1f}", [], [], m+ return "uncertain", "tail-stall", f"plays the clip's tail: {self.tail_limit - c[-1]:.1f}+ frames with no crossing, over {hi:.1f}", [], [], stepbad = [(a, b) for a, b in zip(c, c[1:]) if played(a, b) and not lo - EPS <= b - a <= hi + EPS]if bad:what = ", ".join(f"{a:g}->{b:g} ({b - a:.1f})" for a, b in bad)return ("uncertain", "step-long" if any(b - a > hi for a, b in bad) else "step-short",- f"plays a step out of [{lo:.1f}, {hi:.1f}]: {what}", [], [], m)+ f"plays a step out of [{lo:.1f}, {hi:.1f}]: {what}", [], [], step)if self.run_limit is not None:- stands = [(a, b) for a, b in self.runs if a <= last and b >= s and b - a + 1 > self.run_limit + EPS]+ stands = [(a, b) for a, b in self.stands if a <= last and b >= s]if stands:what = ", ".join(f"{a}..{b}" for a, b in stands)- return "uncertain", "stand", f"plays a stand: feet together {what}, over {self.run_limit:.1f} frames", [], [], m+ return "uncertain", "stand", f"plays a stand: feet together {what}, over {self.run_limit:.1f} frames", [], [], stepheads = np.linspace(*before, OPEN_SAMPLES) if head_played else [None]if e <= c[-1]:tails: Any = [None]@@ -298,21 +335,21 @@ class Reading:for x in heads:for y in tails:cc = ([x] if x is not None else []) + list(c) + ([y] if y is not None else [])- advance = _phi(cc, e) - _phi(cc, s)+ advance = self.per * (_phi(cc, e) - _phi(cc, s))k = int(math.floor(advance + 0.5))ks.add(k)deltas.append(advance - k)if len(ks) > 1:- return "uncertain", "open-count", f"the open step leaves the count open: {sorted(ks)}", sorted(ks), deltas, m+ return "uncertain", "open-count", f"the open step leaves the count open: {sorted(ks)}", sorted(ks), deltas, stepk = next(iter(ks))if not all(SEAM_BAND[0] - EPS <= d <= SEAM_BAND[1] + EPS for d in deltas):return ("uncertain", "seam", f"the wrap joins points {min(deltas):+.2f}..{max(deltas):+.2f} of a step apart: it makes or hides a crossing",- [k], deltas, m)+ [k], deltas, step)if k == 0:- return "uncertain", "no-step", "under half a step: no crossing", [k], deltas, m+ return "uncertain", "no-step", "under half a step: no crossing", [k], deltas, stepif k == 2:- return "two", "two", "two steps", [k], deltas, m- return "refuted", "refuted", f"{'one step' if k == 1 else f'{k} steps'}, each seen", [k], deltas, m+ return "two", "two", "two steps", [k], deltas, step+ return "refuted", "refuted", f"{'one step' if k == 1 else f'{k} steps'}, each seen", [k], deltas, stepdef judge(self, s: int, L: int) -> dict[str, Any]:"""The cut s/L: `verdict` (two, refuted, uncertain) with its `code` and `why`, the steps it covers (`k`), the@@ -395,7 +432,7 @@ def read(sig: dict[str, list[float]]) -> Reading:sides=[int(x) for x in sides], unconfirmed=unconfirmed)if reading.readable:# The lean of feet stepping turns over every step; a body swaying or wobbling on another beat does not.- alternation = _alternation(sig["lean"], reading.step)+ alternation = correlation_on(sig["lean"], reading.step)reading.alternation = None if alternation is None else round(alternation, 3)if alternation is None or alternation > ALTERNATION_MAX:reading.why = (f"the foot band's lean does not turn over a step on (correlation {alternation:+.2f} at "@@ -404,13 +441,14 @@ def read(sig: dict[str, list[float]]) -> Reading:return reading-def _alternation(lean: list[float], step: float) -> float | None:- """The lean's correlation one step on (its trend taken out), the larger at the two whole lags about `step`."""- x = np.asarray(lean, dtype=float)+def correlation_on(values: list[float], span: float) -> float | None:+ """A per-frame signal's correlation `span` frames on (its trend taken out), the larger at the two whole lags about+ `span`: the lean's one step on (`read`), a foot cue's one interval on (`local_cycle.read_cycles`)."""+ x = np.asarray(values, dtype=float)t = np.arange(len(x))x = x - np.polyval(np.polyfit(t, x, 1), t)out = []- for lag in sorted({math.floor(step), math.ceil(step)}):+ for lag in sorted({math.floor(span), math.ceil(span)}):a, b = x[:-lag], x[lag:]if lag < 1 or len(a) < 3 or a.std() < 1e-12 or b.std() < 1e-12:return Nonediff --git a/sprite_gen/video/legs.py b/sprite_gen/video/legs.pyindex 56547fe..fe9feb4 100644--- a/sprite_gen/video/legs.py+++ b/sprite_gen/video/legs.py@@ -15,6 +15,11 @@ Both read the same per-frame signals (`strike_signals`) and choose between them- `gap`: the widest empty run between the foot band's two ends, of the frame's height — two feetseen apart.+Which of the two feet is which is read on cues the view draws (`depth_cue`, `shade_cue`): from the front or back the+foot nearer the viewer is drawn lower, from the side or a diagonal the far leg is drawn in shade. `video-cycle-align`+names the foot that lands by them (`align.strike_foot`), and the step count asks whether the same leg leads again one+crossing interval on (`local_cycle.read_cycles`).+The swing of the stride or the lowest row says there is something to read, not that it is legs:a legless body that squashes as it bounces widens its foot band once a cycle, where a walker'swidens once a step. Counting steps therefore also asks for two feet seen apart (`feet_apart`).@@ -41,6 +46,7 @@ REACH_MIN = 0.015 # the lowest row's swing (of the body's height) that says a f# each step, from any view; a legless body's foot band is one run.FEET_APART = 0.02FEET_APART_SHARE = 0.2+SHADE_BAND = 0.15 # the shade cue reads the feet and lower legs: the lowest 15 % of the bodydef _longest_runs(solid: np.ndarray) -> np.ndarray:@@ -116,3 +122,35 @@ def step_signal(sig: dict[str, list[float]]) -> dict[str, Any]:if apart < FEET_APART_SHARE:return {**record, "by": None, "why": f"no two feet seen apart ({apart:.0%} of the frames, legs from {FEET_APART_SHARE:.0%})"}return {**record, "by": by[0], "values": [float(v) for v in sig[by[0]]]}+++def feet_halves(frame: Image.Image) -> tuple[np.ndarray, np.ndarray, int]:+ """(solid mask, the picture's right half of the feet as a column mask, body height): the halves+ split at the middle of the foot band (the lowest FOOT_BAND of the frame's own height)."""+ solid = np.asarray(frame.getchannel("A")) >= LOW_ALPHA+ rows = np.nonzero(solid.any(axis=1))[0]+ y1, height = int(rows[-1]), int(rows[-1] - rows[0] + 1)+ xs = np.nonzero(solid[y1 + 1 - max(1, round(height * FOOT_BAND)) : y1 + 1].any(axis=0))[0]+ return solid, np.arange(solid.shape[1]) >= (xs[0] + xs[-1]) / 2, height+++def depth_cue(frame: Image.Image) -> float:+ """How much lower the picture's right foot is drawn than its left, as a fraction of the body's+ height (the lowest solid row of each half)."""+ solid, right, height = feet_halves(frame)+ low = [int(np.nonzero(solid[:, half].any(axis=1))[0].max()) if solid[:, half].any() else 0 for half in (~right, right)]+ return (low[1] - low[0]) / height+++def shade_cue(frame: Image.Image, facing: str) -> float:+ """How much lighter the front foot is drawn than the back one (mean luma 0..1 of the lowest+ SHADE_BAND of the body, front half against back half; the front is the side faced)."""+ solid, right, height = feet_halves(frame)+ rows = np.nonzero(solid.any(axis=1))[0]+ band = np.zeros_like(solid)+ band[rows[-1] + 1 - max(1, round(height * SHADE_BAND)) : rows[-1] + 1] = True+ rgb = np.asarray(frame.convert("RGB"), dtype=np.float32) / 255.0+ luma = rgb @ np.array([0.299, 0.587, 0.114], dtype=np.float32)+ front = right if facing == "right" else ~right+ parts = [luma[solid & band & cols[None, :]] for cols in (front, ~front)]+ return float(parts[0].mean() - parts[1].mean()) if all(p.size for p in parts) else 0.0diff --git a/sprite_gen/video/local_cycle.py b/sprite_gen/video/local_cycle.pyindex d1d5535..21d7dc2 100644--- a/sprite_gen/video/local_cycle.py+++ b/sprite_gen/video/local_cycle.py@@ -18,6 +18,7 @@ from __future__ import annotationsimport mathfrom sprite_gen._deps import npfrom sprite_gen.video import period as period_mod+from sprite_gen.video import crossings as crossings_modfrom sprite_gen.video.crossings import HIDE_SHAREREFUSED_SHOWN = 12 # refused windows a failed search reports, as many as a found cycle's candidates@@ -26,11 +27,15 @@ REFUSED_SHOWN = 12 # refused windows a failed search reports, as many as a founSEAM_FLOW_BAND = 0.5REPEAT_OVER_STEP_MAX = 2 # `detect` refuses a repeat further off than two playback steps ('repeat error over two steps')SEAM_TRIES = 4 # two-step cuts, best first, whose seam is read as the seam gate reads it before one is taken (`by_steps`)-# The clip a cut on, frame by frame along the cut, at most this many of the cut's playback steps off: the same picture-# again (`same_picture`). An odd count of steps swaps the legs a cut on, and a step drawn nearer than the next frame-# is no swap: the count missed a crossing — asked only where a pass can hide (crossings.HIDE_SHARE), since from the-# side a step on can draw as near as that, its legs alike.-SAME_PICTURE_MAX = 1.0+# Whether the crossings mark cycles (`read_cycles`): the clip one interval between crossings on is nearer than half an+# interval on and as near as two intervals on within CYCLE_SLACK of the clip's mean step (each read at a whole lag, up+# to half a frame off the interval: about half a step).+CYCLE_SLACK = 0.5+# ... unless the view's foot cue (`legs.shade_cue` from a diagonal or the side, `legs.depth_cue` from the front or+# back) correlates at CUE_SWAPPED or under one interval on (`crossings.correlation_on`): the other leg leads there,+# and the interval is a step. A cue that does not follow the feet reads near 0 and decides nothing.+CUE_SWAPPED = -0.2+SIDE_VIEW = 'side' # from the side the legs a step on are one silhouette, as near as a cycle on: asked only where a pass hidesdef _around(start, length):@@ -480,37 +485,60 @@ def _calm(row):return 'pops' in row['top'] and not row['top']['pops']-def same_picture(distances, start, length):- """How far the clip one cut on lies from the cut, frame by frame along it, in the cut's playback steps: the mean of- each frame's distance to the frame `length` on, over the cut's mean step. None where under half the cut has a- frame one cut on in the clip, or the cut does not move."""+def repeat_at(distances, span):+ """How far the clip lies from itself `span` frames on, the nearer at the two whole lags about it: the mean distance of+ every frame to the one a lag on, over the clip's mean step from one frame to the next. None where the clip holds+ under half a lag of frames past it, or does not move."""n = len(distances)- js = np.arange(start, start+length)- js = js[js+length < n]- step = float(np.diag(distances[start:start+length, start:start+length], 1).mean())- if len(js) < length/2 or step <= 1e-10:+ step = float(np.diag(distances, 1).mean()) if n > 1 else 0.0+ found = [float(np.diag(distances, lag).mean())/step for lag in sorted({math.floor(span), math.ceil(span)})+ if lag >= 1 and n-lag >= max(2, lag/2) and step > 1e-10]+ return min(found) if found else None+++def read_cycles(reading, distances, *, view=None, cue=None):+ """Whether the crossings the clip shows (`reading`, gap mode) mark its cycles, not its steps, read and kept on the+ reading (`Reading.mark_cycles`; crossings.py, "Crossings that mark cycles"). The feet need not meet on the screen+ at every pass: the far foot can pass hidden behind the near one, or a foot step toward or away from the camera and+ pass the other apart. Then they meet once a cycle, and the clip one interval between crossings on (`repeat_at`) has+ the same leg leading, not the other: it is nearer than half an interval on (the pose a step on) and as near as two+ intervals on within CYCLE_SLACK. Where the clip says so, the view's foot cue (`cue`, per frame) is asked whether the+ other leg leads one interval on (`crossings.correlation_on` at CUE_SWAPPED or under): there the interval is a step.++ Asked where a pass can hide (`reading.overlap` over HIDE_SHARE, the far foot behind the near one), or where the+ `view` is given and is not the side; from the side the legs a step on are one silhouette, as near as a cycle on, and+ the picture cannot tell. Returns what was read, None where it is not asked."""+ if reading.mode != 'gap' or not reading.readable:return None- return float(distances[js, js+length].mean())/step---def same_picture_count(reading, distances, judged):- """A cut the crossings count an odd number of steps (`judged`, `reading.judge`), asked whether the count missed a- crossing: where the feet are seen together over more than HIDE_SHARE of a step at a pass (`reading.overlap`) and the- clip a cut on is the same picture (`same_picture`, at most SAME_PICTURE_MAX playback steps along the cut), no legs- swapped. Returns (what was read, None where it is not asked; the cut's count, `uncertain` (`same-picture`) where the- count missed a crossing, else `judged` itself)."""overlap = reading.overlap- if not (judged['verdict'] == 'refuted' and judged['k'][0] % 2 and overlap is not None and overlap > HIDE_SHARE):- return None, judged- near = same_picture(distances, *judged['cut'])- said = {'over_step': None if near is None else round(near, 3), 'max': SAME_PICTURE_MAX, 'overlap': round(overlap, 3),- 'hides': HIDE_SHARE}- if near is None or near > SAME_PICTURE_MAX:- return said, judged- return said, {**judged, 'verdict': 'uncertain', 'code': 'same-picture',- 'why': f"the crossings count {judged['why']}, but the feet are seen together {overlap:.2f} of a step at a "- f"pass (over {HIDE_SHARE:g}: a pass can hide there) and the clip a cut on is the same picture ({near:.2f} "- f"playback steps along the cut, at most {SAME_PICTURE_MAX:g}): no legs swapped, a crossing unseen"}+ hides = overlap is not None and overlap > HIDE_SHARE+ if not hides and view in (None, SIDE_VIEW):+ return None+ d = reading.interval+ near = {name: repeat_at(distances, span) for name, span in (('half', d/2), ('one', d), ('two', 2*d))}+ said = {'asked': (f'the feet together {overlap:.2f} of an interval at a pass, over {HIDE_SHARE:g}: a pass can hide there'+ if hides else f'the {view} view, the legs side by side'),+ 'interval': round(d, 2), 'overlap': None if overlap is None else round(overlap, 3),+ **{k: None if v is None else round(v, 3) for k, v in near.items()}, 'slack': CYCLE_SLACK}+ if None in near.values():+ said.update(cycles=False, why='the clip is too short to be read two intervals on')+ elif not (near['one'] < near['half'] and near['one'] <= near['two']+CYCLE_SLACK):+ said.update(cycles=False, why=f"the clip one interval on ({near['one']:.2f} steps off) is not the same picture as half "+ f"an interval on ({near['half']:.2f}) and two on ({near['two']:.2f}, +{CYCLE_SLACK:g}) "+ "would make it: the crossings mark steps")+ else:+ turned = None if cue is None else crossings_mod.correlation_on(cue, d)+ if cue is not None:+ said['cue'] = {'one': None if turned is None else round(turned, 3), 'swapped': CUE_SWAPPED}+ if turned is not None and turned <= CUE_SWAPPED:+ said.update(cycles=False, why=f"the clip one interval on is the same picture, but the view's foot cue turns over "+ f"there ({turned:+.2f}, at most {CUE_SWAPPED:+g}): the other leg leads, a step")+ else:+ said.update(cycles=True, why=f"the clip one interval on ({near['one']:.2f} steps off) is nearer than half an "+ f"interval on ({near['half']:.2f}) and as near as two on ({near['two']:.2f}, "+ f"+{CYCLE_SLACK:g}): the same leg leads, the feet meet once a cycle")+ reading.mark_cycles(said)+ return saiddef _rank(rows, *, flow_limit, seam_max, in_phase):@@ -537,20 +565,14 @@ 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):- """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).+ """The cut the clip's own steps choose (`reading`, crossings.Reading, whose crossings mark steps or cycles as+ `read_cycles` read them), 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).- The clip does not show its steps (`reading.readable` false: no feet seen, a lean that is not feet stepping,under two steps): the search's cut, as it chose it.- The search's cut covers two steps (`two`) and its wrap joins the walk at its own point (`reading.in_phase`):that cut, as it chose it.- - The crossings count the search's cut an odd number of steps — the legs swapped a cut on — but the feet are seen- together over more than HIDE_SHARE of a step at a pass (`reading.overlap`: the far foot behind the near one, a- pass can hide there) and the clip a cut on is the same picture (`same_picture`, at most SAME_PICTURE_MAX- playback steps along the cut): no swap, so the count missed a crossing and proves nothing. The search's cut, as- it chose it, its count `uncertain` (`same-picture`). Where passes are brief — from the side, where a step on- draws as near as the next frame with the legs alike — the count stands.- Else the cuts [min_len, max_len] frames long that cover two steps, any start, however long — the window thatbinds the search binds no count; none, and the search's word stands. Those in phase, if any, else all, areread at the wrap (`seam_flow(start, length)`: the flow off of the cut's last and first frames; `wrap_pop`, the@@ -586,12 +608,6 @@ def by_steps(distances, trajectory, reading, *, found, refused, min_len, max_lenif reading.in_phase(searched):record.update(chosen_by='search', cut=searched)return _two_steps(found, record), record- said, counted = same_picture_count(reading, distances, searched)- if said is not None:- record['search']['same_picture'] = said- if counted is not searched:- record.update(chosen_by='search', cut=counted)- return found, recordtwos = reading.twos(min_len, max_len)record['two_cuts'] = len(twos)if not twos:diff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.pyindex 7648a85..da1dd7f 100644--- a/sprite_gen/video/loop.py+++ b/sprite_gen/video/loop.py@@ -45,6 +45,7 @@ from typing import Anyfrom PIL import Imagefrom sprite_gen._deps import np+from sprite_gen.gen import handedness as handed_modfrom sprite_gen.spec.runio import atomic_write_text, new_stage, refuse_overlapfrom sprite_gen.util.gif_utils import save_clean_giffrom sprite_gen.util.resample import resize_cell@@ -1035,7 +1036,8 @@ def _repair_jumps(frames: list[Image.Image], interpolate: rife_mod.Interpolate |torso = Noneif wrap is not None:torso = None if "off" in wrap else repair_mod.Torso(frames)- asked = partial(repair_mod.overlap_wrap, others=wrap.get("others", {}), seam=wrap_on_cells, steps=ring_steps,+ asked = partial(repair_mod.overlap_wrap, others=wrap.get("others", {}), seam=wrap_on_cells,+ steps=partial(ring_steps, cycles=wrap.get("cycles")),seam_max=wrap["seam_max"], reads=bool(screen["reads"]), torso=torso, off=wrap.get("off"))try:frames, overlap = asked(frames, read=lazy_read)@@ -1204,6 +1206,49 @@ def part_retake(record: dict[str, Any], cut: tuple[int, int], *, given: bool) ->"remedy": "recut-or-retake" if given else "retake"}+STAND_REASON = "start-stop"+++def stand_retake(cycle: dict[str, Any]) -> dict[str, Any] | None:+ """A take to film again where the walk starts or stops in it: the clip shows its steps (`step_count`), its feet stand+ together longer than any pass (the reading's `stands`) — the walk stands still — and the cut kept is not counted+ two steps (its `cut` verdict is not `two`): no cut of two steps closes between the stands. `reason` STAND_REASON,+ `reasons`, the stands, the run limit, the crossings and the cut kept with the count's word on it under+ `start_stop`, and `remedy` `retake`. None otherwise."""+ counted = cycle.get("step_count") or {}+ cut = counted.get("cut") or {}+ if not counted.get("readable") or not counted.get("stands") or cut.get("verdict") == "two":+ return None+ return {"reason": STAND_REASON, "reasons": [STAND_REASON],+ "start_stop": {"stands": counted["stands"], "run_limit": counted["run_limit"], "crossings": counted["crossings"],+ "cut": [cycle["start"], cycle["length"]],+ **{k: cut[k] for k in ("verdict", "code", "why") if k in cut}},+ "remedy": "retake"}+++def retakes(*records: dict[str, Any] | None) -> dict[str, Any] | None:+ """The loop's `retake`: the first reason's record, every reason in `reasons` and each other reason's numbers beside+ it. None where there is none."""+ found = [r for r in records if r]+ if not found:+ return None+ out = dict(found[0])+ for other in found[1:]:+ out.update({k: v for k, v in other.items() if k not in ("reason", "reasons", "remedy")})+ out["reasons"] = [*out["reasons"], *other["reasons"]]+ return out+++def _stand_line(record: dict[str, Any]) -> str:+ """A walk that starts or stops in the take (`stand_retake`), in words (a `video-loop: warning:` line)."""+ said = record["start_stop"]+ stands = ", ".join(f"{a}..{b}" for a, b in said["stands"])+ why = f": {said['why']}" if "why" in said else ""+ return (f"film this direction again ({STAND_REASON}) — the feet stand together {stands}, longer than any pass "+ f"({said['run_limit']:g} frames): the walk starts or stops in the take, and the cut {said['cut'][0]}/{said['cut'][1]} "+ f"kept is not two steps ({said.get('verdict', 'unread')}{why})")++def _pop_lines(record: dict[str, Any], *, given: bool) -> list[str]:"""Each pop that plays as filmed, a take to film again (`retake`), in words (`video-loop: warning:` lines)."""why = ("the cut was given (--cycle fixed or pinned): cut it where no part pops, or film it again" if given else@@ -1494,16 +1539,39 @@ def wrap_on_cells(frames: list[Image.Image]) -> float:return float(np.abs(flat[-1] - flat[0]).mean()) / step if step > 0 else math.inf-def ring_steps(frames: list[Image.Image]) -> dict[str, Any]:+def read_steps(frames: list[Image.Image], D: np.ndarray, *, view: str | None = None, facing: str = "right",+ signals: dict[str, list[float]] | None = None) -> crossings_mod.Reading:+ """The clip's crossings (`crossings.read`), and whether they mark its cycles (`local_cycle.read_cycles`, on `D`, the+ clip's distances, and the `view`'s foot cue: `legs.shade_cue` from the side or a diagonal, `legs.depth_cue` from the+ front or back). Every count the clip's steps make is read on it: the search's cut (`_by_steps`), a fixed cut+ (`fixed_count`) and, carried to the loop, the loop as it plays (`ring_steps`). `signals` are the frames' leg signals+ where already read."""+ signals = leg_signals(frames) if signals is None else signals+ try:+ reading = crossings_mod.read(crossings_mod.foot_signals(frames, gap=signals["gap"] if signals else None))+ except ValueError:+ return crossings_mod.Reading(len(frames), "gap", [], why="a frame has no solid body to read the feet from")+ cue = None+ if view is not None:+ lateral = view in handed_mod.LATERAL_VIEWS+ cue = [legs_mod.shade_cue(f, facing) if lateral else legs_mod.depth_cue(f) for f in frames]+ local_cycle.read_cycles(reading, D, view=view, cue=cue)+ return reading+++def ring_steps(frames: list[Image.Image], *, cycles: dict[str, Any] | None = None) -> dict[str, Any]:"""The steps a loop shows as it plays round: the crossings read on its frames played three times over(`crossings.read`), the turn in the middle judged (`Reading.judge`) — a two where the loop still walks two steps,- joined where the walk goes on."""+ joined where the walk goes on. `cycles` is what the clip the loop was cut from said of its crossings+ (`read_steps`): a loop is too short to be read two intervals on, and its crossings mark what the clip's mark."""ring = [*frames, *frames, *frames]signals = leg_signals(ring)try:reading = crossings_mod.read(crossings_mod.foot_signals(ring, gap=signals["gap"] if signals else None))except ValueError as exc:return {"verdict": "uncertain", "code": "unread", "why": str(exc)}+ if cycles is not None and reading.readable:+ reading.mark_cycles(cycles)return reading.judge(len(frames), len(frames))@@ -1577,21 +1645,13 @@ def drawing_steps(cells: list[Image.Image], pixel: float = 1.0) -> dict[str, Any**({"jitter": jitter} if jitter else {})}-def fixed_count(frames: list[Image.Image], D: np.ndarray, start: int, length: int) -> dict[str, Any]:- """The clip's own count of the steps a fixed cut covers: the crossings of its frames (`crossings.read`), the cut- judged (`Reading.judge`), and an odd count the clip may have missed a crossing in asked whether the clip a cut on is- the same picture (`local_cycle.same_picture_count`, as `--anchor motion-auto` asks it, on `D`, the clip's distances).- Recorded `chosen_by: caller`: the caller named the cut."""- signals = leg_signals(frames)- try:- reading = crossings_mod.read(crossings_mod.foot_signals(frames, gap=signals["gap"] if signals else None))- except ValueError:- reading = crossings_mod.Reading(len(frames), "gap", [], why="a frame has no solid body to read the feet from")- record = {**reading.record(), "chosen_by": "caller"}- said, record["cut"] = local_cycle.same_picture_count(reading, D, reading.judge(start, length))- if said is not None:- record["same_picture"] = said- return record+def fixed_count(frames: list[Image.Image], D: np.ndarray, start: int, length: int, *, view: str | None = None,+ facing: str = "right") -> dict[str, Any]:+ """The clip's own count of the steps a fixed cut covers: the crossings of its frames, steps or cycles as the clip+ says (`read_steps`, on `D`, the clip's distances, as `--anchor motion-auto` reads them), the cut judged+ (`Reading.judge`). Recorded `chosen_by: caller`: the caller named the cut."""+ reading = read_steps(frames, D, view=view, facing=facing)+ return {**reading.record(), "chosen_by": "caller", "cut": reading.judge(start, length)}def odd_count(cycle: dict[str, Any]) -> bool:@@ -1625,19 +1685,17 @@ 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, view: str | None = None, facing: str = "right") -> 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`).+ sprite_gen/video/crossings.py, steps or cycles as the clip and its `view` say: `read_steps`), 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 thatfinds nothing names each refused window's count, those the crossings refute last, and raises."""signals = leg_signals(frames)- try:- reading = crossings_mod.read(crossings_mod.foot_signals(frames, gap=signals["gap"] if signals else None))- except ValueError:- reading = crossings_mod.Reading(len(frames), "gap", [], why="a frame has no solid body to read the feet from")+ reading = read_steps(frames, D, view=view, facing=facing, signals=signals)moved = moved_alpha(frames, analysis)picked, record = local_cycle.by_steps(D, trajectory, reading, found=cycle, refused=refused, min_len=window.lo, max_len=window.max_len or len(frames),@@ -1889,6 +1947,7 @@ def _cut_loop(wrap_blend: str = "auto",unfixed: str = "warn",seam_pop_max: float | None = repair_mod.SEAM_POP_REFERENCE,+ view: str | None = None,) -> dict[str, Any]:state = state.strip().lower() if state else stateif state == effect.STATE:@@ -1924,6 +1983,8 @@ def _cut_loop(raise SystemExit(f"video-loop: unknown --unfixed {unfixed!r}; expected one of {', '.join(UNFIXED_MODES)}")if facing not in FACINGS:raise SystemExit(f"video-loop: unknown --facing {facing!r}; expected one of {', '.join(FACINGS)}")+ if view is not None and view not in handed_mod.VIEWS:+ raise SystemExit(f"video-loop: unknown --view {view!r}; expected one of {', '.join(handed_mod.VIEWS)}")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 anchor is None:@@ -2057,7 +2118,8 @@ def _cut_loop(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)+ window=window, searched=searched, detect=detect, seam_max=seam_max, cells=cells,+ view=view, facing=facing)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(@@ -2090,7 +2152,7 @@ def _cut_loop(if gait_frames is not None:# A walk or run loops on two steps: the clip's own count of the cut the caller named, as a search's cut is# counted. An odd count swaps the legs at the wrap, however close the frames there look.- cycle["step_count"] = fixed_count(gait_frames, D, start, length)+ cycle["step_count"] = fixed_count(gait_frames, D, start, length, view=view, facing=facing)if odd_count(cycle):counted = cycle["step_count"]if seam_max <= STEP_RATIO_MAX:@@ -2245,6 +2307,7 @@ def _cut_loop(wrap = ({"others": cycle_apart(files, start=i, length=L, skip=skip, analysis=analysis, motion=motion,size=frames[0].size), "seam_max": seam_max} if overlap_wrap == "on"else {"off": OVERLAP_WRAP_OFF, "seam_max": seam_max})+ wrap["cycles"] = cycle["step_count"].get("cycles")try:frames, report_base["jump_repair"], overlap = _repair_jumps(frames, interpolate, facing=facing, required=repair == "on",screen=report_base["ghost_screen"], wrap=wrap)@@ -2363,7 +2426,10 @@ def _cut_loop(# again (`retake`), named._pop_settled(report_base["part_pop"], frames, cut_frames)given = cycle_mode in ("fixed", "pinned")- report_base["retake"] = part_retake(report_base["part_pop"], (i, L), given=given)+ stand = stand_retake(cycle)+ report_base["retake"] = retakes(part_retake(report_base["part_pop"], (i, L), given=given), stand)+ if stand is not None:+ print(f"video-loop: warning: {_stand_line(stand)}", file=sys.stderr)pops_left = _pop_lines(report_base["part_pop"], given=given)if pops_left and unfixed == "refuse":error = (f"video-loop: a part pops at the loop's wrap — {'; '.join(pops_left)} ({cycle.get('kind', 'periodic')} "@@ -2710,6 +2776,12 @@ 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("--view", choices=handed_mod.VIEWS, default=None,+ help="walk/run: the view the clip is filmed from. The step count asks whether the feet, which need not "+ "meet on the screen at every pass, meet once a cycle (`cycle.step_count.cycles`): where a pass "+ "can hide, as without it, and from the front, the back or a diagonal also where passes are brief, "+ "the view's foot cue saying whether the other leg leads an interval on (docs/loop-repair.md "+ "section 3, \"The step count\"). Default: not given, asked only where a pass can hide")parser.add_argument("--name", default="loop", help="basename for strip/gif/webp outputs")parser.add_argument("--report", type=Path)@@ -2731,6 +2803,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]+ view=kwargs.get("view"), # type: ignore[arg-type])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")}diff --git a/tests/video/test_cycle_align.py b/tests/video/test_cycle_align.pyindex ad30dcf..bc3ad3e 100644--- a/tests/video/test_cycle_align.py+++ b/tests/video/test_cycle_align.py@@ -335,6 +335,28 @@ def test_video_set_aligns_each_gait_filmed_in_two_or_more_directions(tmp_path):assert batch.align_gaits(rows, tmp_path, "off") == {}+def test_video_set_leaves_a_take_to_film_again_for_a_start_or_stop_out_of_the_alignment(tmp_path):+ """A loop named a take to film again because the walk starts or stops in it (`retake` `start-stop`) loops no two+ steps: it is left out, its loop as cut, and the rest are aligned without it. Left alone, the state is not aligned."""+ from sprite_gen.video import batch++ stand = {"reason": "start-stop", "reasons": ["start-stop"], "remedy": "retake"}+ rows = []+ for direction, length, retake in (("front", 20, None), ("side", 24, None), ("back", 19, stand)):+ item = tmp_path / f"{direction}-walk"+ item.mkdir()+ _cut(item, "loop", length)+ rows.append({"item": f"{direction}-walk", "direction": direction, "state": "walk", "dir": str(item), "ok": True,+ "loop": {"n_out": length, **({"retake": retake} if retake else {})}})+ out = batch.align_gaits(rows, tmp_path, "auto", interpolate=Recorder())+ assert out["walk"]["applied"] and out["walk"]["lengths"] == [20, 24] and out["walk"]["left_out"] == {"back-walk": ["start-stop"]}+ assert [r["loop"]["n_out"] for r in rows] == [out["walk"]["length"]] * 2 + [19] and "cycle_align" not in rows[2]["loop"]+ alone = batch.align_gaits(rows[1:], tmp_path, "auto", interpolate=Recorder())+ assert alone == {"walk": {"ok": True, "applied": False, "why": "fewer than two directions left to align",+ "left_out": {"back-walk": ["start-stop"]}}}++def _no_rife(monkeypatch, tmp_path: Path) -> None:monkeypatch.delenv("SPRITE_GEN_RIFE", raising=False)# PATH keeps every other tool (img2webp, ffmpeg); only the directories holding a RIFE godiff --git a/tests/video/test_gait_guard_anchor_wide.py b/tests/video/test_gait_guard_anchor_wide.pyindex ec2e7ad..9e8119b 100644--- a/tests/video/test_gait_guard_anchor_wide.py+++ b/tests/video/test_gait_guard_anchor_wide.py@@ -4,7 +4,9 @@still come back as a two-step period;* one-shot detection is not bound by the periodic window's lower edge;* `--anchor feet` removes in-canvas drift (not the step) and reports it;-* raised-limb states get a wide canvas, and video-set can force shape/anchor.+* raised-limb states get a wide canvas, and video-set can force shape/anchor;+* with no --anchor, video-set cuts a searched walk or run with motion-auto and every other item with none, and+ lists a loop's take to film again (`retake`)."""from __future__ import annotations@@ -245,6 +247,50 @@ def test_video_set_passes_shape_and_anchor_through(tmp_path: Path, monkeypatch,assert "uncorrected" in (tmp_path / "set/table.md").read_text()[email protected]("state,play,anchor,cut", [("walk", None, None, "motion-auto"), ("run", "loop", None, "motion-auto"),+ ("cheer", None, None, "none"), ("walk", None, "none", "none"),+ ("idle", None, None, "none")])+def test_video_set_cuts_a_searched_walk_with_motion_auto_unless_told(tmp_path: Path, monkeypatch, state, play, anchor, cut) -> None:+ seen: dict[str, object] = {}++ def fake_canvas(base, out, *, state, shape, facing, headroom, lead, report_path, fit="state", view=None):+ Image.new("RGB", (32, 32), (0, 255, 0)).save(out)+ return {"shape": shape or "square", "canvas": [32, 32], "offset": [0, 0]}++ def fake_frames(clip, out_dir, **kw):+ keyed = Path(out_dir) / "keyed"+ keyed.mkdir(parents=True, exist_ok=True)+ return {"fps": 24.0, "frames": 30, "alpha_zero_pct_min": 0.0, "alpha_zero_pct_max": 0.0, "keyed_dir": str(keyed), "spill": {"mode": "full"}}++ def fake_loop(frames_dir, out_dir, **kw):+ seen.update(anchor=kw["anchor"], cycle_mode=kw["cycle_mode"])+ return {"cycle": {"kind": "periodic", "length": 24, "period_global": 24, "ratio": 0.2}, "resampled_seam_ratio": 0.3, "n_out": 8,+ "gif": {"file": "g"}, "webp": {"file": "w"}, "strip": {"path": "s", "drift_px": 0},+ "retake": {"reason": "start-stop", "reasons": ["start-stop"], "start_stop": {}, "remedy": "retake"}}++ def fake_video(image, prompt, out, report, *, duration, resolution, log, **pin):+ Path(out).write_bytes(b"x")+ Path(report).write_text("{}")+ Path(log).write_text("")+ return 0++ monkeypatch.setattr(batch_mod.canvas_mod, "run_canvas", fake_canvas)+ monkeypatch.setattr(batch_mod.frames_mod, "run_frames", fake_frames)+ monkeypatch.setattr(batch_mod.loop_mod, "run_loop", fake_loop)+ base = tmp_path / "base.png"+ Image.new("RGB", (32, 32), (0, 255, 0)).save(base)+ payload = batch_mod.run_set(bases={"front": base}, states=[state], root=tmp_path / "set", character=None, duration=6, resolution="720p",+ key="green", concurrency=1, force=False, gap=0.0, video_runner=fake_video, anchor=anchor,+ walk_start="as-given", **({"play": {state: play}} if play else {}))+ assert payload["ok"] == 1, payload["items"][0].get("error")+ assert seen["anchor"] == cut+ assert batch_mod.anchor_for(state, seen["cycle_mode"], anchor) == cut+ item = payload["items"][0]+ assert item["loop"]["retake"] == {"reason": "start-stop", "reasons": ["start-stop"], "remedy": "retake"}+ assert any(w.startswith(f"{item['item']}: film this direction again (start-stop)") for w in payload["warnings"])+ assert "film again: start-stop" in (tmp_path / "set/table.md").read_text()++def test_cheer_motion_template_names_no_limbs() -> None:text = batch_mod.MOTION_TEXT["cheer"] + batch_mod.MOTION_TEXT["wave"]for limb in ("arm", "leg", "knee", "hand", "foot", "wing"):diff --git a/tests/video/test_loop_silent_pass.py b/tests/video/test_loop_silent_pass.pyindex 17ee0a3..202193e 100644--- a/tests/video/test_loop_silent_pass.py+++ b/tests/video/test_loop_silent_pass.py@@ -8,8 +8,8 @@jitter of a loop that barely moves, not a jump, in any colour; a drawing moved two pixels is a jump in any colour.- A frame the jump repair took off the flow and could not make again (its group refused) and that stays off the flow is`jump_repair.unfixed`, said in a warning line; `--unfixed refuse` fails such a loop.-- A fixed cut the clip's own crossings count an odd number of steps fails (`loop.fixed_count`), but where the clip a cut on- is the same picture (the count missed a crossing), as `--anchor motion-auto` exempts its own cut.+- A fixed cut the clip's own crossings count an odd number of steps fails (`loop.fixed_count`); where they mark cycles (a+ pass hidden, the clip an interval on the same picture), they count as `--anchor motion-auto` counts its own cut.- A `--seam-max` past STEP_RATIO_MAX lifts the step gate with the seam: the loop is kept and a warning line says why.- The seam gate's refusal says why where the warning lines know it (a part on a beat of its own), in the failure line andin `seam_refusal`; elsewhere its line is as it was.@@ -27,7 +27,7 @@ import numpy as npimport pytestfrom PIL import Image, ImageDraw-from sprite_gen.video import local_cycle, repair+from sprite_gen.video import repairfrom sprite_gen.video import loop as loop_modfrom tests.video import test_gait_fallback as gaitfrom tests.video import test_loop_overlap as overlap@@ -232,15 +232,15 @@ def test_a_fixed_cut_the_clips_crossings_count_one_step_fails(tmp_path: Path, caassert f"the clip's crossings count the fixed cut {STRIDE}/{STRIDE // 2} one step" in capsys.readouterr().err-def test_a_fixed_cut_that_is_the_same_picture_a_cut_on_is_not_failed_on_its_count(tmp_path: Path):- """Seen from behind on twos, the far foot passes hidden: one crossing a cycle, and the count calls the cycle one- step. The clip a cut on is the same picture — no legs swapped, a crossing unseen — and the count stands aside, as it- does for the cut `--anchor motion-auto` takes."""+def test_a_fixed_cut_of_one_cycle_whose_crossings_mark_cycles_is_counted_two_steps(tmp_path: Path):+ """Seen from behind on twos, the far foot passes hidden: one crossing a cycle. The clip one interval on is the same+ picture, the crossings mark cycles, and the cut of one cycle is two steps — not failed, as `--anchor motion-auto`+ counts its own cut (the parent engine counted it one step and stood the count aside)."""frames = [_behind(k, cycle=20, hold=2) for k in range(73)]D = loop_mod._distances(np.stack([loop_mod._small_features(f) for f in frames]))counted = loop_mod.fixed_count(frames, D, 20, 20)- assert counted["chosen_by"] == "caller" and counted["same_picture"]["over_step"] <= local_cycle.SAME_PICTURE_MAX- assert counted["cut"]["verdict"] == "uncertain" and counted["cut"]["code"] == "same-picture"+ assert counted["chosen_by"] == "caller" and counted["cycles"]["cycles"] is True+ assert counted["cut"]["verdict"] == "two" and counted["cut"]["k"] == [2]assert not loop_mod.odd_count({"kind": "fixed", "step_count": counted})diff --git a/tests/video/test_walk_steps.py b/tests/video/test_walk_steps.pyindex 01c52f6..f38075d 100644--- a/tests/video/test_walk_steps.py+++ b/tests/video/test_walk_steps.py@@ -12,9 +12,13 @@ Each walker is drawn so the pixel search alone makes one of the faults a walk lo- a slow front walk in a short clip, refused outright (no periodic cycle found);- a walk that stalls, its cut playing the stalled step.-And two the count alone gets wrong, where the search's cut stands: a held walk seen from behind whose far foot-passes hidden (one crossing a cycle, the cycle counted one step), and a walk on threes whose tail closes on no cut-of two steps.+Two whose feet meet on the screen once a cycle, read as cycles (`local_cycle.read_cycles`) and cut one cycle: a walk+seen from behind whose far foot passes hidden behind the near one, on ones, twos or threes, a cycle a whole number of+frames or not (the parent engine counted the cycle one step and cut two cycles, or kept the search's cut unwritten); and+a walk on a front diagonal whose near foot steps out toward the camera and passes the far one apart, read so where its+view is given. Two guards: from the side, or where the view's foot cue says the other leg leads an interval on, the+count stands however alike a step on draws. And one the count alone gets wrong, where the search's cut stands: a walk on+threes whose tail closes on no cut of two steps.A walk the search already cuts two steps long, joined at the walk's own point, is cut exactly as before; a bodywhose feet cannot be read is cut as before. Synthetic frames only."""@@ -81,7 +85,7 @@ def _front(k: float, *, cycle: float, phase: float = 0, tail_cycle: float = 1, treturn im-def _behind(k: int, *, cycle: int, hold: int) -> Image.Image:+def _behind(k: int, *, cycle: float, hold: int) -> Image.Image:"""A walker seen from behind on a diagonal, drawn on twos or threes (`hold`): the near leg swings ahead and back,and the far one is seen beside it only while it is behind — ahead, it stands hidden behind the near leg. The feetare seen apart once a cycle and together through the other step, its pass hidden among them: one crossing shows a@@ -103,6 +107,25 @@ def _behind(k: int, *, cycle: int, hold: int) -> Image.Image:return im+def _outward(k: float, *, cycle: float) -> Image.Image:+ """A walker on a front diagonal whose near foot steps out toward the camera: it swings wide ahead and back, and the+ far foot hardly moves, so the feet meet on the screen once a cycle, where the near foot passes the far one on its+ way back; its pass on the way out is made apart. Arms opposite, the far one darker; the far leg a tone off the near."""+ ph = 2 * math.pi * k / cycle+ im = Image.new("RGBA", (300, 220))+ d = ImageDraw.Draw(im)+ x, y = 90, 40 + round(3 * math.cos(2 * ph))+ sw = 16 * math.sin(ph)+ near, far = x + 14 + sw, x + 34 - 4 * math.sin(ph)+ d.rectangle((x + 14 - sw - 4, y + 34, x + 14 - sw + 4, y + 72), fill=(150, 150, 150, 255))+ d.rectangle((far - 5, y + 80, far + 5, y + 126), fill=(61, 61, 71, 255))+ d.rectangle((near - 5, y + 80, near + 5, y + 126), fill=(60, 60, 70, 255))+ d.rectangle((x, y + 30, x + 28, y + 84), fill=(200, 80, 80, 255))+ d.rectangle((x + 2, y, x + 26, y + 28), fill=(230, 200, 170, 255))+ d.rectangle((x + 14 + sw - 4, y + 34, x + 14 + sw + 4, y + 72), fill=(225, 225, 225, 255))+ return im++def _alike(k: float, *, cycle: float, phase: float = 0, tone: int = 1, lean: float = 0) -> Image.Image:"""A side walker whose two steps are the same silhouette: the far leg and arm `tone` tones lighter than the nearones, the arms swinging `lean` px further back than forward — nothing else tells a step from the next."""@@ -191,8 +214,8 @@ def test_a_half_step_diagonal_walk_is_cut_two_steps(tmp_path):counted = _two_steps(report, 29)assert counted["mode"] == "gap" and counted["step_range"][1] == 14.5assert counted["search"]["verdict"] == "refuted" and counted["search"]["k"] == [1] and counted["search"]["cut"][1] in (14, 15)- # Its feet pass briefly: no pass can hide, and the count is not asked whether the clip a cut on is the same picture.- assert "same_picture" not in counted["search"]+ # Its feet pass briefly and no view is given: whether its crossings mark cycles is not asked.+ assert "cycles" not in countedstrip = json.loads((tmp_path / "out" / "loop.strip.json").read_text())assert strip["steps"] == 2 and strip["cycle_frames"] == report["cycle"]["length"]# The step screen's pixel suspicion of a cycle twice as long is settled by the count.@@ -246,25 +269,53 @@ def test_a_walk_that_stalls_is_not_cut_across_the_stalled_step(tmp_path):assert counted["search"]["code"] == "step-long"[email protected]("cycle, hold", [(20, 2), (24, 3)])-def test_a_held_walk_whose_far_foot_hides_is_cut_one_cycle(tmp_path, cycle, hold):- """Seen from behind on a diagonal, on twos or threes, the far foot passes hidden behind the near one: one crossing- shows a cycle, and the count takes the cycle for one step. The search's cut is the clip's cycle, the same picture a- cut on, which the count calls one step; a step on the legs are swapped, and a swap nearer than the next frame is- none — the count missed a crossing. The search's cut stands, one cycle, and no `steps` is written (the parent- engine cut it two cycles long, `steps: 2`, the set alignment's two-cycle screen settled by it)."""- report = _cut(tmp_path / "out", _keyed(tmp_path, lambda k: _behind(k, cycle=cycle, hold=hold)))+def _one_cycle(out: Path, cycle: float) -> dict:+ """The cut in `out` is one cycle of the walker, `cycle` frames, two steps by its crossings read as cycles, and says+ so — in its strip too."""+ report = json.loads((out / "loop.loop.report.json").read_text())c = report["cycle"]counted = c["step_count"]- assert c["length"] == cycle and "steps" not in c- assert "steps" not in json.loads((tmp_path / "out" / "loop.strip.json").read_text())- assert report["drawings"]["hold"] == hold and report["status"] == "passed"- assert counted["mode"] == "gap" and abs(counted["step_range"][1] - cycle) <= 1- assert counted["search"]["verdict"] == "refuted" and counted["search"]["k"] == [1]- assert counted["search"]["same_picture"]["over_step"] <= local_cycle.SAME_PICTURE_MAX- assert counted["chosen_by"] == "search" and counted["cut"]["verdict"] == "uncertain" and counted["cut"]["code"] == "same-picture"- assert c["method"] == "local-repeat-drift-v1"+ assert abs(c["length"] - cycle) <= 1+ assert c["steps"] == {"count": 2, "by": "crossings"}+ assert counted["mode"] == "gap" and counted["cycles"]["cycles"] is True+ assert abs(counted["step_range"][1] - cycle / 2) <= 1+ assert counted["cut"]["verdict"] == "two" and counted["cut"]["k"] == [2] and counted["cut"]["ring"] == 2+ assert abs(counted["cut"]["phase"]) <= crossings.PHASE_TOLERANCE+ assert json.loads((out / "loop.strip.json").read_text())["steps"] == 2+ assert report["status"] == "passed"+ return counted++[email protected]("cycle, hold", [(20, 2), (24, 3), (17.5, 1), (18.5, 1)])+def test_a_walk_whose_far_foot_hides_is_cut_one_cycle(tmp_path, cycle, hold):+ """Seen from behind on a diagonal, the far foot passes hidden behind the near one: the feet are seen together over+ more than half the interval between two crossings, one crossing a cycle. The clip one interval on is the same+ picture, a cycle on, and the count reads the crossings as cycles: two steps an interval. The cut is one cycle,+ `steps: 2` (the parent engine counted the cycle one step: on twos and threes it kept the search's cut unwritten, and+ on ones, a cycle a whole number of frames or not, cut two cycles, 35 and 37 frames)."""+ report = _cut(tmp_path / "out", _keyed(tmp_path, lambda k: _behind(k, cycle=cycle, hold=hold)))+ counted = _one_cycle(tmp_path / "out", cycle)+ assert report["drawings"]["hold"] == hold+ assert counted["cycles"]["asked"].startswith("the feet together") and counted["cycles"]["overlap"] > crossings.HIDE_SHARE+ assert counted["cycles"]["one"] < counted["cycles"]["half"]++[email protected]("cycle", [16, 18])+def test_a_diagonal_walk_whose_near_foot_steps_out_is_cut_one_cycle_from_its_view(tmp_path, cycle):+ """On a front diagonal the near foot steps out toward the camera and passes the far one apart: the feet meet on the+ screen once a cycle, and briefly — no pass hides. Given the view, the count asks the picture: the clip one interval+ on is the same picture, the legs as they were, and the view's foot cue does not turn over there. One cycle,+ `steps: 2` (the parent engine counted each meeting a step and cut two cycles, 32 and 36 frames). Without the view+ it is not asked, and cuts as before."""+ keyed = _keyed(tmp_path, lambda k: _outward(k, cycle=cycle))+ _cut(tmp_path / "view", keyed, "--view", "front_diagonal")+ counted = _one_cycle(tmp_path / "view", cycle)+ assert counted["cycles"]["overlap"] <= crossings.HIDE_SHARE and counted["cycles"]["asked"] == "the front_diagonal view, the legs side by side"+ assert counted["cycles"]["cue"]["one"] > local_cycle.CUE_SWAPPED+ plain = _cut(tmp_path / "plain", keyed)+ assert "cycles" not in plain["cycle"]["step_count"] and abs(plain["cycle"]["length"] - 2 * cycle) <= 1@pytest.mark.slow@@ -273,12 +324,25 @@ def test_a_side_walk_whose_two_steps_look_alike_is_cut_two_steps_however_near_a_"""The case the count was made for, guarded: from the side the two steps are one silhouette, the near leg and arma tone or a few apart from the far ones. The walk is slower than the window, so the search cuts one step, and atone tone the clip a step on draws nearer than the next frame (0.89 playback steps). Its feet pass briefly — no pass- can hide — so the count stands: two steps, a cycle long (as the parent engine cut it; asking the picture alone kept- the half step)."""- report = _cut(tmp_path / "out", _keyed(tmp_path, lambda k: _alike(k, cycle=46, phase=13, tone=tone, lean=lean)))+ can hide — and from the side the picture is not asked: the count stands, two steps, a cycle long."""+ keyed = _keyed(tmp_path, lambda k: _alike(k, cycle=46, phase=13, tone=tone, lean=lean))+ for out, extra in (("plain", ()), ("side", ("--view", "side"))):+ counted = _two_steps(_cut(tmp_path / out, keyed, *extra), 46)+ assert counted["search"]["verdict"] == "refuted" and counted["search"]["k"] == [1]+ assert "cycles" not in counted+++def test_a_diagonal_walk_whose_foot_cue_turns_over_a_step_on_is_cut_two_steps(tmp_path):+ """The same walker filmed as a front diagonal: its legs a step on are one silhouette, so the clip one interval on is+ as near as a cycle on, but its far leg is drawn a few tones off the near one, and the view's foot cue turns over one+ interval on — the other leg leads. The count stands: two steps, a cycle long."""+ report = _cut(tmp_path / "out", _keyed(tmp_path, lambda k: _alike(k, cycle=46, phase=13, tone=4, lean=1)),+ "--view", "front_diagonal")counted = _two_steps(report, 46)- assert counted["search"]["verdict"] == "refuted" and counted["search"]["k"] == [1]- assert "same_picture" not in counted["search"]+ said = counted["cycles"]+ assert said["cycles"] is False and said["one"] <= said["two"] + local_cycle.CYCLE_SLACK+ assert said["cue"]["one"] <= local_cycle.CUE_SWAPPED and "the other leg leads" in said["why"]@pytest.mark.slow@@ -374,15 +438,23 @@ def test_the_search_refuses_what_the_crossings_refute_and_names_their_count(unceassert "refute after the rest" in refused.value.diagnostics["order"]-def _choose(found: dict, *, period: int, seam: float, run: int = 9, search_seam: float = 1.0) -> tuple[dict, dict]:- """`by_steps` on a clip whose picture goes round every `period` frames, its feet passing every 15 (crossings at 8,- 23 … 68), seen together `run` frames at each pass (9: over half a step, a pass can hide there; 3: brief), with the- search's cut `found`: every two-step cut's seam reads `seam` at the gate, its top calm and its flow off 1.0 either- side, and the search's own cut `search_seam`."""- D = _distances(period=period, frames=FRAMES)+def _reading(run: int) -> crossings.Reading:+ """A clip whose feet meet every 15 frames (crossings at 8, 23 … 68), seen together `run` frames at each meeting+ (9: over half the interval, a pass can hide there; 3: brief)."""middles = (8, 23, 38, 53, 68)- reading = crossings.Reading(FRAMES, "gap", [(float(c), float(c)) for c in middles],- runs=[(c - run // 2, c + run // 2) for c in middles])+ return crossings.Reading(FRAMES, "gap", [(float(c), float(c)) for c in middles],+ runs=[(c - run // 2, c + run // 2) for c in middles])+++def _choose(found: dict, *, period: int, seam: float, run: int = 9, search_seam: float = 1.0, view: str | None = None,+ cue: list[float] | None = None) -> tuple[dict, dict]:+ """`by_steps` on a clip whose picture goes round every `period` frames and whose feet meet every 15 (`_reading`),+ its crossings read as `read_cycles` reads them from `view` and its foot `cue`, with the search's cut `found`: every+ two-step cut's seam reads `seam` at the gate, its top calm and its flow off 1.0 either side, and the search's own+ cut `search_seam`."""+ D = _distances(period=period, frames=FRAMES)+ reading = _reading(run)+ local_cycle.read_cycles(reading, D, view=view, cue=cue)return local_cycle.by_steps(D, np.zeros(FRAMES), reading, found=dict(found), refused=None, min_len=12, max_len=FRAMES,seam_flow=lambda s, L: {"off": [1.0, 1.0], "turn": [0.0, 0.0], "window": [[0, 0, 1, 1], [0, 0, 1, 1]]},@@ -412,26 +484,73 @@ def test_a_cut_the_count_does_not_refute_gives_way_only_to_a_two_step_cut_that_cdef test_a_cut_the_count_refutes_gives_way_to_two_steps_closing_or_not():"""A search's cut the count refutes, one step seen, is a fault of its own: the two-step cut is taken though its seam- fails the gate, and the gate says whether the loop passes."""+ fails the gate, and the gate says whether the loop passes. The picture goes round every 30 frames: one interval on+ it is half a cycle off, and the crossings mark steps."""picked, record = _choose({"start": 10, "length": 15}, period=30, seam=3.0)+ assert record["cycles"]["cycles"] is False and record["cycles"]["one"] > record["cycles"]["half"]assert record["search"]["verdict"] == "refuted" and record["search"]["k"] == [1]- assert record["search"]["same_picture"]["over_step"] > local_cycle.SAME_PICTURE_MAX- assert record["chosen_by"] == "two steps" and picked["steps"] == {"count": 2, "by": "crossings"}+ assert record["chosen_by"] == "two steps" and picked["steps"] == {"count": 2, "by": "crossings"} and abs(picked["length"] - 30) <= 1-def test_a_one_step_cut_that_is_the_same_picture_a_cut_on_is_the_searchs_cycle():- """The same count — one step — on a clip whose picture goes round every 15 frames: the frame a cut on is the- frame itself, so no legs were swapped and the count missed a crossing. The search's cut stands, no steps written."""+def test_where_a_pass_can_hide_and_the_picture_repeats_each_interval_the_crossings_mark_cycles():+ """The same meetings on a clip whose picture goes round every 15 frames, the feet together 9 frames at each: a pass+ can hide there, and one interval on the clip is the same picture as two on — the same leg leads. The crossings mark+ cycles, the step is half the interval, and the search's cut 10/15 is two steps joined at the walk's own point: it+ stands, `steps` written."""picked, record = _choose({"start": 10, "length": 15}, period=15, seam=1.0)- assert (picked["start"], picked["length"]) == (10, 15) and "steps" not in picked- assert record["chosen_by"] == "search" and record["cut"]["code"] == "same-picture" and record["cut"]["verdict"] == "uncertain"- assert record["search"]["same_picture"]["over_step"] <= local_cycle.SAME_PICTURE_MAX- assert record["search"]["same_picture"]["overlap"] > crossings.HIDE_SHARE---def test_where_the_feet_pass_briefly_the_count_stands_however_alike_a_step_on():- """The same clip, its feet seen together only at the moment they pass: no pass can hide, and a step on drawing as- near as the next frame is what legs drawn alike do from the side. The count stands: two steps."""- picked, record = _choose({"start": 10, "length": 15}, period=15, seam=1.0, run=3)- assert record["search"]["verdict"] == "refuted" and "same_picture" not in record["search"]- assert record["chosen_by"] == "two steps" and picked["steps"] == {"count": 2, "by": "crossings"}+ said = record["cycles"]+ assert said["cycles"] is True and said["asked"].startswith("the feet together") and said["one"] <= said["two"] + local_cycle.CYCLE_SLACK+ assert record["step_range"][1] == 7.5+ assert (picked["start"], picked["length"]) == (10, 15) and picked["steps"] == {"count": 2, "by": "crossings"}+ assert record["chosen_by"] == "search" and record["cut"]["verdict"] == "two"++[email protected]("view", [None, "side"])+def test_where_the_feet_meet_briefly_the_count_stands_from_the_side_or_no_view(view):+ """The same clip, its feet seen together only at the moment they meet: no pass can hide, and from the side (or with+ no view given) a step on drawing as near as a cycle on is what legs drawn alike do. Not asked: two steps."""+ picked, record = _choose({"start": 10, "length": 15}, period=15, seam=1.0, run=3, view=view)+ assert "cycles" not in record+ assert record["search"]["verdict"] == "refuted" and record["chosen_by"] == "two steps" and abs(picked["length"] - 30) <= 1++[email protected]("turns, cycles", [(True, False), (False, True)])+def test_from_a_diagonal_the_foot_cue_says_which_leg_leads_an_interval_on(turns, cycles):+ """The same brief meetings from a front diagonal: asked. One interval on is the same picture; where the view's foot+ cue turns over there (the near foot's shade leading one interval, the far one's the next) the other leg leads and+ the count stands, two steps of 15; where it does not, the crossings mark cycles and the search's 15 frames are the+ cycle."""+ t = np.arange(FRAMES)+ cue = list(np.sin(2 * np.pi * (t - 8) / (30 if turns else 15)))+ picked, record = _choose({"start": 10, "length": 15}, period=15, seam=1.0, run=3, view="front_diagonal", cue=cue)+ said = record["cycles"]+ assert said["asked"] == "the front_diagonal view, the legs side by side" and said["cycles"] is cycles+ assert (said["cue"]["one"] <= local_cycle.CUE_SWAPPED) is turns+ assert abs(picked["length"] - (15 if cycles else 30)) <= (0 if cycles else 1)++[email protected]("verdict, named", [("uncertain", True), ("two", False)])+def test_a_walk_that_starts_and_stops_in_the_take_is_named_to_film_again(verdict, named):+ """Feet together 15 frames at the head and 14 at the tail, longer than any pass the clip shows whole (8, 3): the+ walk stands still there. Where the cut kept is not two steps, no cut of two closes between the stands and the loop+ names the take to film again (`start-stop`), its stands, crossings and cut; a cut counted two steps is a walk+ looped, and nothing is named. Feet that only pass name nothing."""+ reading = crossings.Reading(FRAMES, "gap", [(10.0, 10.0), (20.0, 20.0), (40.5, 40.5)],+ runs=[(3, 17), (19, 21), (37, 44), (59, 72)], unconfirmed=[(59, 72)])+ assert reading.stands == [(3, 17), (59, 72)] and reading.run_limit == pytest.approx(8 * math.sqrt(2))+ record = reading.record()+ assert record["stands"] == [[3, 17], [59, 72]] and record["run_limit"] == round(8 * math.sqrt(2), 2)+ cut = {"verdict": verdict, "code": "tail-stall" if verdict == "uncertain" else "two", "why": "plays the clip's tail"}+ retake = loop.stand_retake({"start": 37, "length": 19, "step_count": {**record, "cut": cut}})+ if named:+ assert retake["reason"] == "start-stop" and retake["reasons"] == ["start-stop"] and retake["remedy"] == "retake"+ assert retake["start_stop"]["stands"] == [[3, 17], [59, 72]] and retake["start_stop"]["cut"] == [37, 19]+ assert retake["start_stop"]["code"] == "tail-stall"+ assert loop.retakes(None, retake) == retake+ assert loop.retakes({"reason": "part-pop", "reasons": ["part-pop"], "part_pop": {}, "remedy": "retake"}, retake)["reasons"] == \+ ["part-pop", "start-stop"]+ else:+ assert retake is None+ passing = _reading(3)+ assert passing.stands == [] and "stands" not in passing.record()+ assert loop.stand_retake({"start": 10, "length": 15, "step_count": {**passing.record(), "cut": {"verdict": "uncertain"}}}) is None