Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
feat(video-loop): a walk is cut two steps long wherever the clip shows its feet pass
Soohong Kim31cdd9533ecc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 87be07d..1ef5839 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,8 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the## Unreleased+- **Behavior change: `video-loop --anchor motion-auto` cuts a walk two steps long — the left foot forward once and the right once — wherever the clip shows its feet pass.** Left foot forward and right foot forward are nearly the same silhouette from the side or a diagonal, so the pixel search could take one step for a cycle (a half step loop: one foot goes forward), three steps where a tail on its own beat repeated there (the wrap puts the nearer foot back: a stomp in place), or refuse a slow walk whose cycle its window could not hold. The feet are now read (`crossings.read`): where they are seen apart, each run of frames with them together is a crossing; where they never are (front, back), the foot band's lean about the body's axis changing side is, and the lean must turn over a step on. Every crossing counted is one the clip shows whole: a run cut by the clip's first or last frame counts only where its twin confirms it, every step a cut plays — on both sides of its wrap — lies within √2 of the clip's own step, and a cut is two steps only when the walk's phase advances by two over it, its wrap joins two points of a step within [1/√2 − 1, √2 − 1] of each other under every bound of what the clip does not show, and the loop as played shows two crossings too (`two`; `refuted` one or three steps; anything else `uncertain`, never two). The search's cut is kept, every image as before, where it is a two within 1.5 frames of phase; otherwise the cut is the two-step cut in phase whose top band does not pop at the wrap, whose wrap is within the seam gate of its step and whose seam is the smoothest by the flow reading (both seam frames under `repair.FLOW_LIMIT`, within 0.5 of the smoothest, the wrap nearest the clip's own way on), read on the frames moved as the cut will be corrected, of any length the count allows inside an explicit `--min-len`/`--max-len` (`method: observed-two-steps-v1`); of the first four, the first whose seam the gate will pass, read as the gate reads it (`loop.seam_on_cells`), is taken. A window that holds no two steps of a walk whose steps are seen is refused, naming both (`no cut of two steps in --max-len 25: …`), never cut one step long. A clip whose feet are not read is cut exactly as before. The report records `cycle.step_count` (the crossings, the step range, the verdict of the cut taken and of the search's cut, `chosen_by`); a cut on two steps records `cycle.steps` `{count: 2, by: crossings}` and `strip.json` `steps: 2`, so `video-cycle-align` reads its half-way return as its step, and the step screen's pixel suspicion is settled (`pixel_suspect`). Where the clip shows its steps but no cut of two, the search runs again refusing the cuts the crossings refute, and a refusal lists each window's count, those refuted last. `--steps` is still the word on the search's cut. `repair.clip_flow_states` and `repair.ring_scores` read the flow of every cut of a clip on one path; `flow_scores` and the repair read as before ([loop-repair](docs/loop-repair.md) section 3, "The step count").+- **Tests** — `tests/video/test_crossings.py` (a walk that stalls proves no two steps across the stall, on either side of the wrap; a hold before or after the cut, a stall with the feet apart, a stand with them together, a stomp in place, the stance a clip opens on, a pass the first frame cuts with or without a twin that confirms it, a change the clip ends on: none two; half a cycle and three steps refuted, a wrap half a step off and a wrap that slips feet together in uncertain; noise at the threshold and a wobble at the axis no steps; a hold the step range absorbs stays two and a longer one does not; two crossings set no range; a lean that does not turn over is not read; every two lies in the lengths two steps cover; the lean and gap off drawn frames), `tests/video/test_walk_steps.py` (on synthetic walkers the pixel search alone cuts one step, one step past its window, three steps by the gait fallback, nothing at all, and across a stalled step: each is cut two steps long, in phase, the strip saying `steps: 2`; a walk the search already cuts two steps in phase is cut byte for byte as before; a legless body is cut as the search cuts it; a count given is the word; the set aligns a loop cut on two steps as one cycle; `detect` refuses what the crossings refute and orders a refusal by the count), the step screen's tests in `tests/video/test_one_step_cut.py` and the pixel search's in `tests/video/test_auto_motion.py`, `tests/video/test_loop_prop_seam.py` and `tests/video/test_loop_prop_seam_held.py` (a walker whose legs open and close once a drawing and never pass each other, which the count reads as one step a drawing) read their walker's feet as unseen (`tests/conftest.py`, `feet_unseen`), and `tests/video/test_explicit_window.py` refuses a `--max-len 25` that holds one step of the 42-frame walker.- **New: `video-loop --repair auto` (and `on`) eases a part that rushes on its way — the frames either side of the rush are made again at times that spread it, the body's own steps kept.** A part can keep its way and still jump: a tail that runs short of the cycle rushes on at the wrap, covering in one step what it covers in eight elsewhere, and each frame there lies near enough the line between its neighbours that the flow reading lets it pass, or takes the frame at the wrap out and leaves the rush over two steps. `repair.surges` reads the speed on the flow reading's own path and windows: a run of one or two steps whose mean step is at least 3.0 usual steps and 3.0 times the mean of the three steps either side, the part going on the way it came through it (a step that turns back is a frame flung, the flow repair's). After the flow groups, the worst rush is eased over three or four drawings either side, made from the frames as filmed (a frame the flow made inside is made again, `supersedes`) and kept between two frames as filmed, never leaving more than half the loop made with the rounds before it (as much as `video-loop-compare` reads back as the repair's): `repair.ease_times` gives every frame a time, on a grid of a twentieth of a step, where the part's step changes from one step to the next as little as it can — from the speed it came in with to the speed it goes on with — while the foot line's centre and the body's mass (`loop.foot_centre`, `loop.body_centre`) and the lowest solid row move in a step no further than the stretch's largest step as it played and half a pixel, and every other window of the flow reading no further than its own largest step there; within 2 % of that, the timing nearest the frames' own. How far the part has gone is the path of its coverage's centre in the windows that read the rush, which grows as far as the part moves where a blurred distance stops growing. RIFE makes each drawing between the frames as filmed either side of its time, one call a drawing, at most nine, outside the three of the flow groups; the stretch is taken only where no frame made has an interpolation fault, no body measure moves a pixel past the stretch's largest step, the part's largest step falls, no frame is left further off the flow and over its limit, no new rush appears in the rest of the body, and no window of the rest of the body steps further on the frames made than its own largest step over the stretch as it played (`rejected_for`, `the rest faster`: the search reads the rest of the body on the line between the frames as filmed, and the frames made, which go the body's own way between them, step further where a part moves far between frames). On the synthetic walker drawn over 24 frames a cycle, the tail a quarter short goes, after the flow repair, from 5.3 usual steps into the wrap to 3.4 with no rush left; over 16 frames, 15 % short and under the flow reading's limit, from 3.6 to 1.7; over 36 frames every stretch is refused, the rest of the body 1.5 % to 19 % past its own largest step on the frames made; ordinary walks and a flung frame read no rush. A loop with no rush costs one more reading and no call. `jump_repair` carries `surge`, `surge_after`, `ease_skipped`, `ease_calls` and the round `why: ease` (its `rest`: per window the rush is not read in, `step_max_before`, `step_max_after` and `faster`), `replaced` its frames, and the summary `eased`; without RIFE the rush is cut as filmed with a warning line, and `--repair on` refuses ([loop-repair](docs/loop-repair.md) section 2, "The eased retime").- **Tests** — `tests/video/test_loop_ease.py` (a tail that rushes on at the wrap after the flow repair is eased over three or four drawings either side, in play order, made only from frames as filmed — the flow's frame at the wrap made again — every frame outside as it was, the part's largest step down by a quarter or more and the body's feet, mass and ground within the stretch's own steps and a pixel, and every window of the rest of the body within its own largest step, read again on the loop as it plays; a rush under the flow reading's limit eased, none left; over 36 frames, the stretch whose frames made step further in the arm, the head and the legs than they did there refused for that alone, the loop as the flow left it; ordinary walks, drawn every frame and on twos, have no rush and nothing is made; a frame flung against the way is not a rush; on twos each drawing made once and shown on both its frames; a made frame pushed sideways refuses the stretch for drift, and one with its outline melted for a fault, the loop left as the flow left it; without an interpolator the rush named and nothing made; the same frames whichever way the body faces; a fourteen-frame loop eased three a side where four would leave more than half of it made; the search keeps every frame at its own time where the part moves evenly, and spreads a rush as far as the body's bound lets it; `video-loop` playing the frames made in a loop as long, a rush without RIFE cut as filmed with a warning line, `--repair on` without RIFE refused), and `tests/video/test_loop_flow.py`'s walker draws its dark parts whole on asking (`dark_whole`), so that a frame drawn between two phases has no more dark pixels than they have.- **Behavior change: a frame the jump repair or the cycle alignment makes between outlined drawings loses its outline only where it is lighter than its neighbours' edge rank by rank, too.** The fault `outline` read the made frame's edge against one dark line (a solid pixel under 70/255 within 2 px, `outline_loss` over 5 %), so art outlined in a mid tone — a brown or a painted line whose tone lies about 70/255 — had its line on the near side of the line in the drawings and on the far side wherever the flow softened it by a few tones: every frame made between two such drawings read as melted, and the repair and `--between auto` refused it. `rife.outline_shift(made, a, b)` reads the same edge, each pixel by how dark the darkest solid pixel within 2 px of it is, in order, against the lighter neighbour's edge at the same rank, and counts it where it is lighter by more than 50/255 (`rife.OUTLINE_SHIFT`). The fault `outline` now needs both over 5 %: a softened line is lighter by less at every rank and is kept, whatever tone the art outlines in; a line gone to the fill beside it is lighter by its whole contrast and is lost. Art outlined near-black reads the same on both, and art outlined lighter than 70/255 is still not judged by the outline. On the two-tone walker of the tests, the drawing between with its line 20 to 45 tones lighter reads `outline_loss` 57 % and `outline_shift` 0 (refused before, kept now); with its legs' line turned to fill, 24 % and 48 % (refused). A line less than 50/255 darker than the fill it melts into is not read as lost. The rank reading is read only between outlined drawings: `rife.outlined(frame)` is the share of a frame's edge whose line, the darkest solid pixel within 2 px, is darker than its fill, its colour from twice the bleed's depth inside (`rife.LINE_DEPTH`), by more than 50/255, and both neighbours must read at least 75 % (`rife.OUTLINED`); elsewhere `outline_shift` is `null` and the dark line judges alone, as before. Art painted without a line has no line to lose, and a part the flow melts there — a boot washed pale — can come out lighter by less than 50/255 at every rank: read rank by rank it would be kept and delivered, where refused it is replaced by the nearer filmed frame. On the walker of the tests painted without a line (outlined on 4 % of its edge), the drawing between with its near boot washed 40 tones lighter reads `outline_loss` 7.8 % and, rank by rank, 0: refused. The 75 % is set on frames made between drawn walks and judged by eye so that no frame seen as broken that the dark line alone refused is kept. The jump repair's proposals and the alignment's `smear` rows carry `outline_shift`, and the alignment's warning line names it where it was read; `video-loop-compare` and `video-loop-repair` keep their versioned measures, `rife.smear` alone, and judge the outline on the dark line as before ([loop-repair](docs/loop-repair.md) section 4).diff --git a/SKILL.md b/SKILL.mdindex 1312073..a66ab77 100644--- a/SKILL.md+++ b/SKILL.md@@ -148,4 +148,4 @@ Scene creation consumes finished assets and remains optional. Asset metadata own## Contracts and advanced tools-[run-contract](docs/run-contract.md) owns numeric requests, run layout, atomic publication and curated exports. [architecture](docs/architecture.md) explains domain ownership. [docs index](docs/README.md) lists every specialized feature and QA procedure. `sprite-gen --help` derives the command map from the package catalog. Never replace an engine stage — extraction, the loop cut, set alignment, loop repair — with a script of your own while presenting the result as a pipeline output. Where a stage's result is wrong, use the engine's own options first (another cut with `video-loop --max-len` or `--cycle fixed`, `video-cycle-align --length`, `--between auto` (the default: a made frame that melted or carries a ghost takes the nearer source frame, and a filmed ghost frame a clean one beside it; a made frame the report names as a possible cross-fade of two drawings, `look`, is kept — look at it, and where the legs show twice use `--between nearest` or film that direction again) or `--between nearest`, or `--cycles <loop>=<k>` once you have counted a suspect loop's strides, or `--foot <loop>=left|right` (`video-set --align-foot <item>=…`) once you have looked at the first strike frame of a loop the report lists under `unnamed_feet`), keep the engine's result as the comparison, report the defect against the engine, and name in the delivery each stage done by hand and why. A new clip is for what no stage can reach: the drawing, the motion itself, a clip that holds no whole cycle ([loop-review](docs/loop-review.md)) — and a clip the engine names for one: when the alignment report's `retake` lists a loop (reason `held-drawings`: the cycle cut from its clip shows each drawing for two or three frames, the set's length leaves it at under 13 drawings a second, and frames between its drawings could not be made, so the loop halts there; or `filmed-ghost`: a filmed ghost frame has filmed ghosts on both sides, so no clean frame stands there and the loop shows it — `reasons` lists both where both apply), run the engine verbs first as above, then film that direction again and align the set anew rather than hand-painting the gap; tell the user what the reason was and that a new take usually fixes it ([loop-repair](docs/loop-repair.md) section 4). `video-loop --anchor motion-auto` already cuts a walk two steps long — one cycle — where a staff held above the head closes only there (`cycle.steps`, `strip.json` `steps: 2`; `video-cycle-align` aligns it as the one cycle it is). When its report's `cycle.step_screen` says `suspect` (a slow walk cut one step long), or `video-cycle-align` stops on a loop under `one_step`, count the steps in the loop (how often each foot lands) and cut it again with `video-loop --steps 1` if it is one step (`--steps 2` if it is two); never stretch or double it by hand. When `video-loop` warns that the top of the silhouette jumps into the loop's first frame (a staff or flag held above the head, swinging on its own beat), or that the held part does not close at the wrap below its top, that part does not close at the cut: look at the loop, and try `--cycle fixed` with another cut before filming again; a walk refused for no cycle names in its report's `cycle.candidates` the windows it measured, best first, for a cut you must deliver anyway ([loop-repair](docs/loop-repair.md) section 3, "The seam pop" and "The held side").+[run-contract](docs/run-contract.md) owns numeric requests, run layout, atomic publication and curated exports. [architecture](docs/architecture.md) explains domain ownership. [docs index](docs/README.md) lists every specialized feature and QA procedure. `sprite-gen --help` derives the command map from the package catalog. Never replace an engine stage — extraction, the loop cut, set alignment, loop repair — with a script of your own while presenting the result as a pipeline output. Where a stage's result is wrong, use the engine's own options first (another cut with `video-loop --max-len` or `--cycle fixed`, `video-cycle-align --length`, `--between auto` (the default: a made frame that melted or carries a ghost takes the nearer source frame, and a filmed ghost frame a clean one beside it; a made frame the report names as a possible cross-fade of two drawings, `look`, is kept — look at it, and where the legs show twice use `--between nearest` or film that direction again) or `--between nearest`, or `--cycles <loop>=<k>` once you have counted a suspect loop's strides, or `--foot <loop>=left|right` (`video-set --align-foot <item>=…`) once you have looked at the first strike frame of a loop the report lists under `unnamed_feet`), keep the engine's result as the comparison, report the defect against the engine, and name in the delivery each stage done by hand and why. A new clip is for what no stage can reach: the drawing, the motion itself, a clip that holds no whole cycle ([loop-review](docs/loop-review.md)) — and a clip the engine names for one: when the alignment report's `retake` lists a loop (reason `held-drawings`: the cycle cut from its clip shows each drawing for two or three frames, the set's length leaves it at under 13 drawings a second, and frames between its drawings could not be made, so the loop halts there; or `filmed-ghost`: a filmed ghost frame has filmed ghosts on both sides, so no clean frame stands there and the loop shows it — `reasons` lists both where both apply), run the engine verbs first as above, then film that direction again and align the set anew rather than hand-painting the gap; tell the user what the reason was and that a new take usually fixes it ([loop-repair](docs/loop-repair.md) section 4). `video-loop --anchor motion-auto` already cuts a walk two steps long — one cycle — where a staff held above the head closes only there (`cycle.steps`, `strip.json` `steps: 2`; `video-cycle-align` aligns it as the one cycle it is). Where the clip shows its feet pass, it counts the steps on those crossings and cuts two of them, joined at the walk's own point (`cycle.step_count`, `steps: 2`, [loop-repair](docs/loop-repair.md) section 3, "The step count"). When its report's `cycle.step_screen` says `suspect` (a slow walk cut one step long, its feet not read), or `video-cycle-align` stops on a loop under `one_step`, count the steps in the loop (how often each foot lands) and cut it again with `video-loop --steps 1` if it is one step (`--steps 2` if it is two); never stretch or double it by hand. When `video-loop` warns that the top of the silhouette jumps into the loop's first frame (a staff or flag held above the head, swinging on its own beat), or that the held part does not close at the wrap below its top, that part does not close at the cut: look at the loop, and try `--cycle fixed` with another cut before filming again; a walk refused for no cycle names in its report's `cycle.candidates` the windows it measured, best first, for a cut you must deliver anyway ([loop-repair](docs/loop-repair.md) section 3, "The seam pop" and "The held side").diff --git a/docs/loop-repair.md b/docs/loop-repair.mdindex 38816b6..9577c20 100644--- a/docs/loop-repair.md+++ b/docs/loop-repair.md@@ -748,6 +748,85 @@ closes: the top band's cut stands, and it is warned about.(below). `--cycle fixed` cuts any window ([loop review](loop-review.md)); a two-step cut made thatway carries no `steps`, and the set alignment asks for its count.+### The step count — two steps, read off the clip's crossings++A walk cycle is two steps: the left foot forward once and the right once. Seen from the side or a+diagonal, left foot forward and right foot forward are nearly the same silhouette, so a cut chosen by+how its shape matches at the wrap can be one step (a half step loop: one foot goes forward) or three+(the wrap puts the nearer foot back: a stomp in place), and a walk whose cycle the search window cannot+hold, or whose tail repeats on its own beat, is cut one step long or not at all. Pixels cannot count+the steps. The feet can: each step they pass each other once, a **crossing**, and a cut that covers two+crossings, joined at the wrap where the walk itself goes on, is one cycle (`crossings.py`).++`--anchor motion-auto` reads the crossings of the frames it searched and records them in the report+(`cycle.step_count`), whatever it cuts:++| Field | What |+|---|---|+| `mode` | `gap`: the feet are seen apart (the foot band's widest gap, `legs.FEET_APART`, in at least a fifth of the frames: side and diagonal views); `sign`: they are not, and the foot band's lean about the body's axis says which foot is nearer (front and back views) |+| `crossings` | where the feet pass, in the search's frames (`read_from`: after a lead-in); a pair is a crossing whose middle the clip bounds but does not show |+| `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` |+| `chosen_by` | `search` (kept), `two steps` (chosen on the count), and the search again where the count refutes its cut (`searched_again`) |++**Counting a cut.** Every crossing counted is one the clip shows whole. A cut s/L plays frames s to+s+L−1 and then frame s again where the clip itself plays frame s+L; the wrap joins two frames the clip+never filmed side by side, so nothing the loop shows across it counts as a step. Every step the cut+plays, on both sides of the wrap, lies in the step range (a stall, a stand with the feet together, a+stomp fail it: `step-long`, `step-short`, `stand`, `head-stall`, `tail-stall`); the walk's phase+(crossings so far, plus how far into the step) advances by k steps over the cut, and the wrap joins two+points of a step that far apart, which must lie within [1/√2 − 1, √2 − 1] of a step (`seam`). What the+clip does not show — a bounded crossing's middle, an open step's other end — is tried across its bound,+and the verdict is the one every value gives (`bounds`, `open-count`). A **two** is k = 2 that way,+with the loop as played showing exactly two crossings as well (`ring`); **refuted** is k steps, each+seen (`one step`, `three steps`); anything else is **uncertain** and never taken as two. `phase` is how+far the wrap is from joining the same point of the walk, in frames, the worst over the bounds.++**Choosing the cut.**++- The clip does not show its steps (no feet seen, a legless body, a lean that does not turn over, under+ three 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, every+ image and frame as the search alone cuts it.+- 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 gait+ fallback's ceiling (a walk slower than the window is cut two steps long). Those in phase, if any, are+ read at the wrap: the flow off of the cut's last and first frames (section 2, "The flow reading", on+ the clip's own path and box, its frames moved as the cut will be corrected, read once:+ `repair.clip_flow_states`, `repair.ring_scores`), the top band's jump (`repair.seam_pop`, "The seam+ pop" below) and the wrap over the cut's step (`ratio`, what the seam gate holds a loop to). The cuts in+ phase whose top does not pop, whose `ratio` is at most the seam gate's **2.0** (`--seam-max`) and whose+ two seam frames are both under **3.0** (`repair.FLOW_LIMIT`), the worse within **0.5** of the smoothest+ such cut's (`local_cycle.SEAM_FLOW_BAND`), are taken nearest the clip's own way on at the wrap+ (`closure`, as for a counted cut); where none passes, in phase first, then a calm top, then the flow+ limit, then the seam gate, then the smoothest seam (`method: observed-two-steps-v1`, `cycle.candidates`+ ranked, `review_recommended` when none passed). Of the first four (`local_cycle.SEAM_TRIES`) the first+ whose seam the gate will pass is taken, read as the gate reads it before anything is cut+ (`loop.seam_on_cells`: the cut corrected as it will be, its wrap over its step on the analysis+ thumbnail; `step_count.seam_gate.tried`): the correction of one cut can leave a jump at its wrap that+ no reading of the clip shows. A part on a beat of its own — a tail, a staff — that closes on no cut of+ two steps leaves every one with a wrap that jumps: the first is cut, still two steps, and the seam gate+ says whether it closes, as for any cut.+ The pixel search's repeat rule is not asked: a part off the legs' beat — a tail on its own beat —+ repeats on its own, and its seam is the flow repair's (section 2). `step_count.repeat` records the+ search's word on the cut, and a cut it would refuse, or one that passed no gate, is a warning line.+- The clip shows its steps but no cut of two: the search's cut, unless the count refutes it — then the+ search runs again refusing what the crossings refute, and a search that finds nothing lists each+ refused window's count (`cycle.candidates[].step_count`), those the crossings refute last.++A cut taken on two steps records `cycle.steps` (`{"count": 2, "by": "crossings"}`) and `strip.json`+says `steps: 2`: `video-cycle-align` reads its return half way as the step it is (section 4). The step+screen below then has its word only where the count does not: its pixel suspicion is kept as+`pixel_suspect`, `suspect` false. A count given (`--steps`) is the word on the search's cut, and the+crossings are not asked.++**What crossings cannot see**: a hold the step range absorbs (a 13-frame step held to 17), a still run of+the 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. Four-legged gaits are read as one foot band (`legs.strike_signals`), as before.+### The step screen — a slow walk cut one step longThe walk window is 0.5 to 1.6 s, and at most half the clip: a cycle has to be seen repeating. A@@ -758,6 +837,8 @@ directions play two, and nothing said so: the two-cycle screen looks only belowfundamental period", [video pipeline](video-pipeline.md) section 4), and the gait fallback's longerwindow runs only when the first search finds nothing.+Where the clip shows its steps the count above settles it, and a walk slower than the window is cut two+steps long. Where it does not (the feet hidden, a lean that does not turn over),`--anchor motion-auto` screens the cut it takes the other way, over the whole clip rather than thewindow (`cycle.step_screen`, `period.step_screen`):@@ -779,9 +860,10 @@ by eye, or a vision call). Its images, `strip.json`, warnings and stderr are whait; the report's `cycle`, and the summary `video-loop` prints, gain `step_screen`. A twice-the-cutlag past the clip (fewer than 4 pairs) is not read: `lag` null, not a suspect. The synthetic walkerof `tests/video/test_one_step_cut.py` — a 42-frame cycle, legs drawn alike and arms shaded apart, 73-frames — is cut at 21 (`ratio` 0.48, a suspect); the same drawing on a 25-frame cycle is cut at 25-(`ratio` 1.53), and on 23.5 frames at 24 (`ratio` 0.66: a suspect that is a cycle), each written-exactly as with no screen at all.+frames, its feet read as unseen — is cut at 21 (`ratio` 0.48, a suspect); the same drawing on a+25-frame cycle is cut at 25 (`ratio` 1.53), and on 23.5 frames at 24 (`ratio` 0.66: a suspect that is a+cycle), each written exactly as with no screen at all. With its feet read, the 42-frame walker is cut+two steps long, 42 frames, on the count.**`video-loop --steps 1|2`** is the count coming back, with `--anchor motion-auto`: how many stepsthe cut it takes without `--steps` holds.diff --git a/docs/loop-review.md b/docs/loop-review.mdindex 16fb61a..17261b0 100644--- a/docs/loop-review.md+++ b/docs/loop-review.md@@ -114,12 +114,15 @@ sets a length (the count of steps and the one-shot failover below included), andfails ([loop repair](loop-repair.md) section 3, "The step screen"). Without one, onlythe gait fallback below looks past the state's window, and only after this search found nothing.-A walk slower than the window can hold — its legs drawn alike — is found one step long, and the-search has nothing to refuse it on: the step repeats. So the cut is screened the other way, over-the whole clip (`cycle.step_screen`): where twice it repeats better than it, the report names it a-suspect and nothing else changes. Look at the loop and count its steps (how often each foot lands);-`video-loop --steps 1` cuts it again two of its lengths long, `--steps 2` keeps it and says so-([loop repair](loop-repair.md) section 3, "The step screen").+A walk whose two steps look alike — its legs drawn alike, from the side or a diagonal — can be found+one 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 is+two 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"). Where it+does not, the cut is screened the other way, over the whole clip (`cycle.step_screen`): where twice it+repeats better than it, the report names it a suspect and nothing else changes. Look at the loop and+count its steps (how often each foot lands); `video-loop --steps 1` cuts it again two of its lengths+long, `--steps 2` keeps it and says so ([loop repair](loop-repair.md) section 3, "The step screen").### The gait fallback: a slow walk, or a walk toward the cameradiff --git a/docs/video-pipeline.md b/docs/video-pipeline.mdindex 592db38..716876c 100644--- a/docs/video-pipeline.md+++ b/docs/video-pipeline.md@@ -761,9 +761,11 @@ was 17). `video-loop` therefore:reports that jump and warns on it ([loop repair](loop-repair.md) section 3,"The seam pop"). Once the top jumps, the held part is read below its top too, and a staffthat closes only on two steps is cut two steps long — one cycle (`cycle.steps`, "The held- side"). The cut taken is screened for one step of a cycle twice as long, over the whole clip- (`cycle.step_screen`, "The step screen"); nothing is cut on it, and `--steps` is the count- that cuts again.+ side"). Where the clip shows its steps, the cut is two of them — read off the crossings of the+ feet, joined at the walk's own point, the smoothest seam first — and the search's cut is kept+ where it already is that (`cycle.step_count`, "The step count"). Where it does not, the cut taken+ is screened for one step of a cycle twice as long, over the whole clip (`cycle.step_screen`, "The+ step screen"); nothing is cut on it, and `--steps` is the count that cuts again.This neighbourhood check measures temporal consistency, not anatomical legidentity. A consistently repeated malformed motion can still score well; visual@@ -840,8 +842,9 @@ swings the stride twice a step; a diagonal view's two steps open the feet unequathe set stage: `video-cycle-align` screens every loop by the same rule, stops a set on a suspect,and takes one cycle out of a loop only when told how many it holds (`--cycles`, [looprepair](loop-repair.md) section 4). The local search of `--anchor motion-auto` records the same. A-loop whose steps are known (`steps: 2` in `strip.json`: cut two steps long so a held part closes, or-cut again on a count with `video-loop --steps`) returns half way at its second step; the set stage+loop whose steps are known (`steps: 2` in `strip.json`: cut two steps long on the clip's crossings or+so a held part closes, or cut again on a count with `video-loop --steps`) returns half way at its+second step; the set stagereads that return as the step it is, not a second cycle. The screen also looks the other way there:a cut that may be one step of a cycle twice as long (`cycle.step_screen`, read over the whole clip)stops the set the same way, and only a count — `video-loop --steps 1` — cuts it again.diff --git a/sprite_gen/video/crossings.py b/sprite_gen/video/crossings.pynew file mode 100644index 0000000..dd86745--- /dev/null+++ b/sprite_gen/video/crossings.py@@ -0,0 +1,405 @@+# SPDX-License-Identifier: Apache-2.0+"""How many steps a walk's cut covers, read only from the steps the clip itself shows (docs/loop-repair.md+section 3, "The step count").++A walk cycle is two steps: the left foot forward once and the right once. Seen from the side or a diagonal, left+foot forward and right foot forward are nearly the same silhouette, so a cut that matches its shape at the wrap can+be one step (a half step loop: one foot goes forward), or three, the wrap putting the near foot back (a stomp in+place). Pixels cannot count them. The feet can: each step the feet pass each other once, a **crossing**, and a cut+that covers two crossings, joined at the wrap where the walk itself goes on, is one cycle.++Every crossing counted is one the clip shows whole. A cut s/L plays frames s..s+L-1 and then frame s again where+the clip itself plays frame e = s+L; the wrap joins two frames the clip never filmed side by side, so nothing the+loop shows across it is evidence. The loop as played only has to agree.++Reading the crossings (`read`):++- **gap** (the feet are seen apart in at least `legs.FEET_APART_SHARE` of the frames: side, diagonals): the foot+ band's widest gap (`legs.strike_signals`). The feet are together under `legs.FEET_APART` of the body's height+ and apart again only at APART_AGAIN times it; a run of frames together with apart frames on both sides is a+ crossing, at its middle.+- **sign** (front, back: the feet are never seen apart): which side of the body's axis the foot band leans+ (`foot_signals`). The side changes only when the lean reaches SIDE_SWING of its swing past the axis on the other+ side; the crossing is where it last crossed the axis. The lean must alternate a step apart (its correlation one+ step on at most ALTERNATION_MAX), else it is not feet and the clip is not read.+- A run cut by the clip's first or last frame is partial: it may be the stance the clip starts from. It is a+ crossing only where its twin (the run two runs away, the same foot's pass) is whole, at least as long as the part+ seen, and the part seen moves like the twin's matching part; its middle is then bounded by the twin's length.+ Frames no reading confirms (an unconfirmed partial run; in sign mode the frames before the first side and after a+ last change the clip ends before confirming) make every cut that plays them uncertain.++Judging a cut (`Reading.judge`): the clip's steps (between consecutive crossings) set the step range, their median+m within a factor of sqrt 2 each way. Every step the cut plays, on both sides of the wrap, lies in it (a stall, a+stomp or a stand fails it). The walk's phase phi (crossings so far, plus how far into the step) advances+A = phi(e) - phi(s) over the cut; k = round(A) steps, and the wrap joins two points of a step delta = A - k apart,+which must lie in [1/sqrt2 - 1, sqrt2 - 1]. A `two` is k = 2 under every bound of what the clip does not show, with+the loop as played showing exactly two crossings as well; `refuted` is k steps, each seen (`one step`,+`three steps`); everything else is `uncertain`, never taken as two. `phase` is delta in frames (delta x m), the+worst over the bounds: how far the wrap is from joining the same point of the walk.++What crossings cannot see: a hold the step range absorbs (a 13-frame step held to 17), a still run of the feet+together as long as a pass, a wobble that reaches the reading's sides at a step's beat. They read as steps.+"""++from __future__ import annotations++import itertools+import math+from typing import Any++from PIL import Image++from sprite_gen._deps import np+from sprite_gen.video import legs as legs_mod++AXIS_PART = 0.4 # the body's axis: the middle of the solid pixels of its top 40 % (head and torso)+FOOT_TOP = 0.88 # the foot band the sides are read on: from 88 % of the body's height down (its lowest 12 %)+MERGE = 3 # sign mode: a side held fewer frames than this is the side before it+SIDE_SWING = 0.1 # sign mode: of the lean's swing (P90 - P10), past the axis, before a side is seen+APART_AGAIN = 1.5 # gap mode: x FEET_APART before feet seen together are seen apart again+ALTERNATION_MAX = -0.7 # sign mode: the lean's correlation one step on, at most: feet stepping turn it over+ROOT2 = math.sqrt(2.0)+SEAM_BAND = (1 / ROOT2 - 1, ROOT2 - 1) # the wrap's delta: its step within the step range of the steps it joins+OPEN_SAMPLES = 9 # values an open step's unseen end is tried at, across its bound+PARTIAL_SAMPLES = 3 # values a partial crossing's middle is tried at, across its bound+PHASE_TOLERANCE = 1.5 # frames: crossings are read to half a frame, a cut's length to one+EPS = 1e-9+++def foot_signals(frames: list[Image.Image], gap: list[float] | None = None) -> dict[str, list[float]]:+ """Per frame: `gap`, the foot band's widest gap (`legs.strike_signals`, or as given); `lean`, the foot band's+ solid pixels left of the body's axis less those right of it, over both; `mass`, both, over the body's height+ squared. Raises ValueError where a frame has no solid body."""+ gap = legs_mod.strike_signals(frames)["gap"] if gap is None else gap+ lean, mass = [], []+ for frame in frames:+ solid = np.asarray(frame.getchannel("A")) >= legs_mod.LOW_ALPHA+ rows = np.nonzero(solid.any(axis=1))[0]+ if rows.size == 0:+ raise ValueError("a loop frame has no solid body")+ y0, y1 = int(rows[0]), int(rows[-1])+ height = y1 - y0 + 1+ xs = np.nonzero(solid[y0:y0 + max(1, int(AXIS_PART * height))])[1]+ axis = float(xs.mean())+ band = solid[y0 + int(FOOT_TOP * height):y1 + 1]+ left = band & (np.arange(solid.shape[1])[None, :] < axis)+ side_l, side_r = float(left.sum()) / height / height, float((band & ~left).sum()) / height / height+ lean.append((side_l - side_r) / max(side_l + side_r, 1e-9))+ mass.append(side_l + side_r)+ return {"gap": [float(g) for g in gap], "lean": lean, "mass": mass}+++def _smooth(v: Any) -> np.ndarray:+ v = np.asarray(v, dtype=float)+ return np.convolve(np.pad(v, 1, mode="edge"), [.25, .5, .25], mode="valid")+++def _merge_short(sides: np.ndarray) -> np.ndarray:+ """Sides held fewer than MERGE frames go to the side before them (the reading's noise filter)."""+ sides = sides.copy()+ k = 0+ while k < len(sides):+ j = k+ while j + 1 < len(sides) and sides[j + 1] == sides[k]:+ j += 1+ if j - k + 1 < MERGE and k > 0 and sides[k] != 0:+ sides[k:j + 1] = sides[k - 1]+ k = j + 1+ return sides+++def _sides(lean: list[float]) -> tuple[np.ndarray, int | None]:+ """+1/-1 a frame once a side is seen (0 before), and the frame from which the clip's end leaves a change+ unconfirmed (or None)."""+ v = _smooth(lean)+ v = v - np.median(v)+ reach = SIDE_SWING * float(np.percentile(v, 90) - np.percentile(v, 10))+ sides = np.zeros(len(v), dtype=int)+ side, axis = 0, 0+ for t in range(len(v)):+ if t > 0 and np.sign(v[t]) != np.sign(v[t - 1]):+ axis = t+ if side == 0 and abs(v[t]) >= reach:+ side = 1 if v[t] > 0 else -1+ elif side != 0 and -side * v[t] >= reach:+ side = -side+ sides[axis:t] = side+ sides[t] = side+ sides = _merge_short(sides)+ pending = axis if side != 0 and axis > 0 and np.sign(v[axis]) == -side and np.all(-side * v[axis:] < reach) else None+ return sides, pending+++def _together(gap: list[float]) -> list[bool]:+ out, together = [], None+ for g in gap:+ if together is None:+ together = g < legs_mod.FEET_APART+ elif together and g >= APART_AGAIN * legs_mod.FEET_APART:+ together = False+ elif not together and g < legs_mod.FEET_APART:+ together = True+ out.append(bool(together))+ return out+++def _runs(flags: list[bool]) -> list[tuple[int, int]]:+ out, k, n = [], 0, len(flags)+ while k < n:+ if flags[k]:+ j = k+ while j + 1 < n and flags[j + 1]:+ j += 1+ out.append((k, j))+ k = j + 1+ else:+ k += 1+ return out+++def _motion(sig: dict[str, list[float]], a: int, b: int) -> float | None:+ """How much the foot band moves a frame over frames a..b, in swings of its mass and lean: a pass moves, a stance+ does not. None where it cannot be read."""+ if b <= a:+ return None+ total = 0.0+ for key in ("mass", "lean"):+ v = np.asarray(sig[key], dtype=float)+ swing = float(np.percentile(v, 90) - np.percentile(v, 10))+ if swing <= 0:+ return None+ total += float(np.mean(np.abs(np.diff(v[a:b + 1])))) / swing+ return total+++def _moves_like(sig: dict[str, list[float]], part: tuple[int, int], twin: tuple[int, int]) -> bool:+ m, t = _motion(sig, *part), _motion(sig, *twin)+ return m is not None and t is not None and t > 0 and m >= t / ROOT2+++def _phi(c: list[float], t: float) -> float:+ i = int(np.searchsorted(c, t, side="right")) - 1+ i = min(max(i, 0), len(c) - 2)+ return i + (t - c[i]) / (c[i + 1] - c[i])+++class Reading:+ """What the clip shows of its steps: `mode`, the crossings (each (lo, hi): a whole one has lo == hi), the frames+ no reading confirms, the frame states the loop as played is read on, and whether it reads at all (`readable`,+ `why`)."""++ def __init__(self, n: int, mode: str, crossings: list[tuple[float, float]], *, head_limit: float = -0.5,+ tail_limit: float | None = None, runs: list[tuple[int, int]] | None = None, together: list[bool] | None = None,+ sides: list[int] | None = None, unconfirmed: list[tuple[int, int]] | None = None, why: str | None = None):+ self.n, self.mode = n, mode+ self.crossings = sorted(crossings)+ self.head_limit = head_limit # an unseen crossing before the first lies at or before this+ self.tail_limit = n - 0.5 if tail_limit is None else tail_limit # ... after the last, at or after this+ self.runs = runs or []+ self.together, self.sides = together, sides+ self.unconfirmed = unconfirmed or []+ 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 None+ middles = [(lo + hi) / 2 for lo, hi in self.crossings]+ self.step = float(np.median(np.diff(middles))) if len(middles) >= 3 else None+ self.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+ f"{len(middles)} crossing{'s' if len(middles) != 1 else ''} in the clip: under two steps, no step range")++ @property+ def readable(self) -> bool:+ return self.why is None++ def record(self) -> dict[str, Any]:+ """The reading as the report keeps it."""+ out: dict[str, Any] = {"method": "observed-crossings-v1", "mode": self.mode, "readable": self.readable,+ "crossings": [round(lo, 2) if hi - lo < EPS else [round(lo, 2), round(hi, 2)] for lo, hi in self.crossings],+ "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.alternation is not None:+ out["alternation"] = self.alternation+ if self.why is not None:+ out["why"] = self.why+ return out++ def scenarios(self):+ """Crossing position lists, each bounded crossing at its low end, middle and high end."""+ choices = [[lo] if hi - lo < EPS else list(np.linspace(lo, hi, PARTIAL_SAMPLES)) for lo, hi in self.crossings]+ for pick in itertools.product(*choices):+ 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."""+ 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)+ if self.together is None:+ return None+ t = list(self.together[s:s + L])+ if all(t) or not any(t):+ return 0+ r = t.index(False)+ return 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)."""+ e, last = s + L, s + L - 1+ if len(c) < 3:+ return "uncertain", "no-range", "under two steps in the clip: no step range", [], [], None+ m = float(np.median(np.diff(c)))+ lo, hi = m / ROOT2, m * ROOT2++ def played(a: float, b: float) -> bool:+ return max(math.floor(a) + 1, s) <= min(math.ceil(b) - 1, last)++ 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+ head_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+ if 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+ bad = [(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)+ 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]+ 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+ heads = np.linspace(*before, OPEN_SAMPLES) if head_played else [None]+ if e <= c[-1]:+ tails: Any = [None]+ elif tail_played:+ tails = np.linspace(*after, OPEN_SAMPLES)+ else: # frame e alone lies past the last crossing, unplayed: any step the clip allows+ tails = np.linspace(c[-1] + max(lo, self.tail_limit - c[-1]), c[-1] + 10 * hi, OPEN_SAMPLES)+ ks, deltas = set(), []+ 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)+ 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+ k = 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)+ if k == 0:+ return "uncertain", "no-step", "under half a step: no crossing", [k], deltas, m+ if 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++ def 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+ wrap's `delta` (its least and largest over the bounds), `phase` (the worst delta, in frames) and the+ crossings the loop as played shows (`ring`)."""+ rec: dict[str, Any] = {"cut": [s, L]}+ if not self.readable:+ return {**rec, "verdict": "uncertain", "code": "unread", "why": self.why}+ outs = [self._scenario(c, s, L) for c in self.scenarios()]+ verdicts = {o[0] for o in outs}+ ks = sorted({k for o in outs for k in o[3]})+ deltas = [d for o in outs for d in o[4]]+ ms = [o[5] for o in outs if o[5] is not None]+ worst = max(deltas, key=abs) if deltas else None+ rec.update(k=ks, delta=[round(float(min(deltas)), 3), round(float(max(deltas)), 3)] if deltas else None,+ phase=round(float(worst) * float(np.median(ms)), 1) if worst is not None and ms else None, ring=self.ring_count(s, L))+ if len(verdicts) > 1 or (verdicts == {"refuted"} and len(ks) > 1):+ whys = "; ".join(sorted({f"{o[0]}: {o[2]}" for o in outs}))+ return {**rec, "verdict": "uncertain", "code": "bounds", "why": f"what the clip does not show leaves it open: {whys}"}+ verdict, code, why = outs[0][0], outs[0][1], outs[0][2]+ if verdict == "two" and rec["ring"] is not None and rec["ring"] != 2:+ return {**rec, "verdict": "uncertain", "code": "ring",+ "why": f"two steps in the clip, but the loop shows {rec['ring']} crossings: the wrap adds or hides one"}+ return {**rec, "verdict": verdict, "code": code, "why": why}++ def in_phase(self, judged: dict[str, Any]) -> bool:+ """A two whose wrap joins the same point of the walk, within PHASE_TOLERANCE frames."""+ return judged["verdict"] == "two" and judged.get("phase") is not None and abs(judged["phase"]) <= PHASE_TOLERANCE++ def lengths(self, lo: int, hi: int) -> range:+ """The cut lengths in [lo, hi] that can cover two steps: two steps in the step range, the wrap's delta in its band."""+ if self.step is None:+ return range(0)+ return range(max(lo, math.floor((2 + SEAM_BAND[0]) * self.step / ROOT2)), min(hi, self.n, math.ceil((2 + SEAM_BAND[1]) * self.step * ROOT2)) + 1)++ def twos(self, lo: int, hi: int) -> list[dict[str, Any]]:+ """Every cut [lo, hi] frames long that covers two steps (`judge`), by length then start."""+ out = []+ for L in self.lengths(lo, hi):+ for s in range(self.n - L + 1):+ judged = self.judge(s, L)+ if judged["verdict"] == "two":+ out.append(judged)+ return out+++def read(sig: dict[str, list[float]]) -> Reading:+ """The crossings of the clip whose `foot_signals` are `sig`."""+ gap = sig["gap"]+ n = len(gap)+ if float(np.mean([g >= legs_mod.FEET_APART for g in gap])) >= legs_mod.FEET_APART_SHARE:+ together = _together(gap)+ runs = _runs(together)+ if not runs or any(a == 0 and b == n - 1 for a, b in runs):+ return Reading(n, "gap", [], runs=runs, together=together)+ crossings, head_limit, tail_limit, unconfirmed = [], -0.5, None, []+ for i, (a, b) in enumerate(runs):+ if a > 0 and b < n - 1:+ crossings.append(((a + b) / 2, (a + b) / 2))+ continue+ twin = runs[i + 2] if a == 0 and i + 2 < len(runs) else runs[i - 2] if b == n - 1 and i >= 2 else None+ seen = twin[1] - twin[0] + 1 if twin is not None and twin[0] > 0 and twin[1] < n - 1 else 0+ if a == 0 and seen >= b + 1 and _moves_like(sig, (0, b), (twin[1] - b, twin[1])):+ crossings.append(((2 * b + 1 - seen) / 2, b / 2))+ elif a == 0:+ head_limit = b / 2+ unconfirmed.append((a, b))+ elif seen >= n - a and _moves_like(sig, (a, n - 1), (twin[0], twin[0] + n - 1 - a)):+ crossings.append(((a + n - 1) / 2, (2 * a + seen - 1) / 2))+ else:+ tail_limit = (a + n - 1) / 2+ unconfirmed.append((a, b))+ return Reading(n, "gap", crossings, head_limit=head_limit, tail_limit=tail_limit, runs=runs, together=together,+ unconfirmed=unconfirmed)+ sides, pending = _sides(sig["lean"])+ unseen = int(np.argmax(sides != 0)) if np.any(sides != 0) else n+ crossings = [(k - .5, k - .5) for k in range(max(1, unseen + 1), n) if sides[k] != sides[k - 1]]+ unconfirmed = ([(0, unseen - 1)] if unseen > 0 else []) + ([(pending, n - 1)] if pending is not None else [])+ reading = Reading(n, "sign", crossings, head_limit=max(-0.5, unseen - 0.5), tail_limit=None if pending is None else pending - 0.5,+ 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)+ 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 "+ f"{reading.step:g} frames, over {ALTERNATION_MAX:+.2f}): not feet stepping" if alternation is not None+ else "the foot band's lean does not move")+ 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)+ 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)}):+ a, b = x[:-lag], x[lag:]+ if lag < 1 or len(a) < 3 or a.std() < 1e-12 or b.std() < 1e-12:+ return None+ out.append(float(np.corrcoef(a, b)[0, 1]))+ return max(out)diff --git a/sprite_gen/video/local_cycle.py b/sprite_gen/video/local_cycle.pyindex add854d..542d068 100644--- a/sprite_gen/video/local_cycle.py+++ b/sprite_gen/video/local_cycle.py@@ -9,7 +9,10 @@ recorded (`fundamental`, sprite_gen/video/period.py), never cut shorter; thelegs are read off `signals` (`legs.strike_signals` of the analysed frames).The cut taken is screened the other way too, for one step of a cycle twice aslong that the window could not hold (`step_screen`), never cut longer on it:-only a count of the steps (`video-loop --steps`) cuts again.+only a count of the steps cuts again — given (`video-loop --steps`), or read off+the clip's own crossings (`by_steps`, sprite_gen/video/crossings.py): where the+clip shows its steps, the cut is two of them, joined at the walk's own point,+the smoothest seam first."""from __future__ import annotationsimport math@@ -17,6 +20,11 @@ from sprite_gen._deps import npfrom sprite_gen.video import period as period_modREFUSED_SHOWN = 12 # refused windows a failed search reports, as many as a found cycle's candidates+# A two-step cut's seam is as smooth as the smoothest in-phase one's within this much more flow off (`_rank`): about+# what an ordinary frame of a walk lies off the line between its neighbours, in its window's usual steps.+SEAM_FLOW_BAND = 0.5+REPEAT_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`)def _around(start, length):@@ -231,9 +239,32 @@ def counted(distances, trajectory, *, min_len, max_len, periodicity_min, signalsperiodicity_min=periodicity_min, signals=signals)}+def _screens(distances, chosen, *, lo, hi, gait_floor, periodicity_min, signals):+ """The cut's two screens, as `detect` records them: below it for two or three cycles (`fundamental`,+ period.screen on the local profile about it) and above it for one step of a cycle twice as long+ (`step_screen`, period.step_screen over the whole clip)."""+ radius, js = _around(chosen['start'], chosen['length'])+ profile = _profile(distances, js, radius, lo, hi)+ fundamental = period_mod.screen(+ chosen['period_local'], D=distances, prof=profile, minima=period_mod.local_minima(profile),+ mean=float(np.mean(list(profile.values()))), lowest=max(lo, gait_floor), periodicity_min=periodicity_min,+ signals=signals, gait=True, js=js, floor_why='the gait floor' if gait_floor >= lo else 'the window')+ steps = period_mod.step_screen(distances, start=chosen['start'], length=chosen['length'],+ periodicity_min=periodicity_min, signals=signals)+ return fundamental, steps+++def judged(rows, judge):+ """Each window row's steps as the clip's crossings count them (`step_count`: verdict, code, k, phase)."""+ for row in rows:+ counted = judge(row['start'], row['length'])+ row['step_count'] = {k: counted[k] for k in ('verdict', 'code', 'k', 'phase') if k in counted}+ return rows++def detect(distances, trajectory, *, min_len, max_len, gait_floor,periodicity_min, double_tolerance, double_search, max_fraction=.5, signals=None, wrap_pop=None,- held_edge=None, length_cap=None, double=True, closure=False):+ held_edge=None, length_cap=None, double=True, closure=False, judge=None):"""`wrap_pop(start, length)`, when given, is the top band's jump at that cut's wrap(repair.seam_pop): a chosen cut that pops is chosen again (`_shape_rank`), and a search that findsnothing raises with the windows it refused, popping ones last (`ValueError.diagnostics`).@@ -249,7 +280,11 @@ def detect(distances, trajectory, *, min_len, max_len, gait_floor,Among the equivalent candidates the earliest is taken; with `closure` (a length the caller counted,`video-loop --steps`), the one whose wrap is nearest the clip's own way on there (`_closure`). Thecut taken is screened for one step of a cycle twice as long (`step_screen`, period.step_screen,- over the whole clip); nothing is cut on it."""+ over the whole clip); nothing is cut on it.++ `judge(start, length)` (crossings.Reading.judge), when given, refuses a window whose steps the clip's+ crossings count as other than two ('one step', 'three steps': `refuted`), and a search that finds+ nothing names each refused window's count (`step_count`), those the crossings refute last."""n = len(distances)# A cycle has to be seen repeating: half the clip by default, more for the gait fallback, and as# long as the caller's own ceiling allows.@@ -306,6 +341,11 @@ def detect(distances, trajectory, *, min_len, max_len, gait_floor,if min(first_motion, second_motion) < .25*step:refuse('a still segment')continue+ if judge is not None:+ counted = judge(start, length)+ if counted['verdict'] == 'refuted':+ refuse(f"{counted['why']} in the clip's crossings")+ continueratio = float(distances[start+length-1, start])/stepx = np.arange(length)segment = trajectory[start:start+length]@@ -324,6 +364,8 @@ def detect(distances, trajectory, *, min_len, max_len, gait_floor,# (a forced cut) takes one the engine measured instead of the whole clip.refused.sort(key=lambda row: (row['score'], row['start'], row['length']))shown = refused[:REFUSED_SHOWN]+ if judge is not None:+ judged(shown, judge)if wrap_pop is not None:# Those whose top closes first, then those whose top could not be read, then those that pop.rank = {}@@ -332,10 +374,13 @@ def detect(distances, trajectory, *, min_len, max_len, gait_floor,_mark(row, measured)rank[row['start'], row['length']] = 1 if 'skipped' in measured else 2 if measured['pops'] else 0shown.sort(key=lambda row: (rank[row['start'], row['length']], row['score'], row['start'], row['length']))+ if judge is not None:+ shown.sort(key=lambda row: row['step_count']['verdict'] == 'refuted')exc.diagnostics = {'kind': 'periodic', 'method': 'local-repeat-drift-v1', 'status': 'refused','window': [lo, hi], 'refused_count': len(refused),'order': 'score' + (', windows whose top could not be read after those whose top closes,'- ' windows whose top pops at the wrap last' if wrap_pop is not None else ''),+ ' windows whose top pops at the wrap last' if wrap_pop is not None else '')+ + (', windows whose steps the crossings refute after the rest' if judge is not None else ''),'candidates': shown}raise exccandidates.sort(key=lambda row: (row['score'], row['start'], row['length']))@@ -357,14 +402,8 @@ def detect(distances, trajectory, *, min_len, max_len, gait_floor,# A window two lengths long (`_held_rank`) was not a candidate: its wrap over its step, as a candidate's.s, L = chosen['start'], chosen['length']chosen['ratio'] = float(distances[s+L-1, s])/float(np.diag(distances[s:s+L, s:s+L], 1).mean())- radius, js = _around(chosen['start'], chosen['length'])- profile = _profile(distances, js, radius, lo, hi)- fundamental = period_mod.screen(- chosen['period_local'], D=distances, prof=profile, minima=period_mod.local_minima(profile),- mean=float(np.mean(list(profile.values()))), lowest=max(lo, gait_floor), periodicity_min=periodicity_min,- signals=signals, gait=True, js=js, floor_why='the gait floor' if gait_floor >= lo else 'the window')- steps = period_mod.step_screen(distances, start=chosen['start'], length=chosen['length'],- periodicity_min=periodicity_min, signals=signals)+ fundamental, steps = _screens(distances, chosen, lo=lo, hi=hi, gait_floor=gait_floor,+ periodicity_min=periodicity_min, signals=signals)return {**chosen, 'fundamental': fundamental, 'kind': 'periodic', 'method': 'local-repeat-drift-v1','period_global': None, 'periodicity_min': periodicity_min,@@ -375,3 +414,150 @@ def detect(distances, trajectory, *, min_len, max_len, gait_floor,**({'seam_pop': shape} if shape is not None else {}),'step_screen': steps,}+++def _worse(row):+ return max(row['seam_flow']['off'])+++def _calm(row):+ """The cut's top band was read at the wrap and does not pop (`wrap_pop`)."""+ return 'pops' in row['top'] and not row['top']['pops']+++def _rank(rows, *, flow_limit, seam_max, in_phase):+ """Two-step cuts, best first, and whether the first passed the gates: in phase (`in_phase`), its top band calm at+ the wrap (`_calm`: a thin part the flow hardly sees, a staff, does not jump), its wrap over its step (`ratio`) at+ most `seam_max` (what the seam gate holds a loop to) and both seam frames' flow off under `flow_limit`, the worse+ within SEAM_FLOW_BAND of the smoothest such cut's, then the wrap nearest the clip's own way on (`_closure`); after+ those the rest, in phase first, then calm, then under the flow limit, then under `seam_max`, then by the worse flow."""+ gated = [row for row in rows if in_phase(row) and _calm(row) and row['ratio'] <= seam_max and _worse(row) < flow_limit]+ best = min((_worse(row) for row in gated), default=None)+ band = sorted((row for row in gated if _worse(row) <= best + SEAM_FLOW_BAND),+ key=lambda row: (row['closure'] is None, row['closure'] or 0.0, _worse(row), row['start'], row['length']))+ rest = sorted((row for row in rows if row not in band),+ key=lambda row: (not in_phase(row), not _calm(row), _worse(row) >= flow_limit, row['ratio'] > seam_max, _worse(row),+ row['start'], row['length']))+ return band + rest, bool(band)+++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):+ """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 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.+ - Else the cuts [min_len, max_len] frames long that cover two steps, any start, however long — the window that+ binds the search binds no count; none, and the search's word stands. Those in phase, if any, else all, are+ read at the wrap (`seam_flow(start, length)`: the flow off of the cut's last and first frames; `wrap_pop`, the+ top band's jump, repair.seam_pop) and ranked (`_rank`). Of the first SEAM_TRIES the first whose seam the seam+ gate passes (`seam_gate`: its wrap over its step as the gate will read the cut, at most `seam_max`) is taken,+ where none the first, and the gate says whether it closes (`method: observed-two-steps-v1`). The pixel+ search's own repeat rule is not asked: a part off the legs' beat (a tail) repeats on its own and its seam is+ the flow repair's; `repeat` records it.++ A cut taken on two steps records `steps` (count 2, by crossings): `video-cycle-align` reads a return half way+ as its step, and the step screen's pixel suspicion of one step (`step_screen`) is settled, kept as+ `pixel_suspect`."""+ record = reading.record()+ record['search'] = ({'cut': [found['start'], found['length']]} if found is not None else {'refused': str(refused)})+ if not reading.readable:+ record['chosen_by'] = 'search'+ if found is not None:+ record['cut'] = reading.judge(found['start'], found['length'])+ return found, record+ if found is not None:+ counted = reading.judge(found['start'], found['length'])+ record['search'].update({k: counted[k] for k in ('verdict', 'code', 'k', 'phase') if k in counted})+ if reading.in_phase(counted):+ record.update(chosen_by='search', cut=counted)+ return _two_steps(found, record), record+ twos = reading.twos(min_len, max_len)+ record['two_cuts'] = len(twos)+ if not twos:+ record['chosen_by'] = 'search'+ if found is not None:+ record['cut'] = reading.judge(found['start'], found['length'])+ return found, record+ pool = [row for row in twos if reading.in_phase(row)]+ record['in_phase'] = len(pool)+ rows = []+ for counted in pool or twos:+ start, length = counted['cut']+ step = float(np.diag(distances[start:start+length, start:start+length], 1).mean())+ rows.append({'start': start, 'length': length, 'phase': counted['phase'], 'counted': counted,+ 'seam_flow': seam_flow(start, length), 'top': wrap_pop(start, length), 'closure': _closure(distances, start, length),+ 'ratio': float(distances[start+length-1, start])/step if step > 1e-10 else math.inf})+ ranked, gated = _rank(rows, flow_limit=flow_limit, seam_max=seam_max, in_phase=lambda row: reading.in_phase(row['counted']))+ tried = []+ for row in ranked[:SEAM_TRIES]:+ tried.append({'start': row['start'], 'length': row['length'], 'seam': round(seam_gate(row['start'], row['length']), 3)})+ if tried[-1]['seam'] <= seam_max:+ break+ passed = [t for t in tried if t['seam'] <= seam_max]+ picked = next(row for row in ranked if (row['start'], row['length']) == ((passed[0]['start'], passed[0]['length']) if passed+ else (tried[0]['start'], tried[0]['length'])))+ record['seam_gate'] = {'max': seam_max, 'tried': tried}+ start, length = picked['start'], picked['length']+ record.update(chosen_by='two steps', cut=picked['counted'], gated=gated, flow_limit=flow_limit, seam_max=seam_max)+ # The pixel search's own word on this cut: its repeat, read as `detect` reads a window it refused.+ radius, js = _around(start, length)+ measured = _measure(distances, trajectory, start, length, _profile(distances, js, radius, max(6, min_len), length))+ if measured is not None:+ over = measured['context_repeat_over_step']+ record['repeat'] = {'over_step': round(over, 3), 'max': REPEAT_OVER_STEP_MAX,+ **({'why': f'about its start the clip a cut length on is {over:.2f} playback steps off, over '+ f'{REPEAT_OVER_STEP_MAX}: the pixel search refuses it (repeat error over two steps) — a part '+ 'off the legs\' beat repeats on its own'} if over > REPEAT_OVER_STEP_MAX else {})}+ cycle = {'start': start, 'length': length, 'period_local': length, 'ratio': picked['ratio'],+ 'closure': picked['closure'], 'seam_flow': picked['seam_flow'], 'top': picked['top'], 'kind': 'periodic', 'method': 'observed-two-steps-v1',+ 'repeat': 'two steps seen in the clip, joined at the walk\'s own point',+ 'period_global': None, 'periodicity_min': periodicity_min, 'review_recommended': not gated,+ 'candidate_count': len(rows),+ 'candidates': [{'start': row['start'], 'length': row['length'], 'phase': row['phase'], 'seam_flow': row['seam_flow']['off'],+ 'seam_pop': row['top'].get('pop'), 'ratio': round(row['ratio'], 3),+ 'closure': None if row['closure'] is None else round(row['closure'], 3)}+ for row in ranked[:REFUSED_SHOWN]]}+ cycle['fundamental'], cycle['step_screen'] = _screens(distances, cycle, lo=max(6, min_len), hi=max(length, min_len),+ gait_floor=gait_floor, periodicity_min=periodicity_min, signals=signals)+ return _two_steps(cycle, record), record+++def _two_steps(cycle, record):+ """A cut the crossings count two steps: `steps` recorded, the step screen's pixel suspicion settled."""+ cycle.setdefault('steps', {'count': 2, 'by': 'crossings'})+ screen = cycle.get('step_screen')+ if screen and screen.get('suspect'):+ screen.update(suspect=False, pixel_suspect=True, settled_by='crossings',+ why=f"two steps counted on the clip's crossings (cycle.step_count); the pixels alone: {screen['why']}")+ return cycle+++def step_verdict(cycle):+ """The step count's warnings, in words: a cut taken on two steps whose seam the pixel search refuses (a part off+ the legs' beat) or that passed no gate, and a clip that shows its steps but no cut of two."""+ counted = cycle.get('step_count')+ if not counted or not counted.get('readable'):+ return []+ s, L = cycle['start'], cycle['length']+ out = []+ if counted.get('chosen_by') == 'two steps':+ if not counted.get('gated'):+ out.append(f"the cut {s}/{L} covers two steps by the clip's crossings, but no two-step cut joins the walk within "+ f"its phase, its top calm, its wrap within {counted['seam_max']:g} of its step and its seam under the flow "+ f"limit {counted['flow_limit']:g} (phase {counted['cut']['phase']:+.1f} frames, wrap {cycle['ratio']:.2f}, "+ f"seam flow {cycle['seam_flow']['off']}, top {cycle['top'].get('pop', cycle['top'].get('skipped'))}): "+ "a part on a beat of its own closes on no cut of two steps — look at the wrap")+ if 'why' in counted.get('repeat', {}):+ worst = int(np.argmax(cycle['seam_flow']['off']))+ out.append(f"the cut {s}/{L} covers two steps by the clip's crossings, and {counted['repeat']['why']}; the seam's "+ f"worst window is {cycle['seam_flow']['window'][worst]} of the body's box, turning "+ f"{cycle['seam_flow']['turn'][worst]:+.2f} there — the flow repair reads it")+ elif 'two_cuts' in counted and counted['two_cuts'] == 0:+ out.append(f"the clip shows its steps (crossings {counted['crossings']}) but no cut of two: the cut {s}/{L} is "+ f"{counted['cut']['verdict']} ({counted['cut']['why']}) — count its steps")+ return outdiff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.pyindex fcd33e6..da7342d 100644--- a/sprite_gen/video/loop.py+++ b/sprite_gen/video/loop.py@@ -49,6 +49,7 @@ from sprite_gen.spec.runio import atomic_write_textfrom sprite_gen.util.gif_utils import save_clean_giffrom sprite_gen.util.resample import resize_cellfrom sprite_gen.video import motion_anchor, auto_motion, local_cycle, gait_fallback, nonloop, effect+from sprite_gen.video import crossings as crossings_modfrom sprite_gen.video import held as held_modfrom sprite_gen.video import legs as legs_modfrom sprite_gen.video import period as period_mod@@ -969,12 +970,29 @@ def _ghost_lines(jump_repair: dict[str, Any]) -> list[str]:return lines+def _shifts(analysis: dict[str, Any]) -> tuple[np.ndarray, int]:+ """The analysis translation `auto_motion.analyse` measured, whole pixels a frame, and the room it needs."""+ shifts = np.rint(np.asarray(analysis["analysis_only_translation_xy"], dtype=np.float64)).astype(int)+ return shifts, int(np.abs(shifts).max()) + 1+++def moved_frames(frames: list[Image.Image], analysis: dict[str, Any]) -> list[Image.Image]:+ """Every frame whole, moved as `moved_alpha` moves its alpha, on one canvas: what `SeamFlow` reads a cut's wrap+ on, so a body that walks across the frame or toward it is read at the wrap as the cut will be corrected."""+ shifts, pad = _shifts(analysis)+ out = []+ for f, (dx, dy) in zip(frames, shifts):+ canvas = Image.new("RGBA", (f.width + 2 * pad, f.height + 2 * pad))+ canvas.paste(f, (pad + int(dx), pad + int(dy)))+ out.append(canvas)+ return out++def moved_alpha(frames: list[Image.Image], analysis: dict[str, Any]) -> list[np.ndarray]:"""The alpha of every frame, each moved by the analysis translation `auto_motion.analyse` measured(its drift taken out, the way the cut will be corrected), cropped once to the clip's subject:what `wrap_pop_on` and `HeldEdge` read a cut on."""- shifts = np.rint(np.asarray(analysis["analysis_only_translation_xy"], dtype=np.float64)).astype(int)- pad = int(np.abs(shifts).max()) + 1+ shifts, pad = _shifts(analysis)boxes = [f.getchannel("A").point(lambda v: 255 if v >= repair_mod.ALPHA_SOLID else 0).getbbox() for f in frames]boxes = [b for b in boxes if b]box = (min(b[0] for b in boxes), min(b[1] for b in boxes), max(b[2] for b in boxes), max(b[3] for b in boxes))@@ -1036,6 +1054,96 @@ class HeldEdge:return {"skipped": str(exc), "reference": repair_mod.HELD_EDGE_REFERENCE}+class SeamFlow:+ """The flow at a cut's wrap, for `local_cycle.by_steps` to rank two-step cuts by: the flow off of the cut's last and+ first frames (`off`), their worst windows (`window`, fractions of the clip's union box) and turns there (`turn`) —+ `repair.ring_scores` on the clip's path, its frames moved as the cut will be corrected (`moved_frames`), read once+ on first use (`repair.clip_flow_states`)."""++ def __init__(self, frames: list[Image.Image], analysis: dict[str, Any]):+ self.frames, self.analysis = frames, analysis+ self._states: np.ndarray | None = None++ def __call__(self, start: int, length: int) -> dict[str, Any]:+ if self._states is None:+ self._states = repair_mod.clip_flow_states(moved_frames(self.frames, self.analysis))+ scores = repair_mod.ring_scores(self._states[start:start + length])+ at = (length - 1, 0)+ return {"off": [round(float(scores["off"][k]), 3) for k in at], "turn": [round(float(scores["turn"][k]), 3) for k in at],+ "window": [[round(v, 3) for v in scores["windows"][int(scores["window"][k])]] for k in at]}+++def seam_on_cells(frames: list[Image.Image]) -> float:+ """The seam gate's reading of a motion-auto cut before it is cut: its frames corrected as the cut will be+ (`auto_motion.discover`, `auto_motion.correct_cycle`), cropped to their union box, the wrap over the mean step on+ the analysis thumbnail — the rendered cells the gate reads, short of the strip's scale and the jump repair.+ Infinite where the frames cannot be corrected."""+ try:+ regions, _ = auto_motion.discover(frames, reference_index=0)+ frames, _ = auto_motion.correct_cycle(frames, regions, coarse_dx=body_wrap_offset(frames, search=motion_anchor.COARSE_SEARCH))+ except ValueError:+ return math.inf+ boxes = [f.getbbox() for f in frames]+ boxes = [b for b in boxes if b]+ box = (min(b[0] for b in boxes), min(b[1] for b in boxes), max(b[2] for b in boxes), max(b[3] for b in boxes))+ flat = np.stack([_small_features(f.crop(box)) for f in frames])+ step = float(np.abs(flat[1:] - flat[:-1]).mean())+ return float(np.abs(flat[-1] - flat[0]).mean()) / step if step > 0 else math.inf+++def _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) -> 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`).++ Where the clip shows its steps but no cut of two, and the search's cut is one they refute (one step, three), the+ search runs again on the window it searched (`searched`) refusing such cuts (`detect`'s `judge`). A search that+ finds nothing names each refused window's count, those the crossings refute last, and raises."""+ 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")+ 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),+ seam_flow=SeamFlow(frames, analysis), wrap_pop=wrap_pop_on(moved), seam_gate=lambda s, L: seam_on_cells(frames[s:s + L]),+ flow_limit=repair_mod.FLOW_LIMIT, seam_max=seam_max,+ gait_floor=detect["gait_floor"], periodicity_min=detect["periodicity_min"], signals=signals)+ if picked is not None and record.get("cut", {}).get("verdict") == "refuted":+ first = record["cut"]+ try:+ picked = local_cycle.detect(D, trajectory, signals=signals, wrap_pop=wrap_pop_on(moved), held_edge=HeldEdge(moved),+ length_cap=window.max_len, judge=reading.judge, **searched, **detect)+ except ValueError as exc:+ picked, refused = None, exc+ record["searched_again"] = {"refuted": first, "why": f"no cut of two steps, and the search's cut is {first['why']}: "+ "searched again, refusing the cuts the crossings refute"}+ if picked is not None:+ record["cut"] = reading.judge(picked["start"], picked["length"])+ elif window.said() and record.get("two_cuts") == 0 and reading.twos(1, len(frames)):+ # The caller's window holds none of the walk's two steps: the window and the walk disagree.+ lengths = sorted({row["cut"][1] for row in reading.twos(1, len(frames))})+ failed = ValueError(f"no cut of two steps in {window.said()}: the clip's crossings show two steps take "+ f"{lengths[0]}-{lengths[-1]} frames, and every cut the window holds that the search found is "+ f"{first['why']} — widen the window, or count the steps (--steps)")+ failed.diagnostics = getattr(refused, "diagnostics", {}) # type: ignore[attr-defined]+ refused = failed+ if picked is None:+ diagnostics = getattr(refused, "diagnostics", None)+ if isinstance(diagnostics, dict):+ if reading.readable and diagnostics.get("candidates") and "step_count" not in diagnostics["candidates"][0]:+ local_cycle.judged(diagnostics["candidates"], reading.judge)+ diagnostics["candidates"].sort(key=lambda row: row["step_count"]["verdict"] == "refuted")+ diagnostics["order"] = f"{diagnostics.get('order', 'score')}, windows whose steps the crossings refute after the rest"+ diagnostics["step_count"] = record+ assert refused is not None+ raise refused+ picked["step_count"] = record+ return picked++def _counted(cycle: dict[str, Any], steps: int, *, window: CutWindow, D: np.ndarray, trajectory: np.ndarray,frames: list[Image.Image], moved: list[np.ndarray], detect: dict[str, Any]) -> dict[str, Any]:"""The cut once its steps are counted (`--steps`): 2 keeps it; 1 cuts again in the window two of@@ -1259,6 +1367,8 @@ def run_loop(report_base["automatic_motion_analysis"] = analysisdetect = dict(gait_floor=round(prof.min_seconds*fps), periodicity_min=PERIODICITY_MIN,double_tolerance=GAIT_DOUBLE_TOL, double_search=GAIT_DOUBLE_SEARCH)+ searched: dict[str, Any] = {"min_len": lo, "max_len": hi}+ refused: ValueError | None = Nonetry:moved = moved_alpha(source_frames, analysis)cycle = local_cycle.detect(D, trajectory, min_len=lo, max_len=hi, signals=leg_signals(source_frames),@@ -1280,6 +1390,7 @@ def run_loop(hi_long = window.past(gait_fallback.long_window(lo, len(files), fps))fallback["window"] = [lo, hi_long]report_base["gait_fallback"] = fallback+ searched = {"min_len": lo, "max_len": hi_long, "max_fraction": gait_fallback.LONG_CYCLE_FRACTION}try:moved = moved_alpha(source_frames, analysis)cycle = local_cycle.detect(D, trajectory, min_len=lo, max_len=hi_long,@@ -1292,9 +1403,16 @@ def run_loop(# The windows the wider search measured and refused go into the report's `cycle`.if hasattr(second, "diagnostics"):failed.diagnostics = second.diagnostics # type: ignore[attr-defined]- raise failed from first+ failed.__cause__ = first+ refused, cycle = failed, Noneif steps is not None:+ # A count given is the word on the search's cut; the crossings are not asked.+ if refused is not None:+ raise refusedcycle = _counted(cycle, steps, window=window, D=D, trajectory=trajectory, frames=source_frames, moved=moved, detect=detect)+ 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)elif cycle_mode == "once":source_frames = [Image.open(f).convert("RGBA") for f in files]boxes = [nonloop.body_box(frame) for frame in source_frames]@@ -1336,6 +1454,9 @@ def run_loop()if skip:cycle, shifted = _from_lead_in(cycle, skip), True+ if "step_count" in cycle:+ # Its frame numbers are the search's: the clip's after its lead-in.+ cycle["step_count"]["read_from"] = skip# Whatever chose the cut — a search, a count, --cycle fixed or pinned — it is inside the caller's bounds.window.hold(cycle)except (SystemExit, ValueError) as exc:@@ -1483,6 +1604,7 @@ def run_loop(# The held side below the top, read on the source frames when the cut was chosen again (local_cycle).warnings += repair_mod.held_edge_verdict(cycle.get("seam_pop"))warnings += coverage_verdict(cycle)+ warnings += local_cycle.step_verdict(cycle)gated = repair != "off" and (jolt_max is not None or head_step_max is not None)over = repair_mod.jolt_verdict(jolt, jolt_max=jolt_max, head_step_max=head_step_max) if gated else []report_base["jolt"] = {**jolt, "reference": reference, "warnings": warnings,@@ -1739,6 +1861,9 @@ def run(**kwargs: object) -> int:summary["cycle"]["coverage"] = payload["cycle"]["coverage"]if "step_screen" in payload["cycle"]:summary["cycle"]["step_screen"] = payload["cycle"]["step_screen"]+ if "step_count" in payload["cycle"]:+ counted = payload["cycle"]["step_count"]+ summary["cycle"]["step_count"] = {k: counted[k] for k in ("mode", "readable", "chosen_by", "cut", "why") if k in counted}if payload.get("ghost_screen", {}).get("ghosts") or payload.get("ghost_screen", {}).get("reads") is False:summary["ghost_screen"] = payload["ghost_screen"]for key in ("ghost_given_way", "ghost_kept"):diff --git a/sprite_gen/video/repair.py b/sprite_gen/video/repair.pyindex f768da2..9aab6ad 100644--- a/sprite_gen/video/repair.py+++ b/sprite_gen/video/repair.py@@ -106,6 +106,7 @@ FLOW_BLUR = 0.03 # the blur's sigma, of the body height: a shape moved one ordiFLOW_GRID = 4 # the union box in FLOW_GRID x FLOW_GRID cells, read in windows of 2 x 2 cells at a stride of one cellFLOW_LIMIT = 3.0 # a frame this many of its window's usual steps off the line between its neighbours leaves the flowFLOW_SPAN = 2 # frames in a row a group takes out at most, to be made again between the frames either side+FLOW_CHUNK = 12 # frames a whole clip's path is read in at a time (`clip_flow_states`): a clip's pixels whole are gigabytes# The share of a held loop's runs that show their drawing for the hold, a frame more or less (a slip): under it the# runs are not the hold, and the loop is read a drawing a frame (`flow_drawings`).HELD_RUNS = 0.75@@ -131,11 +132,28 @@ def flow_states(frames: list[Image.Image], box: tuple[int, int, int, int] | None(luma times coverage) inside `box` (the union box), averaged down to a grid of a third of the blurand blurred by FLOW_BLUR of the body height. Raises ValueError for a loop with no body."""pixels = np.stack([np.asarray(f.crop(box or union_box(frames)), dtype=np.float64) / 255.0 for f in frames])- alpha = pixels[..., 3]- rows = np.where(alpha.max(axis=(0, 2)) > 0.1)[0]+ rows = np.where(pixels[..., 3].max(axis=(0, 2)) > 0.1)[0]+ if rows.size == 0:+ raise ValueError("every loop frame is fully transparent")+ return _states(pixels, FLOW_BLUR * max(1, int(rows.max() - rows.min())))+++def clip_flow_states(frames: list[Image.Image]) -> np.ndarray:+ """`flow_states` of a whole clip in one box, its union box, and one blur, read FLOW_CHUNK frames at a time: the path+ every cut of the clip is read on (`ring_scores`), so a choice among its cuts reads each seam alike without reading+ the clip again for each one."""+ box = union_box(frames)+ rows = np.where(np.max([np.asarray(f.crop(box), dtype=np.float64)[..., 3].max(axis=1) / 255.0 for f in frames], axis=0) > 0.1)[0]if rows.size == 0:raise ValueError("every loop frame is fully transparent")sigma = FLOW_BLUR * max(1, int(rows.max() - rows.min()))+ return np.concatenate([_states(np.stack([np.asarray(f.crop(box), dtype=np.float64) / 255.0 for f in frames[k:k + FLOW_CHUNK]]), sigma)+ for k in range(0, len(frames), FLOW_CHUNK)])+++def _states(pixels: np.ndarray, sigma: float) -> np.ndarray:+ """The frames' points (`flow_states`) from their pixels in the box, 0..1, blurred by `sigma` px."""+ alpha = pixels[..., 3]planes = np.stack([alpha, (pixels[..., :3] @ _LUMA) * alpha], axis=-1)n, height, width, c = planes.shapef = max(1, min(int(round(sigma / 1.5)), height, width))@@ -215,7 +233,11 @@ def _flow(frames: list[Image.Image], box: tuple[int, int, int, int] | None,"""The loop's path read on its drawings: their states, the runs of frames that show them, the windows,and per drawing and window the distance off the path, the step out and the turn, and the windows' usualstep. `drawings` (runs, hold) reads it on those drawings instead of the ones `flow_drawings` finds."""- states = flow_states(frames, box)+ return _flow_on(flow_states(frames, box), drawings)+++def _flow_on(states: np.ndarray, drawings: tuple[list[list[int]], int] | None = None) -> dict[str, Any]:+ """`_flow` of a loop whose path is read already."""runs, hold = drawings if drawings is not None else flow_drawings(states)path = states[[run[0] for run in runs]]windows = flow_windows(states.shape[1], states.shape[2])@@ -242,9 +264,19 @@ def flow_scores(frames: list[Image.Image], *, box: tuple[int, int, int, int] | Nthe step into the drawing and the step out of it (`turn`, below 0 against the way it came, 1 whereeither is still) and the two steps in the window's usual steps (`into`, `out`). Every frame thatshows a drawing (`flow_drawings`, `hold`) reads the drawing's values."""- flow = _flow(frames, box)+ return _frame_scores(_flow(frames, box), len(frames))+++def ring_scores(states: np.ndarray) -> dict[str, Any]:+ """`flow_scores` of a loop whose path is read already: a cut of the clip's path (`clip_flow_states`), read as the+ ring the cut plays. The box and the blur are the clip's, not the cut's own, so a frame of one cut reads as it does+ in another; the values are the cut's `flow_scores` within what a box a little larger moves the windows by."""+ return _frame_scores(_flow_on(states), len(states))+++def _frame_scores(flow: dict[str, Any], frames: int) -> dict[str, Any]:per = _drawing_scores(flow)- of = np.zeros(len(frames), dtype=int)+ of = np.zeros(frames, dtype=int)for d, run in enumerate(flow["runs"]):of[run] = dreturn {**{k: v[of] for k, v in per.items()}, "windows": flow["fractions"], "hold": flow["hold"]}diff --git a/tests/conftest.py b/tests/conftest.pyindex 00e3e3b..cd93e9a 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -5,6 +5,7 @@ import shutilimport subprocessimport sysfrom collections.abc import Generator+from contextlib import contextmanagerfrom pathlib import Pathimport pytest@@ -115,6 +116,19 @@ def pytest_make_collect_report(collector: pytest.Collector) -> Generator[None, preturn report+@contextmanager+def feet_unseen() -> Generator[None, None, None]:+ """`video-loop`'s step count reads no feet (sprite_gen/video/crossings.py): the cut is the pixel search's alone.+ For the tests of that search, whose walker is drawn for it — legs that open and close once a drawing and never+ pass each other, a scissor no walk makes, which the count reads as one step a drawing — and of the step screen,+ the word where a clip does not show its steps."""+ from sprite_gen.video import crossings++ with pytest.MonkeyPatch.context() as mp:+ mp.setattr(crossings, "read", lambda sig: crossings.Reading(len(sig["gap"]), "gap", [], why="the feet read as unseen (test)"))+ yield++@pytest.fixturedef fixture_run_dir(tmp_path: Path) -> Path:"""A throwaway copy of the golden fixture run dir."""diff --git a/tests/video/test_auto_motion.py b/tests/video/test_auto_motion.pyindex a45fc6e..89d6943 100644--- a/tests/video/test_auto_motion.py+++ b/tests/video/test_auto_motion.py@@ -5,9 +5,18 @@ import mathimport numpy as npimport pytestfrom PIL import Image, ImageDraw+from conftest import feet_unseenfrom sprite_gen.video import auto_motion, batch, local_cycle, loop[email protected](scope="module", autouse=True)+def _feet_unseen():+ """Every cut in this module is the pixel search's: the walker's legs open and close once a drawing and never pass+ each other, which the step count would read as one step a drawing (tests/conftest.py, `feet_unseen`)."""+ with feet_unseen():+ yield++def walker(k, *, repeat=True):im = Image.new('RGBA', (280, 180))d = ImageDraw.Draw(im)diff --git a/tests/video/test_crossings.py b/tests/video/test_crossings.pynew file mode 100644index 0000000..a905c16--- /dev/null+++ b/tests/video/test_crossings.py@@ -0,0 +1,248 @@+# SPDX-License-Identifier: Apache-2.0+"""The step count of a walk's cut, read only from the crossings the clip shows (sprite_gen/video/crossings.py,+docs/loop-repair.md section 3, "The step count").++Each bait is a way something the clip never showed could pass for a step: a walk that stalls, a stand with the feet+together, a stomp, the stance a clip opens on, a pass the clip's first frame cuts, a wrap half a step off, a wrap+that slips a frame of feet together in, noise at the reading's threshold, a stop wobbling at the axis, a clip that+ends on a change it never confirms. Two readings that counted them as two steps were refused before this one: one+divided a cut's length by the median step (a cut with no crossing counted two), one read the loop as played, its+wrap included (a side change the wrap made counted as a crossing). Each bait names the cuts they took for two.++The signals are synthetic: the foot band's gap (`gap`, seen apart from 0.03 of the body's height), its lean about+the body's axis (`lean`, a step a half wave) and its mass."""++from __future__ import annotations++import math++import numpy as np+import pytest+from PIL import Image, ImageDraw++from sprite_gen.video import crossings, legs+++def _gap_walk(n: int, centres: list[int], width: int = 2, still: tuple[tuple[int, int], ...] = ()) -> dict[str, list[float]]:+ """Feet together for 2 x width + 1 frames about each centre, apart (0.1 of the height) between; the foot band+ moving throughout but over the `still` frames, held as the frame before them (the first moving one for a head)."""+ gap = np.full(n, 0.1)+ for c in centres:+ gap[max(0, c - width):c + width + 1] = 0.0+ t = np.arange(n, dtype=float)+ mass, lean = 1.0 + 0.5 * np.cos(2 * np.pi * t / 15), np.sin(np.pi * t / 15)+ for a, b in still:+ src = a - 1 if a > 0 else b + 1+ mass[a:b + 1], lean[a:b + 1] = mass[src], lean[src]+ return {"gap": list(gap), "lean": list(lean), "mass": list(mass)}+++def _sine(n: int, half: int = 13) -> np.ndarray:+ """The nearer foot changing side every `half` frames."""+ return np.sin(np.pi * (np.arange(n) + .5) / half)+++def _sign_walk(lean: np.ndarray) -> dict[str, list[float]]:+ return {"gap": [0.0] * len(lean), "lean": list(lean), "mass": [1.0] * len(lean)}+++def _points(n: int, at: list[int]) -> crossings.Reading:+ return crossings.Reading(n, "points", [(x, x) for x in at])+++def _verdicts(reading: crossings.Reading, cases: dict[tuple[int, int], str]) -> dict[tuple[int, int], str]:+ return {cut: reading.judge(*cut)["verdict"] for cut in cases}+++# --- stalls: a cut that plays a step the walk does not take ------------------------------------------------------++def test_a_walk_that_stalls_proves_no_two_steps_across_the_stall():+ """Crossings 5, 20, 35, 80, 95, 110: the walk stalls between 35 and 80. A cut with no crossing (40/30), one that+ plays the stall on either side of its wrap and one that ends where the stall starts its step are not two; the+ length reading counted 40/30, 30/30 and 6/31 two, the loop reading 6/31."""+ cases = {(40, 30): "uncertain", (30, 30): "uncertain", (33, 50): "uncertain", (18, 40): "uncertain",+ (6, 31): "uncertain", (6, 30): "two", (2, 30): "two", (7, 15): "refuted", (82, 30): "two"}+ assert _verdicts(_points(116, [5, 20, 35, 80, 95, 110]), cases) == cases+ assert _points(116, [5, 20, 35, 80, 95, 110]).judge(40, 30)["code"] == "step-long"+++def test_a_hold_after_the_cut_is_read_on_both_sides_of_the_wrap():+ """The nearer foot changes side every 13 frames and holds from 135 to 174. The loop reading counted 117/26,+ 112/26 and 110/30 two: the wrap flips the foot back, and the step before the cut (115.5 to 130.5, 15 frames) is+ ordinary. The step after it is the hold (130.5 to 174.5, 44 frames): not two."""+ lean = _sine(400)+ lean[135:175] = lean[134]+ reading = crossings.read(_sign_walk(lean))+ cases = {(117, 26): "uncertain", (112, 26): "uncertain", (110, 30): "uncertain", (100, 30): "two", (60, 26): "two"}+ assert _verdicts(reading, cases) == cases+++def test_a_hold_before_the_cut_leaves_no_two_anywhere_near_it():+ """The mirror: a hold from 200 to 239, one change after it; every cut from 222 to 241, 22 to 30 frames long. The+ loop reading took 16 of the 180 for two, the length reading 104."""+ lean = _sine(400)+ lean[200:240] = lean[199]+ reading = crossings.read(_sign_walk(lean))+ assert not [(s, L) for s in range(222, 242) for L in range(22, 31) if reading.judge(s, L)["verdict"] == "two"]+++def test_a_stall_with_the_feet_apart_and_a_stand_with_them_together():+ """No crossing from 37 to 82 with the feet apart (the length reading counted 45/30 and 30/30 two); the feet+ together from 50 to 89 (the loop reading, joining the run across its wrap, counted 23/30 two)."""+ cases = {(45, 30): "uncertain", (30, 30): "uncertain", (0, 30): "two"}+ assert _verdicts(crossings.read(_gap_walk(110, [7, 22, 37, 82, 97])), cases) == cases+ sig = _gap_walk(150, [7, 22, 37, 97, 112, 127, 142])+ sig["gap"][50:90] = [0.0] * 40+ stand = crossings.read(sig)+ cases = {(23, 30): "uncertain", (8, 30): "two", (99, 30): "two"}+ assert _verdicts(stand, cases) == cases+ assert stand.judge(23, 30)["code"] in ("stand", "step-long")+++def test_a_stomp_in_place_is_a_step_out_of_range():+ """The foot set down again in place 7 frames after the pass at 37: the loop reading counted 46/30 two."""+ sig = _gap_walk(100, [7, 22, 37, 52, 67, 82])+ sig["gap"][44:46] = [0.0, 0.0]+ cases = {(30, 30): "uncertain", (46, 30): "uncertain", (53, 30): "two"}+ assert _verdicts(crossings.read(sig), cases) == cases+++# --- the clip's head and tail -------------------------------------------------------------------------------------++def test_the_stance_a_clip_opens_on_is_no_step():+ """Feet together 20 frames, or the lean held 40, before the walk starts: the length reading counted 5/30 and+ 25/26 two."""+ sig = _gap_walk(100, [32, 47, 62, 77, 92])+ sig["gap"][0:20] = [0.0] * 20+ cases = {(5, 30): "uncertain", (35, 30): "two"}+ assert _verdicts(crossings.read(sig), cases) == cases+ lean = _sine(400)+ lean[:40] = lean[40]+ cases = {(25, 26): "uncertain", (60, 26): "two"}+ assert _verdicts(crossings.read(_sign_walk(lean)), cases) == cases++[email protected]("sig, cases", [+ # Six frames seen, its twin five: longer than the pass it would be — a stance, unconfirmed.+ (dict(n=80, centres=[3, 18, 33, 48, 63], head=6), {(10, 30): "two", (2, 30): "uncertain"}),+ # A pass cut by the first frame, its twin whole, longer and moving like it: a crossing, its middle bounded.+ (dict(n=80, centres=[2, 17, 32, 47, 62]), {(4, 30): "two", (5, 15): "refuted"}),+ # As long as its twin but still: a stance, not a pass (the loop reading counted 4/30 two).+ (dict(n=80, centres=[2, 17, 32, 47, 62], still=((0, 4),)), {(4, 30): "uncertain", (6, 30): "two"}),+])+def test_a_run_the_first_frame_cuts_counts_only_where_its_twin_confirms_it(sig, cases):+ walk = _gap_walk(sig["n"], sig["centres"], still=sig.get("still", ()))+ if "head" in sig:+ walk["gap"][0:sig["head"]] = [0.0] * sig["head"]+ assert _verdicts(crossings.read(walk), cases) == cases+++def test_a_change_the_clip_ends_on_before_the_other_side_is_seen_is_unseen():+ lean = _sine(105)+ lean[100:] = 0.15 # past the axis, short of the tenth of the swing a side needs+ reading = crossings.read(_sign_walk(lean))+ assert _verdicts(reading, {(77, 26): "", (70, 26): ""}) == {(77, 26): "uncertain", (70, 26): "two"}+ assert reading.judge(77, 26)["code"] == "partial"+++# --- the wrap ---------------------------------------------------------------------------------------------------++def test_the_wrap_joins_the_walk_at_its_own_point():+ """Half a cycle (one step), three steps (the stomp of a cut a step and a half too long: the wrap puts the nearer+ foot back), a wrap half a step off, the open first step: only two steps joined in phase are two."""+ sign = crossings.read(_sign_walk(_sine(120)))+ cases = {(19, 13): "refuted", (19, 26): "two", (20, 27): "two", (19, 39): "refuted", (19, 33): "uncertain",+ (19, 20): "uncertain", (0, 26): "uncertain", (1, 26): "uncertain", (6, 26): "two"}+ assert _verdicts(sign, cases) == cases+ assert sign.judge(19, 13)["k"] == [1] and sign.judge(19, 39)["k"] == [3] and sign.judge(19, 33)["code"] == "seam"+ gap = crossings.read(_gap_walk(90, [7, 22, 37, 52, 67, 82]))+ cases = {(10, 30): "two", (7, 30): "two", (8, 28): "two", (6, 32): "two", (22, 16): "refuted", (15, 15): "refuted",+ (0, 45): "refuted", (10, 37): "uncertain"}+ assert _verdicts(gap, cases) == cases+++def test_a_wrap_that_slips_feet_together_in_is_not_two():+ """Wide and narrow steps: 30/38 covers two steps, but its wrap joins the end of a+ pass to its own start, and the loop as played shows three runs of feet together."""+ reading = crossings.read(_gap_walk(90, [7, 27, 42, 62, 82], width=3))+ assert _verdicts(reading, {(30, 38): "", (31, 38): ""}) == {(30, 38): "uncertain", (31, 38): "two"}+ assert reading.judge(30, 38)["code"] == "ring" and reading.judge(30, 38)["ring"] == 3+++def test_phase_is_how_far_the_wrap_is_from_the_walks_own_point_in_frames():+ reading = crossings.read(_sign_walk(_sine(120)))+ assert abs(reading.judge(19, 26)["phase"]) <= 0.5 and reading.in_phase(reading.judge(19, 26))+ assert reading.judge(20, 27)["verdict"] == "two" and 0 < reading.judge(20, 27)["phase"] <= crossings.PHASE_TOLERANCE+++# --- what the reading cannot see, and what it does not read -------------------------------------------------------++def test_noise_at_the_threshold_and_a_wobble_at_the_axis_are_no_steps():+ sig = _gap_walk(110, [7, 22, 37, 82, 97])+ sig["gap"][40:80] = [0.022] * 40+ sig["gap"][50:53] = [0.018] * 3+ sig["gap"][65:68] = [0.018] * 3+ assert crossings.read(sig).judge(45, 30)["verdict"] == "uncertain"+ lean = _sine(300)+ lean[100:160] *= 0.03+ assert crossings.read(_sign_walk(lean)).judge(110, 26)["verdict"] == "uncertain"++[email protected]("hold, verdict", [(4, "two"), (8, "uncertain")])+def test_a_hold_inside_a_step_the_range_absorbs_stays_two(hold, verdict):+ """The limit by design: a 13-frame step held 4 frames is 17, inside the step range — two; held 8, outside."""+ lean = _sine(200)+ lean[60:60 + hold] = lean[59]+ lean[60 + hold:] = _sine(200 - hold)[60:]+ assert crossings.read(_sign_walk(lean)).judge(45, 26 + hold)["verdict"] == verdict+++def test_two_crossings_set_no_step_range():+ reading = _points(60, [20, 40])+ assert not reading.readable and reading.judge(10, 40)["verdict"] == "uncertain"+++def test_a_lean_that_does_not_turn_over_a_step_on_is_not_feet():+ """A body that wobbles about its axis, nothing stepping, changes side now and then, but a step on its lean has+ not turned over: not read, so nothing is counted on it."""+ lean = np.random.default_rng(7).normal(0, 1, 150)+ reading = crossings.read(_sign_walk(lean))+ assert len(reading.crossings) >= 3 and not reading.readable and "does not turn over" in reading.why+ assert reading.judge(10, 40)["code"] == "unread"+ walk = crossings.read(_sign_walk(_sine(120)))+ assert walk.readable and walk.alternation is not None and walk.alternation <= crossings.ALTERNATION_MAX+++def test_a_body_that_never_parts_its_feet_and_never_leans_reads_nothing():+ still = crossings.read({"gap": [0.0] * 60, "lean": [0.0] * 60, "mass": [1.0] * 60})+ assert not still.readable and still.twos(8, 60) == []+++def test_every_two_lies_in_the_lengths_two_steps_can_cover():+ reading = crossings.read(_gap_walk(90, [7, 22, 37, 52, 67, 82]))+ every = [(s, L) for L in range(8, 91) for s in range(91 - L) if reading.judge(s, L)["verdict"] == "two"]+ assert every and all(L in reading.lengths(1, 90) for _, L in every)+ assert [tuple(r["cut"]) for r in reading.twos(1, 90)] == sorted(every, key=lambda c: (c[1], c[0]))+++# --- the signals off the frames -----------------------------------------------------------------------------------++def _frame(drop: float, apart: float) -> Image.Image:+ """A body over two legs: the left foot `drop` px lower than the right, the legs `apart` px apart."""+ im = Image.new("RGBA", (200, 200))+ d = ImageDraw.Draw(im)+ d.rectangle((80, 20, 120, 110), fill=(200, 80, 80, 255))+ d.rectangle((88 - apart / 2, 110, 99 - apart / 2, 170 + drop), fill=(60, 60, 70, 255))+ d.rectangle((101 + apart / 2, 110, 112 + apart / 2, 170), fill=(60, 60, 70, 255))+ return im+++def test_the_foot_bands_lean_and_gap_off_the_frames():+ sig = crossings.foot_signals([_frame(0, 0), _frame(8, 0), _frame(0, 30)])+ assert sig["gap"] == legs.strike_signals([_frame(0, 0), _frame(8, 0), _frame(0, 30)])["gap"]+ assert abs(sig["lean"][0]) < 0.05 and sig["lean"][1] > 0.2 # the lower foot fills the band+ assert sig["gap"][2] >= legs.FEET_APART > sig["gap"][0]+ assert all(m > 0 for m in sig["mass"])+ with pytest.raises(ValueError, match="no solid body"):+ crossings.foot_signals([Image.new("RGBA", (10, 10))])+ assert math.isclose(crossings.SEAM_BAND[1] - crossings.SEAM_BAND[0], math.sqrt(2) - 1 / math.sqrt(2))diff --git a/tests/video/test_explicit_window.py b/tests/video/test_explicit_window.pyindex d20aaf6..cc36cc6 100644--- a/tests/video/test_explicit_window.py+++ b/tests/video/test_explicit_window.py@@ -22,7 +22,7 @@ from tests.video.test_video_pipeline import _one_shot_framesdef _slow(root: Path) -> Path:- return step_clips._keyed(root) # a 42-frame cycle the walk window cuts one step (21) long+ return step_clips._keyed(root) # a 42-frame cycle the walk window holds one step (21) of; its feet pass every 21def _short(root: Path) -> Path:@@ -51,7 +51,9 @@ MOTION = ("--anchor", "motion-auto", "--repair", "off")# path, clip, arguments, what the report shows the path ran, and whether the cut is made at allROWS = [- ("first", _slow, ("--state", "walk", *MOTION, "--max-len", "25"), lambda r: "gait_fallback" not in r, True),+ # A window that holds one step of a walk whose steps are seen: no cut of two steps there, and none of one.+ ("first", _slow, ("--state", "walk", *MOTION, "--max-len", "25"),+ lambda r: "gait_fallback" not in r and r["error"].startswith("no cut of two steps in --max-len 25"), False),("first", _slow, ("--state", "walk", *MOTION, "--min-len", "18"), lambda r: "gait_fallback" not in r, True),("two-step", _held, ("--state", "walk", *MOTION, "--max-len", "25"),lambda r: r["cycle"]["seam_pop"]["held_edge"]["two_step_capped"]["max_len"] == 25, True),diff --git a/tests/video/test_loop_prop_seam.py b/tests/video/test_loop_prop_seam.pyindex c46be8e..470ace4 100644--- a/tests/video/test_loop_prop_seam.py+++ b/tests/video/test_loop_prop_seam.py@@ -20,8 +20,17 @@ import numpy as npimport pytestfrom PIL import Image, ImageDraw+from conftest import feet_unseenfrom sprite_gen.video import local_cycle, loop, repair+[email protected](scope="module", autouse=True)+def _feet_unseen():+ """Every cut in this module is the pixel search's: the walker's legs open and close once a drawing and never pass+ each other, which the step count would read as one step a drawing (tests/conftest.py, `feet_unseen`)."""+ with feet_unseen():+ yield+STEP, SWAY, AMP = 24, 61, 14diff --git a/tests/video/test_loop_prop_seam_held.py b/tests/video/test_loop_prop_seam_held.pyindex 563fe4e..51e9ddd 100644--- a/tests/video/test_loop_prop_seam_held.py+++ b/tests/video/test_loop_prop_seam_held.py@@ -22,8 +22,17 @@ import numpy as npimport pytestfrom PIL import Image, ImageDraw+from conftest import feet_unseenfrom sprite_gen.video import align, local_cycle, loop, repair+[email protected](scope="module", autouse=True)+def _feet_unseen():+ """Every cut in this module is the pixel search's: the walker's legs open and close once a drawing and never pass+ each other, which the step count would read as one step a drawing (tests/conftest.py, `feet_unseen`)."""+ with feet_unseen():+ yield+STEP, SWING, TIP, LOW, PHASE, FRAMES = 24, 48, 14, 14, math.pi / 2, 97diff --git a/tests/video/test_one_step_cut.py b/tests/video/test_one_step_cut.pyindex 5ab7c23..b1e92a3 100644--- a/tests/video/test_one_step_cut.py+++ b/tests/video/test_one_step_cut.py@@ -9,6 +9,10 @@ search finds the step and cuts it: the loop walks on one leg, and its arms jumpcut, read over the whole clip, repeats better than the cut: the screen names it, the cut stays, and`--steps 1` — the count from whoever looked — cuts the cycle.+The screen is the word where the clip does not show its steps: these tests read the walker's feet as unseen+(`crossings.read`), so the search's cut is the pixels' alone. With its feet read the walker is cut two steps long+on the count (tests/video/test_walk_steps.py).+Synthetic frames only; the arm's place is known in closed form, so the tests read the cut against it."""from __future__ import annotations@@ -21,6 +25,7 @@ from pathlib import Pathimport pytestfrom PIL import Image, ImageDraw+from conftest import feet_unseenfrom sprite_gen.video import align, batch, loop, periodCYCLE, FRAMES = 42, 73@@ -50,6 +55,13 @@ def _strider(k: int, cycle: float = CYCLE) -> Image.Image:return im[email protected](scope="module", autouse=True)+def _feet_unseen():+ """Every cut in this module is the pixel search's: the walker's feet are read as unseen."""+ with feet_unseen():+ yield++def _keyed(root: Path, cycle: float = CYCLE, frames: int = FRAMES) -> Path:keyed = root / "keyed"keyed.mkdir(parents=True)diff --git a/tests/video/test_walk_steps.py b/tests/video/test_walk_steps.pynew file mode 100644index 0000000..2e7e5e0--- /dev/null+++ b/tests/video/test_walk_steps.py@@ -0,0 +1,258 @@+# SPDX-License-Identifier: Apache-2.0+"""A walk is cut two steps long — the left foot forward once and the right once — wherever the clip shows its steps+(docs/loop-repair.md section 3, "The step count"; sprite_gen/video/crossings.py, local_cycle.by_steps).++Each walker is drawn so the pixel search alone makes one of the faults a walk loop is cut with:++- a diagonal walk with its legs drawn alike and a tail on its own beat, cut one step long (a half step loop:+ one foot goes forward);+- a walk slower than the search's window, cut one step long;+- a front walk with a big tail on its own beat, cut three steps long by the gait fallback (the wrap puts the+ nearer foot back: a stomp in place);+- a slow front walk in a short clip, refused outright (no periodic cycle found);+- a walk that stalls, its cut playing the stalled step.++A walk the search already cuts two steps long, joined at the walk's own point, is cut exactly as before; a body+whose feet cannot be read is cut as before. Synthetic frames only."""++from __future__ import annotations++import json+import math+import shutil+from pathlib import Path++import numpy as np+import pytest+from PIL import Image, ImageDraw++from conftest import feet_unseen+from sprite_gen.video import align, crossings, local_cycle, loop++FRAMES = 73+++def _side(k: float, *, cycle: float, phase: float = 0, tail_cycle: float = 1, tail: int = 0, arms: bool = True) -> Image.Image:+ """A side or diagonal walker: legs drawn alike, half a cycle apart and seen apart for most of a step; arms opposite,+ the far one darker (`arms`); a tail swinging up and down behind on its own beat (`tail_cycle`, `tail` px long)."""+ ph = 2 * math.pi * (k + phase) / 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)+ if arms:+ d.rectangle((x + 14 - sw - 4, y + 34, x + 14 - sw + 4, y + 72), fill=(150, 150, 150, 255))+ for sign in (1, -1):+ lx = x + 14 + 14 * sign * math.sin(ph)+ d.rectangle((lx - 5, y + 80, lx + 5, y + 126), fill=(60, 60, 70, 255))+ if tail:+ a = 0.8 * math.sin(2 * math.pi * k / tail_cycle)+ d.line((x, y + 50, x - tail * math.cos(a), y + 50 - tail * math.sin(a)), fill=(180, 120, 40, 255), width=12)+ 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))+ if arms:+ d.rectangle((x + 14 + sw - 4, y + 34, x + 14 + sw + 4, y + 72), fill=(225, 225, 225, 255))+ d.point((x + 6, y + 40 + int(k) % 11), fill=(250, 250, 250, 255)) # no two frames the same picture+ return im+++def _front(k: float, *, cycle: float, phase: float = 0, tail_cycle: float = 1, tail: int = 0) -> Image.Image:+ """A walker seen from the front: legs side by side and touching (never seen apart), the nearer foot drawn lower+ each step; arms swinging opposite; a tail swinging sideways at the hips on its own beat."""+ ph = 2 * math.pi * (k + phase) / cycle+ im = Image.new("RGBA", (260, 220))+ d = ImageDraw.Draw(im)+ cx, y = 130, 40 + round(2 * math.cos(2 * ph))+ drop = round(6 * math.sin(ph))+ if tail:+ a = math.sin(2 * math.pi * k / tail_cycle)+ d.line((cx, y + 72, cx + tail * a, y + 90), fill=(180, 120, 40, 255), width=14)+ d.rectangle((cx - 12, y + 80, cx - 1, y + 120 + drop), fill=(60, 60, 70, 255))+ d.rectangle((cx, y + 80, cx + 11, y + 120 - drop), fill=(60, 60, 70, 255))+ d.rectangle((cx - 16, y + 30, cx + 16, y + 84), fill=(200, 80, 80, 255))+ d.rectangle((cx - 12, y, cx + 12, y + 28), fill=(230, 200, 170, 255))+ sw = round(8 * math.sin(ph))+ d.rectangle((cx - 22, y + 34 + sw, cx - 16, y + 70 + sw), fill=(225, 225, 225, 255))+ d.rectangle((cx + 16, y + 34 - sw, cx + 22, y + 70 - sw), fill=(225, 225, 225, 255))+ d.point((cx - 6, y + 40 + int(k) % 11), fill=(250, 250, 250, 255))+ return im+++def _blob(k: int) -> Image.Image:+ """A legless body bouncing every 16 frames: one foot band, nothing to step."""+ im = Image.new("RGBA", (200, 200))+ h = 60 + round(8 * math.cos(2 * math.pi * k / 16))+ ImageDraw.Draw(im).ellipse((70, 170 - h, 130, 170), fill=(90, 160, 220, 255))+ ImageDraw.Draw(im).point((90, 150 - k % 9), fill=(250, 250, 250, 255))+ return im+++def _keyed(root: Path, draw, frames: int = FRAMES, hold: tuple[int, int] | None = None) -> Path:+ """The walker's frames; `hold` (from, frames) holds the walk still that long at `from`."""+ keyed = root / "keyed"+ keyed.mkdir(parents=True)+ for k in range(frames):+ t = k if hold is None or k < hold[0] else hold[0] if k < hold[0] + hold[1] else k - hold[1]+ draw(t).save(keyed / f"{k:03}.png")+ return keyed+++def _cut(out: Path, keyed: Path, *extra: str) -> dict:+ assert loop.main(["--frames-dir", str(keyed), "--out-dir", str(out), "--state", "walk",+ "--anchor", "motion-auto", "--repair", "off", *extra]) == 0+ return json.loads((out / "loop.loop.report.json").read_text())+++def _two_steps(report: dict, cycle: float) -> dict:+ """The cut covers two steps by the clip's crossings — one cycle of the walker, `cycle` frames — and says so."""+ c = report["cycle"]+ counted = c["step_count"]+ assert counted["readable"] and counted["chosen_by"] == "two steps" and c["method"] == "observed-two-steps-v1"+ assert counted["cut"]["verdict"] == "two" and counted["cut"]["k"] == [2] and counted["cut"]["ring"] == 2+ assert abs(counted["cut"]["phase"]) <= crossings.PHASE_TOLERANCE+ assert abs(c["length"] - cycle) <= 1.5+ assert c["steps"] == {"count": 2, "by": "crossings"}+ assert report["status"] == "passed"+ return counted+++def test_a_half_step_diagonal_walk_is_cut_two_steps(tmp_path):+ """Legs drawn alike, 14.5 frames a step, a tail on a 45-frame beat: one step on, the legs are swapped and the+ tail is nearer where it was than a cycle on, so the search takes 14 frames — one foot goes forward. The+ crossings count it one step; the cut is two."""+ report = _cut(tmp_path / "out", _keyed(tmp_path, lambda k: _side(k, cycle=29, tail_cycle=45, tail=60, arms=False)))+ counted = _two_steps(report, 29)+ assert counted["mode"] == "gap" and counted["step_range"][1] == 14.5+ assert counted["search"]["verdict"] == "refuted" and counted["search"]["k"] == [1] and counted["search"]["cut"][1] in (14, 15)+ strip = 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.+ screen = report["cycle"]["step_screen"]+ assert screen["suspect"] is False and (screen.get("settled_by") == "crossings" or "pixel_suspect" not in screen)+++def test_a_walk_slower_than_the_window_is_cut_two_steps(tmp_path):+ """A 46-frame cycle (1.92 s) in a 73-frame clip: past the window's 36, so the search cut a 23-frame step. Two+ steps are 46 frames, and the clip holds 0.59 of a cycle past them."""+ report = _cut(tmp_path / "out", _keyed(tmp_path, lambda k: _side(k, cycle=46, phase=13)))+ counted = _two_steps(report, 46)+ assert report["window"][1] < report["cycle"]["length"]+ assert counted["search"]["k"] == [1]+ assert report["cycle"]["coverage"] == round((FRAMES - report["cycle"]["length"]) / report["cycle"]["length"], 4) > loop.COVERAGE_MIN+++def test_a_tail_on_its_own_beat_no_longer_cuts_three_steps(tmp_path):+ """A front walk, 13.5 frames a step, its big tail on a 41-frame beat: the search refuses the walk's 27 frames+ (repeat error over two steps), and the gait fallback takes the tail's 41 — three steps, the wrap putting the+ nearer foot back: a stomp in place. The crossings count three and cut two."""+ report = _cut(tmp_path / "out", _keyed(tmp_path, lambda k: _front(k, cycle=27, phase=5, tail_cycle=41, tail=70)))+ counted = _two_steps(report, 27)+ assert counted["mode"] == "sign" and counted["alternation"] <= crossings.ALTERNATION_MAX+ assert "gait_fallback" in report and counted["search"]["k"] == [3] and counted["search"]["cut"][1] in (40, 41, 42)+++def test_a_slow_walk_in_a_short_clip_the_search_refuses_is_cut_two_steps(tmp_path):+ """A 34-frame front walk with a tail on a 52-frame beat: no window repeats within two steps of its own, so the+ search and the gait fallback find no cycle. The crossings show two."""+ report = _cut(tmp_path / "out", _keyed(tmp_path, lambda k: _front(k, cycle=34, phase=5, tail_cycle=52, tail=70)))+ counted = _two_steps(report, 34)+ assert counted["search"]["refused"].startswith("no periodic cycle found")+++def test_a_walk_that_stalls_is_not_cut_across_the_stalled_step(tmp_path):+ """A side walk held still 20 frames: the step the hold is in is far longer than the walk's own, and no frame of+ it is played (the search's cut played its last frames, and its seam did not close)."""+ report = _cut(tmp_path / "out", _keyed(tmp_path, lambda k: _side(k, cycle=29, phase=3), frames=96, hold=(30, 20)))+ counted = _two_steps(report, 29)+ c = [x if isinstance(x, (int, float)) else x[1] for x in counted["crossings"]]+ hi = counted["step_range"][2]+ stalled = [(a, b) for a, b in zip(c, c[1:]) if b - a > hi]+ assert stalled == [(26.0, 60.5)]+ s, L = report["cycle"]["start"], report["cycle"]["length"]+ assert s + L - 1 < 26 or s > 60.5+ assert counted["search"]["code"] == "step-long"+++def _same_cut(a: Path, b: Path) -> None:+ for name in ("loop.strip.png", "loop.gif", "loop.webp"):+ assert (a / name).read_bytes() == (b / name).read_bytes(), name+ frames = sorted(p.name for p in (a / "cycle").glob("*.png"))+ assert frames and frames == sorted(p.name for p in (b / "cycle").glob("*.png"))+ assert all((a / "cycle" / f).read_bytes() == (b / "cycle" / f).read_bytes() for f in frames)+++def test_a_walk_the_search_cuts_two_steps_in_phase_is_cut_as_before(tmp_path):+ """The same front walk with a small tail: the search cuts its 27 frames, two steps joined at the walk's own point,+ and the cut is kept — every image as the search alone cut it; the strip says `steps: 2`."""+ keyed = _keyed(tmp_path, lambda k: _front(k, cycle=27, phase=5, tail_cycle=41, tail=40))+ report = _cut(tmp_path / "read", keyed)+ counted = report["cycle"]["step_count"]+ assert counted["chosen_by"] == "search" and counted["cut"]["verdict"] == "two"+ assert report["cycle"]["method"] == "local-repeat-drift-v1" and report["cycle"]["steps"] == {"count": 2, "by": "crossings"}+ with feet_unseen():+ plain = _cut(tmp_path / "unread", keyed)+ assert (plain["cycle"]["start"], plain["cycle"]["length"]) == (report["cycle"]["start"], report["cycle"]["length"])+ _same_cut(tmp_path / "read", tmp_path / "unread")+ strips = [json.loads((tmp_path / d / "loop.strip.json").read_text()) for d in ("read", "unread")]+ assert strips[0].pop("steps") == 2 and "steps" not in strips[1] and strips[0] == strips[1]+++def test_a_body_with_no_feet_to_read_is_cut_as_the_search_cuts_it(tmp_path):+ keyed = _keyed(tmp_path, _blob, frames=64)+ report = _cut(tmp_path / "out", keyed)+ counted = report["cycle"]["step_count"]+ assert counted["readable"] is False and counted["chosen_by"] == "search" and counted["why"]+ assert counted["search"]["cut"] == [report["cycle"]["start"], report["cycle"]["length"]]+ assert "steps" not in report["cycle"] and "steps" not in json.loads((tmp_path / "out" / "loop.strip.json").read_text())+++def test_a_count_given_is_the_word_on_the_searchs_cut(tmp_path):+ """--steps counts the cut the search takes: the crossings are not asked."""+ report = _cut(tmp_path / "out", _keyed(tmp_path, lambda k: _side(k, cycle=46, phase=13)), "--steps", "2")+ assert "step_count" not in report["cycle"] and report["cycle"]["steps"]["by"] == "given"+ assert report["cycle"]["length"] in (22, 23, 24) # the search's one step, kept on the count+++def test_cycle_align_takes_a_loop_cut_two_steps_as_one_cycle(tmp_path):+ """The half-step walk cut two steps long returns half way at its second step; its loop says `steps: 2`, so the+ alignment reads that return as its step, and the set aligns."""+ _cut(tmp_path / "a", _keyed(tmp_path / "ka", lambda k: _side(k, cycle=29, tail_cycle=45, tail=60, arms=False)))+ _cut(tmp_path / "b", _keyed(tmp_path / "kb", lambda k: _side(k, cycle=46, phase=13)))+ dirs = []+ for name in ("a", "b"):+ shutil.copytree(tmp_path / name, tmp_path / "set" / name)+ dirs.append(tmp_path / "set" / name)+ out = align.align_set(dirs, between="nearest")+ assert out["applied"] is True+ assert all(entry["status"] == "steps" for entry in out["suspects"])+++def _distances(period: int = 13, frames: int = 120) -> np.ndarray:+ t = np.arange(frames)+ angle = t * 2 * np.pi / period+ points = np.column_stack([np.cos(angle), np.sin(angle)])+ return np.abs(points[:, None] - points[None, :]).mean(axis=2).astype(np.float32)++[email protected]("uncertain_from", [None, 5])+def test_the_search_refuses_what_the_crossings_refute_and_names_their_count(uncertain_from):+ """`detect` with `judge`: a window the crossings count other than two is refused, and a search that finds nothing+ lists each refused window's count, those the crossings refute after the rest."""+ def judge(s, L):+ if uncertain_from is not None and s >= uncertain_from:+ return {"verdict": "uncertain", "code": "partial", "k": [], "why": "plays frames no crossing confirms"}+ return {"verdict": "refuted", "code": "refuted", "k": [1], "why": "one step, each seen"}++ D = _distances()+ if uncertain_from is not None:+ found = local_cycle.detect(D, np.zeros(len(D)), min_len=12, max_len=14, gait_floor=8, periodicity_min=loop.PERIODICITY_MIN,+ double_tolerance=loop.GAIT_DOUBLE_TOL, double_search=loop.GAIT_DOUBLE_SEARCH, judge=judge)+ assert found["start"] >= uncertain_from+ return+ with pytest.raises(ValueError, match="no periodic cycle found") as refused:+ local_cycle.detect(D, np.zeros(len(D)), min_len=12, max_len=14, gait_floor=8, periodicity_min=loop.PERIODICITY_MIN,+ double_tolerance=loop.GAIT_DOUBLE_TOL, double_search=loop.GAIT_DOUBLE_SEARCH, judge=judge)+ shown = refused.value.diagnostics["candidates"]+ assert shown and all(row["step_count"]["verdict"] == "refuted" for row in shown)+ assert any("one step, each seen in the clip's crossings" == row["refused"] for row in shown)+ assert "refute after the rest" in refused.value.diagnostics["order"]