Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
fix(video): a slow walk cut one step long is named and cut again on a count; a two-step cut is one cycle
Soohong Kim075a3329bd91
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 880fe7e..b06b192 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,12 +2,16 @@All notable public changes to `sprite-gen` are recorded here. Versions track the `version:` field in `SKILL.md` and `pyproject.toml`.-## Unreleased - A staff that closes at the top and swings below the hand is cut two steps long--- **Output change: once the top of the silhouette jumps at its first choice, `video-loop --anchor motion-auto` reads the held part below its top too, and may cut two steps long.** A staff that turns about the hand once in two steps comes back to the same place at the top band half its turn later, moving the other way: v2.35.0 chose again on the top band alone, took such a cut — the top closed — and the shaft under the hand swung back at the wrap, with no warning. Now, behind the seam pop only, the side of the body the top band sits on is read row by row on the silhouette's outer edge (`repair.held_side`, `repair.side_edges`, `repair.held_edge` on the frames the search chooses from, `loop.HeldEdge`): per row, the cut's first and last frames against the clip's frames after its last and before its first, in place and in speed, over the row's median step in the loop; the 80th percentile over the rows is the held seam, closing under **1.2** (`repair.HELD_EDGE_REFERENCE`). Among the candidates whose top does not jump, one whose held side closes is taken (the usual 15 % of the best score, then the smallest held seam). Where no cut one step long closes it, windows twice a candidate's length are read — two cycles of a confirmed repeat, not themselves seen repeating — and one whose held side closes and whose top does not jump is cut: the report's `cycle.cycles` is `2`, and `strip.json` carries `cycles: 2`. A cut with fewer than two clip frames either side of it cannot be read: `skipped`, counted under `unread`, never chosen. An explicit `--max-len` stays the cut's ceiling: windows two steps long over it are not read (`two_cycle_capped`: `max_len`, `lengths_over`); the state's default window is no ceiling. `cycle.seam_pop.held_edge` records `side`, `reference`, `measured`, `unread`, `cycles`, `chosen` and `two_cycle` (lengths tried, `measured`, `unread`, `top_pops`, `closing`); a candidate row carries `held_edge` (`null` with `held_edge_skipped`). A first choice whose top does not jump reads nothing new: a walk without a part held above its head is cut, written and warned about byte for byte as before. [docs/loop-repair.md](docs/loop-repair.md#the-held-side--a-staff-that-closes-at-the-top-and-swings-below-the-hand).-- **New warning: a held part that no window one or two steps long closes.** The top band's cut stands and `jolt.warnings` and stderr gain `the held part does not close at the wrap on the <side> side of the silhouette, below its top: …x its rows' median step (over 1.2); no window one or two cycles long closes it — it swings on a beat of its own` (or, where `--max-len` kept windows two steps long from being read, `no window one cycle long closes it, and windows two cycles long (…-… frames) are over --max-len N, so they were not read`); a held side that could not be read is said as well. Nothing fails on it.-- **Output change: `video-cycle-align` keeps a loop cut two steps long on purpose two steps long.** A loop whose `strip.json` says `cycles: 2` is not stopped as a suspect (its suspects carry `status: "declared"`), counts half its length toward the set's length, and is resampled to twice that length; its row and its `strip.json` `cycle_align` carry `cycles_kept`. Before, the screen stopped the set on it, and `--cycles <loop>=2` cut the held part's wrap back in while `=1` played it twice as fast. A `--cycles` count given for it is still the last word. Every loop without `cycles` in its `strip.json` is aligned as before, its row, `strip.json` and cells byte for byte (no `cycles_kept`).-- **`tests/video/test_loop_prop_seam_held.py`** draws a walker stepping every 24 frames with a staff turning about the hand every 48: v2.35.0 cuts it one step long where the top closes and the staff's foot swings back at the wrap at twice its largest step inside the loop; now every cut one step long whose top closes reads a held seam of 2.0 to 5.2, and the window two steps long taken reads 0. A staff swinging with the step below a pennant that sways on its own beat stays one step long (0 to 0.5); a staff whose foot swings every 37 frames is kept on the top band's cut and warned about; a walk without a staff reads nothing below its top; the set alignment keeps the two-step loop at twice the set's length. With `--max-len 25` the staff walker is cut one step long and warned about, and two loops without a staff are aligned with exactly the `strip.json` and `cycle_align` keys v2.35.0 wrote.+## Unreleased - A slow walk cut one step long is named, and cut again on a count; a staff that closes only on two steps is cut as one cycle++- **New record: `cycle.step_screen` on every walk and run `video-loop --anchor motion-auto` cuts.** A walk slower than its window holds (0.5 to 1.6 s, at most half the clip) is cut one step long where its legs are drawn alike: the step repeats in pixels, the loop walks on one leg, its arms jump at the wrap, and a set aligned with it plays one step where its other directions play two. Nothing said so — the two-cycle screen looks only below the cut. Now the cut is screened the other way, over the whole clip (`period.step_screen`): the lag within 3 frames of twice the cut that repeats best (`lag`, `searched`), its distance over the cut's own over the same frames (`ratio`, `pairs`), its dip under the clip's profile (`depth`), how much of a second cycle the clip holds past it (`coverage`), and the step signal's peaks over the cut (`leg_peaks`, a record only). A repeat there (`depth` at least 0.15) better than at the cut (`ratio` at most **0.85**, `period.STEP_RATIO_MAX`) is a `suspect`. **Nothing is cut on it**: a cycle on a frame count that is not whole repeats better at its double too, so only a count of the steps settles it. Images, `strip.json`, warnings and stderr are as before, byte for byte; the report's `cycle` and the printed summary gain `step_screen`. [docs/loop-repair.md](docs/loop-repair.md#the-step-screen--a-slow-walk-cut-one-step-long).+- **New option: `video-loop --steps 1|2`** (with `--anchor motion-auto`), the count of steps in the cut it takes without it, from whoever looked at the loop. `1` cuts the walk again in the window [2L − 1, 2L + 1] — not bounded by half the clip — with the same search, the equivalent cut whose wrap the clip itself plays taken (`choice: "closure"`) and no window twice that; a clip too short to see that window repeat is cut all the same, the count standing for the repeat (`method: "counted-window-v1"`, `unseen`). `2` keeps the cut. Either way `cycle.steps` records the count (`by: "given"`, `given`, and for `1` `first_cut` and `window`), `strip.json` says `steps: 2`, and `cycle.coverage` is (n − L) / L. **New warning**: a cut two steps long whose clip holds under 0.25 of a cycle past it (`loop.COVERAGE_MIN`) — `the cut is two steps long (… frames, one cycle) and the clip holds … of a cycle past it (under 0.25): its repeat is barely seen — the seam says whether it closes; a longer take shows it repeat`. It is cut, not refused; the seam gate judges it.+- **Output change: an explicit `--min-len`/`--max-len` window is the window.** `--anchor motion-auto` cut the caller's ceiling back to half the clip, so asking for a slow walk's cycle (`--min-len 41 --max-len 43` on 73 frames) searched [41, 36] and failed. Only the state's default window is bounded by half the clip now.+- **Output change: once the top of the silhouette jumps at its first choice, `video-loop --anchor motion-auto` reads the held part below its top too, and may cut two steps long — one cycle.** A staff turns about the hand as the arm swings, once a cycle; one step on it is back in place at the top band moving the other way. Where the legs are drawn alike the search takes that step as the cycle: v2.35.0 chose again on the top band alone, took such a cut — the top closed — and the shaft under the hand swung back at the wrap, with no warning. Now, behind the seam pop only, the side of the body the top band sits on is read row by row on the silhouette's outer edge (`repair.held_side`, `repair.side_edges`, `repair.held_edge` on the frames the search chooses from, `loop.HeldEdge`): per row, the cut's first and last frames against the clip's frames after its last and before its first, in place and in speed, over the row's median step in the loop; the 80th percentile over the rows is the held seam, closing under **1.2** (`repair.HELD_EDGE_REFERENCE`). Among the candidates whose top does not jump, one whose held side closes is taken (the usual 15 % of the best score, then the smallest held seam). Where none closes, windows twice a candidate's length are read — two steps of a confirmed repeat, one cycle, not themselves seen repeating — and one whose held side closes and whose top does not jump is cut: `cycle.steps` is `{"count": 2, "by": "held-edge", "step_lengths": [...]}` (the candidates it is two of, each one step), `cycle.period_local` its own length, `cycle.coverage` recorded, and `strip.json` says `steps: 2`. A cut with fewer than two clip frames either side of it cannot be read: `skipped`, counted under `unread`, never chosen. An explicit `--max-len` stays the cut's ceiling (`two_step_capped`: `max_len`, `lengths_over`), and counted steps read nothing twice as long. `cycle.seam_pop.held_edge` records `side`, `reference`, `measured`, `unread`, `doubled`, `chosen` and `two_step` (`read`, lengths tried, `measured`, `unread`, `top_pops`, `closing`); a candidate row carries `held_edge` (`null` with `held_edge_skipped`). A first choice whose top does not jump reads nothing new. [docs/loop-repair.md](docs/loop-repair.md#the-held-side--a-staff-that-closes-at-the-top-and-swings-below-the-hand).+- **New warning: a held part that no window one or two lengths long closes.** The top band's cut stands and `jolt.warnings` and stderr gain `the held part does not close at the wrap on the <side> side of the silhouette, below its top: …x its rows' median step (over 1.2); no window one or two lengths long closes it — it swings on a beat of its own` (or, where `--max-len` kept the longer windows from being read, `no window one length long closes it, and windows two lengths long (…-… frames) are over --max-len N, so they were not read`; where the steps were counted, `no window of the counted length closes it`); a held side that could not be read is said as well. Nothing fails on it.+- **Output change: `video-cycle-align` reads a loop's steps, and stops on a loop that may be one step.** A loop whose `strip.json` says `steps: 2` returns half way at its second step: that suspect is recorded `status: "steps"` (with `steps`) and does not stop the set, and the loop is resampled to the set's length like the rest; `--cycles <loop>=2` on it takes one half out and drops `steps`. A loop whose cut's report (beside the loop, or one directory up for a `video-set` item: `align.cut_report`) has `cycle.step_screen.suspect`, and whose steps nobody counted, is a suspect too (`one_step`: `length`, `lag`, `seconds`, `ratio`, `depth`, `pairs`, `coverage`, `leg_peaks`, `why`, `report`): stopped under `--multi-cycle fail` with its name and `cut it again with sprite-gen video-loop … --steps 1`, aligned and warned about under `warn`; `--cycles <loop>=1` says it holds a whole cycle. Every loop with neither is aligned as before, its row, `strip.json` and cells byte for byte.+- **`video-set`**: an item whose cut's steps are known carries `loop.steps`, one the step screen suspects `loop.step_screen` (`lag`, `ratio`, `depth`, `coverage`), and `table.md` says so in the cycle column (`46 (2 steps)`, `21 (one step?)`); a state stopped on a loop that may be one step says `<item> may be one step (cut it again with video-loop --steps 1 if it is)`. A cut two steps long now carries `ratio` like any candidate, which the item reads.+- **`tests/video/test_one_step_cut.py`** draws a side walker with a 42-frame cycle, legs alike and arms shaded apart, over 73 frames: v2.35.0 cuts it at 21 and says nothing; now the cut is the same and the step screen names it (`ratio` 0.48), the same drawing on 25 and 23.5 frames is written byte for byte as with no screen (23.5 a suspect that is a cycle), `--steps 1` cuts 15/42 where the arm's wrap is 0 against 7.6 for the step, `--steps 2` keeps the cut, a 50-frame clip is cut 8/42 and warned about its coverage, `--min-len 41 --max-len 43` is the window, and the set alignment stops on the step and aligns its re-cut. **`tests/video/test_loop_prop_seam_held.py`** draws a walker whose legs come back every 24 frames with a staff turning about the hand every 48: every cut one step long whose top closes reads a held seam of 2.0 to 5.2, and the window two steps long taken reads 0 and is aligned at the set's length as one cycle. A staff swinging with the step below a pennant that sways on its own beat stays one step long; a staff whose foot swings every 37 frames is kept on the top band's cut and warned about; a walk without a staff reads nothing below its top; two loops without a staff are aligned with exactly the `strip.json` and `cycle_align` keys v2.35.0 wrote.## v2.35.0 - A staff that swings on its own beat is not cut where it jumpsdiff --git a/SKILL.md b/SKILL.mdindex 250b35d..730ede0 100644--- a/SKILL.md+++ b/SKILL.md@@ -138,4 +138,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 takes the nearer source frame) 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), 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 where a staff held above the head closes only there (`cycle.cycles: 2`, and `video-cycle-align` keeps both cycles at twice the set's length — do not count it down with `--cycles`). 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 takes the nearer source frame) 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), 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").diff --git a/docs/loop-repair.md b/docs/loop-repair.mdindex 94b5a31..c1d0d63 100644--- a/docs/loop-repair.md+++ b/docs/loop-repair.md@@ -304,10 +304,12 @@ plays:### The held side — a staff that closes at the top and swings below the hand-A staff that turns about the hand once in two steps comes back to the same place at the top band-half its turn later, moving the other way. A cut one step long taken there closes the top —-`seam_pop` reads nothing — and the shaft under the hand swings back at the wrap. No cut one step-long closes such a staff; a cut two steps long does.+A staff turns about the hand as the arm that holds it swings: once a cycle, two steps. One step on+it is back in the same place at the top band, moving the other way. Where the legs are drawn alike+the search reads that step as the cycle (the legs are back in place, near and far swapped), and a+cut one step long taken there closes the top — `seam_pop` reads nothing — while the shaft under the+hand swings back at the wrap. No cut one step long closes such a staff; a cut two steps long — the+cycle — does.Nothing that reads the whole silhouette sees it on its own. On a walk without a held part thesilhouette's outer edges are hair, an arm or a foot, and a local jump at the wrap — read per tile,@@ -330,36 +332,41 @@ A cut with fewer than two clip frames on either side has nothing to read its wra`skipped` (why), counted under `unread`, and never chosen.`--anchor motion-auto`, once its first choice pops (`cycle.seam_pop.held_edge`: `side`, `reference`,-`measured`, `unread`, `cycles`, `chosen`, and `two_cycle` when it looked there):+`measured`, `unread`, `doubled`, `chosen`, and `two_step` when it looked there):1. Among the candidates whose top does not pop, those whose held side closes: the scores within the- usual 15 % of the best, then the smallest held seam (`cycles: 1`). A candidate row carries+ usual 15 % of the best, then the smallest held seam (`doubled: false`). A candidate row carries`held_edge` (`null` with `held_edge_skipped` where it could not be read).-2. If no candidate one step long closes it: **windows twice a candidate's length** (every length- 2L − 1 to 2L + 1 for a candidate length L, at every start the clip holds). Such a window is two- cycles of a repeat the search confirmed, not itself seen repeating — a three-second clip cannot- show a window two steps long twice. One whose held side closes and whose top does not pop (a top- that cannot be read is not taken) is cut, the smallest held seam first: `cycle.cycles` is **2**,- `cycle.period_local` half its length, `cycle.seam_pop.chosen.cycles` 2 and `strip.json` `cycles: 2`.- `two_cycle` records the lengths tried and how many were `measured`, `unread`, `top_pops` and- `closing`. An explicit `--max-len` is the caller's ceiling on the cut and stays one: a window two- steps long over it is not read (`two_cycle_capped`: `max_len`, `lengths_over`), and where every- such length is over it, nothing two steps long is read at all. The state's default window is no- ceiling here: without `--max-len` every length is read.-3. If no window one or two steps long closes it, the top band's choice stands (as above),+2. If no candidate closes it: **windows twice a candidate's length** (every length 2L − 1 to 2L + 1+ for a candidate length L, at every start the clip holds). The candidate was one step; such a+ window is two — **one cycle** — of a repeat the search confirmed, not itself seen repeating: a+ three-second clip cannot show a window that long twice. One whose held side closes and whose top+ does not pop (a top that cannot be read is not taken) is cut, the smallest held seam first+ (`doubled: true`). The report says what it is: `cycle.steps` is `{"count": 2, "by": "held-edge",+ "step_lengths": [...]}` — the candidate lengths it is two of, each one step — `cycle.period_local`+ is its own length (it is screened as the one cycle it is), `cycle.coverage` says how much of a+ second cycle the clip holds past it ("The step screen" below), `cycle.seam_pop.chosen.steps` is 2+ and `strip.json` says `steps: 2`, which the set alignment reads (section 4). `two_step` records+ the lengths tried and how many were `measured`, `unread`, `top_pops` and `closing`. An explicit+ `--max-len` is the caller's ceiling on the cut and stays one: a window two lengths long over it is+ not read (`two_step_capped`: `max_len`, `lengths_over`), and where every such length is over it,+ nothing two lengths long is read at all. The state's default window is no ceiling here: without+ `--max-len` every length is read.+3. If no window one or two lengths long closes it, the top band's choice stands (as above),`held_edge.chosen` records its seam, and `jolt.warnings` and stderr gain`video-loop: warning: the held part does not close at the wrap on the right side of the- silhouette, below its top: 5.50x its rows' median step (over 1.2); no window one or two cycles- long closes it — it swings on a beat of its own`. Where `--max-len` kept windows two steps long- from being read, the line ends `no window one cycle long closes it, and windows two cycles long- (47-49 frames) are over --max-len 25, so they were not read` instead. A side that could not be- read is said as well.+ silhouette, below its top: 5.50x its rows' median step (over 1.2); no window one or two lengths+ long closes it — it swings on a beat of its own`. Where `--max-len` kept windows two lengths long+ from being read, the line ends `no window one length long closes it, and windows two lengths long+ (47-49 frames) are over --max-len 25, so they were not read` instead; where the steps were counted+ (`--steps`, below), `no window of the counted length closes it`. A side that could not be read is+ said as well.A first choice whose top does not pop reads nothing here: a walk without a part held above its headis cut, written and warned about exactly as before.The bound sits between cuts that close a held staff and cuts where it swings back at the wrap. The-synthetic walker of `tests/video/test_loop_prop_seam_held.py` — steps every 24 frames, a staff+synthetic walker of `tests/video/test_loop_prop_seam_held.py` — legs back every 24 frames, a staffturning about the hand every 48 — reads 2.0 to 5.2 at every cut one step long whose top closes and0 at the window two steps long taken; with the staff swinging every step instead it reads 0 to 0.5,and the cut stays one step long. Below a staff on a beat neither one step nor two closes (every 37@@ -369,8 +376,77 @@ closes: the top band's cut stands, and it is warned about.- **What it does not see**: a held part on the other side of the body from the top band (the topband names the side), and a held part whose cut needs more than two steps. A window two steps longneeds the clip to hold it with two frames either side: a three-second clip of 30-frame steps has- few starts for one. `--cycle fixed` cuts any window ([loop review](loop-review.md)); a two-step- cut made that way is not marked `cycles: 2`, and the set alignment asks for its count.+ few starts for one. A one-step cut without a held part above the head is the step screen's+ (below). `--cycle fixed` cuts any window ([loop review](loop-review.md)); a two-step cut made that+ way carries no `steps`, and the set alignment asks for its count.++### The step screen — a slow walk cut one step long++The walk window is 0.5 to 1.6 s, and at most half the clip: a cycle has to be seen repeating. A+slow walk can take longer than that a cycle, and then its cycle is outside the window. Where the legs are drawn alike, one step on they are back in place with near and far+swapped, so the search finds the step as the repeat and cuts it. The loop walks on one leg: its arms+— and anything they hold — jump at the wrap, a set aligned with it plays one step where the other+directions play two, and nothing said so: the two-cycle screen looks only below the cut ("The+fundamental period", [video pipeline](video-pipeline.md) section 4), and the gait fallback's longer+window runs only when the first search finds nothing.++`--anchor motion-auto` screens the cut it takes the other way, over the whole clip rather than the+window (`cycle.step_screen`, `period.step_screen`):++| Field | What |+|---|---|+| `lag` | within 3 frames of twice the cut (`searched`), the lag whose mean distance over the clip is least (at least 4 frame pairs) |+| `pairs`, `ratio` | over every frame with both lags in the clip, the distance `lag` on over the distance one cut on |+| `depth` | how far `lag` dips under the clip's lag profile from half the cut up |+| `coverage` | (n − `lag`) / `lag`: how much of a second cycle the clip holds past one of that length |+| `leg_peaks` | the step signal's peaks over the cut (`legs.step_signal`, read as a ring) — a record only, never decided by |+| `suspect`, `why` | a repeat at `lag` (`depth` at least 0.15, `periodicity_min`) that is better than at the cut (`ratio` at most **0.85**, `period.STEP_RATIO_MAX`) |++A true cycle repeats about as well a cycle on as at its own length (its drift makes the longer lag a+little worse: `ratio` 1.0 and up); a step repeats better two cut lengths on, where the arms come+back too. **Nothing is cut on it.** Pixels cannot tell a step from a cycle on a frame count that is+not whole — a cycle of 23.5 frames cut at 24 repeats better at 47, being whole there — so the screen+only names the cut, and the count comes from whoever looks at the loop (how often each foot lands:+by eye, or a vision call). Its images, `strip.json`, warnings and stderr are what they were without+it; the report's `cycle`, and the summary `video-loop` prints, gain `step_screen`. A twice-the-cut+lag past the clip (fewer than 4 pairs) is not read: `lag` null, not a suspect. The synthetic walker+of `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.++**`video-loop --steps 1|2`** is the count coming back, with `--anchor motion-auto`: how many steps+the cut it takes without `--steps` holds.++- **`--steps 1`**: the cut is one step, so the walk is cut again two of its lengths long. The+ window is [2L − 1, 2L + 1] for the cut's length L, as given — not bounded by half the clip — and+ searched as any window (a repeat seen in the clip, the top band and the held side read again, but+ no window twice that); among the equivalent cuts the one whose wrap the clip itself plays is taken+ (`choice: "closure"`: its last frame against the clip's frame before its first, and the step into+ it, over its playback step), not the earliest. A clip too short to see a window that long repeat is+ cut all the same — the count stands for the repeat — at the window whose wrap the clip plays+ (`method: "counted-window-v1"`, `unseen` saying why the search found none). `cycle.steps` is+ `{"count": 2, "by": "given", "given": 1, "first_cut": {start, length}, "window": [lo, hi]}`.+- **`--steps 2`**: the cut is a cycle already; it is kept, and recorded `{"count": 2, "by":+ "given", "given": 2}`.++Either way `strip.json` says `steps: 2` and the report records `cycle.coverage`, (n − L) / L. A cut+two steps long whose clip holds under **0.25** of a cycle past it (`loop.COVERAGE_MIN`) is cut and+warned about, not refused: `the cut is two steps long (42 frames, one cycle) and the clip holds 0.19+of a cycle past it (under 0.25): its repeat is barely seen — the seam says whether it closes; a+longer take shows it repeat`. Whether it closes is the seam gate's word, as for any cut. On the+synthetic walker `--steps 1` cuts 15/42, the arm's wrap 0 where the one-step cut's was 7.6 times+its largest step inside the loop; at 50 frames the counted window 8/42 (coverage 0.19) is cut and+warned about.++An explicit `--min-len`/`--max-len` window is the window as given too: the half-clip bound holds+only for the state's default window. v2.35.0 cut it back, so `--min-len 41 --max-len 43` on a+73-frame clip asked for the window [41, 36] and found no cycle.++- **What it does not see**: a walk whose arms are drawn alike as well — then a step is a cycle in+ every pixel and `ratio` reads 1; a cut whose twice is past the clip; and a cut on any path but+ `--anchor motion-auto` (`--steps` needs it). A set loop whose cut's report is not beside it is not+ screened at the set stage (section 4).## 4. One cycle for a direction set — `video-cycle-align`, `video-set --align-cycles auto`@@ -385,15 +461,26 @@ sprite-gen video-cycle-align --loop-dir set/front-walk/loop --loop-dir set/side-[--foot side-walk=left] [--state walk] [--report set/walk.cycle-align.json]```-- **A loop cut two steps long on purpose is counted already.** `video-loop --anchor motion-auto`- cuts two steps where a held part closes only there (section 3, "The held side") and marks it- `cycles: 2` in `strip.json`. The alignment does not stop on it: its length counts per cycle toward- the set's length, and it is resampled to twice that length, keeping both cycles (`cycles_kept` on- its row and in its `strip.json` `cycle_align`; its suspects carry `status: "declared"`). Only a- loop whose `strip.json` declares `cycles` gets `cycles_kept`: every other loop's row, `strip.json`- and cells are written as before, byte for byte. A- `--cycles` count given for it is still the last word: `--cycles <loop>=2` takes one cycle out of- it (the held part then swings back at that cut's wrap), `=1` aligns it at the set's length.+- **A loop whose steps are counted is one cycle.** A cut two steps long — taken so a held part+ closes (section 3, "The held side") or cut again on a count (`video-loop --steps`, "The step+ screen") — says `steps: 2` in `strip.json`. It returns half way, at its second step, and that+ return is no second cycle: the suspect it makes is recorded with `status: "steps"` (its `steps`,+ its `candidates`) and does not stop the set, and the loop is resampled to the set's length like+ every other. A `--cycles` count given for it is still the last word: `--cycles <loop>=2` takes one+ half out of it (one step — its `steps` is dropped from `strip.json`), `=1` aligns it as it is.+- **A loop that may be one step is stopped too.** Nothing in the loop shows it — its next step is not+ in it — so the screen is the one `video-loop --anchor motion-auto` ran over the whole clip+ (section 3, "The step screen"). The alignment reads it from the cut's report beside the loop+ (`align.cut_report`: a `sprite-gen-video-loop-report`, passed, in the loop's directory or the one+ above it — a `video-set` item keeps it there — whose strip is the loop's and whose cut is the one+ `strip.json` records in `cycle_drawings`). A loop whose cut was suspected, and whose steps nobody+ counted, is a suspect the same way (`one_step`: `length`, `lag`, `seconds`, `ratio`, `depth`,+ `pairs`, `coverage`, `leg_peaks`, `why`, `report`): stopped under `--multi-cycle fail`, aligned and+ named in the warnings under `warn` (`plays one step where the rest play two, if it is one`). The+ alignment cannot settle it — the next step is not in the loop: count its steps, and if it is one,+ cut it again with `video-loop … --steps 1` (the arguments are in its report) and align the set+ anew; if it is two, `--cycles <loop>=1` aligns it as it is. A loop with no report beside it is not+ screened this way.- **Two cycles in one loop are stopped, and counted by whoever looks**: one length for the set isone beat only if every loop holds one cycle. A loop that holds two strides, resampled to theset's length, walks twice as fast as the rest, arms and legs alike — and pixels cannot tell itdiff --git a/docs/loop-review.md b/docs/loop-review.mdindex ab5f430..e14f0d1 100644--- a/docs/loop-review.md+++ b/docs/loop-review.md@@ -98,9 +98,17 @@ and the cut is chosen again among those whose top was read and closes ([loop repsection 3, "The seam pop"; `cycle.seam_pop`). A first choice whose top closes, or cannot be read, is kept andnothing more is measured. Once it pops, the held part is read below its top as well, on the sidethe top band sits on: a cut whose shaft closes under the hand is taken first, and where no cut one-step long closes it, a window two steps long is (`cycle.cycles: 2`; [loop repair](loop-repair.md)-section 3, "The held side"). An explicit `--max-len` is never widened; without one, only the gait-fallback below looks past the state's window, and only after this search found nothing.+step long closes it, a window two steps long — one cycle — is (`cycle.steps`, `strip.json`+`steps: 2`; [loop repair](loop-repair.md) section 3, "The held side"). An explicit `--max-len` is+never widened, nor cut back to half the clip: an explicit window is the window. Without one, only+the 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").### The gait fallback: a slow walk, or a walk toward the cameradiff --git a/docs/video-pipeline.md b/docs/video-pipeline.mdindex 7285849..ecf5283 100644--- a/docs/video-pipeline.md+++ b/docs/video-pipeline.md@@ -695,7 +695,10 @@ was 17). `video-loop` therefore:of the silhouette at the wrap and chooses again when it jumps, and every walk or runreports 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 staff- that closes only on two steps is cut two steps long (`cycle.cycles: 2`, "The held side").+ that 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.This neighbourhood check measures temporal consistency, not anatomical legidentity. A consistently repeated malformed motion can still score well; visual@@ -770,8 +773,11 @@ 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 that search cut two cycles long on purpose (a held part that closes only there, `cycles: 2` in-`strip.json`) is counted already: the set stage keeps both cycles at twice the set's length.+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+reads 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.The rule leans one way on purpose: a suspect costs a look, a miss a loop that plays twice as fast.A run's half step repeats as well as most of its strides do, so a run set is suspected nearlyevery time and stops until its loops are counted; a walk's half step is under its floor morediff --git a/sprite_gen/video/align.py b/sprite_gen/video/align.pyindex fee9451..71c3f2f 100644--- a/sprite_gen/video/align.py+++ b/sprite_gen/video/align.py@@ -36,11 +36,15 @@ it is, `--cycles <loop>=k` takes one cycle — a k-th of it, from the start whosis the most like it — out of the loop as filmed (`take_cycle`) and aligns that. Nothing changes thenumber of cycles in a loop but `--cycles`.-A loop `video-loop` cut two cycles long on purpose — a part it holds swings once in two cycles and-closes only there (its strip metadata says `cycles`, docs/loop-repair.md section 3, "The held side")-— is counted already: it is not a suspect to stop on, its length counts per cycle toward the set's,-and it is resampled to that many times the set's length, keeping its cycles (`cycles_kept`). A-`--cycles` count for it is still the last word.+The other way round, a loop may be one step of a cycle twice as long: a slow walk whose cycle the+cut's window could not hold, its legs drawn alike. Nothing in the loop shows that — the next step+is not in it — so the screen is the one `video-loop --anchor motion-auto` ran over the whole clip+(`cycle.step_screen` in the cut's report, found beside the loop: `one_step`). Such a loop stops the+set the same way (`--multi-cycle`), and align cannot settle it: whoever counts its steps cuts it+again (`video-loop --steps 1`) and aligns the set anew, or says it holds a whole cycle+(`--cycles <loop>=1`). A loop whose steps were counted — cut again on that count, or two lengths+taken so a held part closes (its strip metadata says `steps: 2`) — returns half way at its second+step: that return is no suspect (status `steps`), and the loop is aligned as the one cycle it is.Where a loop's view cannot tell its feet apart (`start_foot` null, with `foot_why`), it starts on itslarger strike, and the report names it under `unnamed_feet` with its two strike frames as they now@@ -448,15 +452,68 @@ class CycleSuspects(SystemExit):self.command = command+def cut_report(loop_dir: Path, meta_path: Path, meta: dict[str, Any]) -> tuple[Path, dict[str, Any]] | None:+ """The report `video-loop` wrote for this loop's cut, or None: a JSON of kind+ sprite-gen-video-loop-report, passed, in the loop's directory or the one above it (a video-set+ item keeps it there), whose strip is this loop's and whose cut (start, length) is the one the strip+ metadata records (`cycle_drawings`) — a report of another cut of the same clip is not it."""+ cut = meta.get("cycle_drawings") or {}+ if "start" not in cut or "length" not in cut:+ return None+ strip_name = meta_path.name[: -len(".strip.json")] + ".strip.png"+ for folder in (loop_dir, loop_dir.parent):+ for path in sorted(folder.glob("*.json")):+ if path.name.endswith(".strip.json"):+ continue+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ continue+ if not isinstance(data, dict) or data.get("kind") != "sprite-gen-video-loop-report" or data.get("status") != "passed":+ continue+ cycle = data.get("cycle") or {}+ if (Path(str((data.get("strip") or {}).get("path", ""))).name == strip_name+ and (cycle.get("start"), cycle.get("length")) == (cut["start"], cut["length"])):+ return path, data+ return None+++def one_step(loop_dir: Path, meta_path: Path, meta: dict[str, Any]) -> dict[str, Any] | None:+ """A loop the cut's step screen suspects of being one step (`cut_report`, `cycle.step_screen`), and+ whose steps nobody counted (no `steps` in its strip metadata): the screen's evidence and the report+ it is in. None otherwise — and where no report is found."""+ if meta.get("steps") is not None:+ return None+ found = cut_report(loop_dir, meta_path, meta)+ if found is None:+ return None+ path, data = found+ screen = (data.get("cycle") or {}).get("step_screen") or {}+ if not screen.get("suspect"):+ return None+ return {**{k: screen[k] for k in ("length", "lag", "ratio", "depth", "pairs", "coverage", "leg_peaks", "why") if k in screen},+ "seconds": round(screen["lag"] / float(data["fps"]), 3), "report": str(path)}++def _suspect_line(entry: dict[str, Any]) -> str:"""One loop's suspects, in words: where it returns, how, and what that would make it."""+ if "one_step" in entry:+ step = entry["one_step"]+ line = (f"{entry['dir']}: may be one step of a cycle {step['lag']} frames long ({step['seconds']:.3f} s) — it repeats "+ f"{step['ratio']:.2f}x as far two lengths on in its clip as one length on; count its steps, and if it is one, cut it "+ f"again with `sprite-gen video-loop … --steps 1` (the arguments are in {step['report']}) and align the set anew")+ return line + ("; it may also hold " + "; or ".join(_returns_said(entry)) if entry["candidates"] else "")+ return f"{entry['dir']}: may hold " + "; or ".join(_returns_said(entry))+++def _returns_said(entry: dict[str, Any]) -> list[str]:parts = []for row in entry["candidates"]:evidence = [f"pose {row['pose']:.2f}" if row.get("pose") is not None else None,f"steps {row['steps']:.2f}" if row.get("steps") is not None else None]parts.append(f"{row['cycles']} cycles of {row['period']} frames ({row['seconds']:.3f} s) — {row['why']}"+ (f" [{', '.join(e for e in evidence if e)}]" if any(evidence) else ""))- return f"{entry['dir']}: may hold " + "; or ".join(parts)+ return partsdef _resolve_loops(flag: str, given: dict[str, Any] | None, loops: list[tuple[Path, Path, dict[str, Any], float]],@@ -536,9 +593,9 @@ def _rebuild(loop_dir: Path, meta_path: Path, meta: dict[str, Any], frames: listif "follow" in meta or (loop_dir / loop_mod.FOLLOW_SOURCE).exists():record["follow_cleared"] = True(loop_dir / loop_mod.FOLLOW_SOURCE).unlink(missing_ok=True)- merged = {**{k: v for k, v in meta.items() if k not in strip_meta and k not in ("cycle_align", "follow", "cycles")}, **strip_meta}- if record.get("cycles_kept", 1) > 1:- merged["cycles"] = record["cycles_kept"]+ # a loop one cycle of which was taken out (`--cycles` k > 1) no longer holds the steps it was counted with+ merged = {**{k: v for k, v in meta.items() if k not in strip_meta and k not in ("cycle_align", "follow")+ and not (k == "steps" and "cycle_taken" in record)}, **strip_meta}if meta.get("foot_anchor") and meta.get("foot_anchor") != "feet":merged["foot_anchor"] = meta["foot_anchor"]cells = [strip.crop((k * strip_meta["w"], 0, (k + 1) * strip_meta["w"], strip_meta["h"])) for k in range(strip_meta["frames"])]@@ -639,26 +696,26 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:given = _resolve_cycles(cycles, loops)told = _resolve_loops("--foot", feet, loops, handed_mod.SIDES)screens = [cycle_screen(frames, fps=fps, state=state or meta.get("state")) for (_, _, meta, _), frames in zip(loops, sources)]- # Cycles a loop keeps: what its cutter declared (`cycles`, a cut two cycles long on purpose) unless- # a --cycles count says otherwise.- kept = {i: int(meta.get("cycles") or 1) for i, (_, _, meta, _) in enumerate(loops)}suspects: list[dict[str, Any]] = []taken: dict[int, dict[str, Any]] = {}cycle_warnings: list[str] = []- for i, ((d, meta_path, _, _), screen) in enumerate(zip(loops, screens)):+ for i, ((d, meta_path, meta, _), screen) in enumerate(zip(loops, screens)):k = given.get(i)- if k is not None:- kept[i] = 1- if screen["suspects"]:- declared = k is None and kept[i] > 1- status = ("declared" if declared else "stopped" if k is None and multi_cycle == "fail"- else "warned" if k is None else "counted")+ # A loop counted two steps long (`steps`) returns half way at its second step: not a second cycle.+ stepped = [row for row in screen["suspects"] if meta.get("steps") == 2 and row["cycles"] == 2]+ rows = [row for row in screen["suspects"] if row not in stepped]+ step = one_step(d, meta_path, meta)+ if rows or step or stepped:+ status = ("counted" if k is not None else "steps" if not rows and not step+ else "stopped" if multi_cycle == "fail" else "warned")suspects.append({"dir": str(d), "name": meta_path.name[: -len(".strip.json")], "length": len(sources[i]),"status": status, "cycles_given": k,"candidates": [{key: row[key] for key in ("period", "seconds", "divisor", "cycles", "periodicity", "pose","off_path", "distance", "steps", "follow", "why") if key in row}- for row in screen["suspects"]],- "settle": [f"--cycles {d}={c}" for c in sorted({1, *(row["cycles"] for row in screen["suspects"])})]})+ for row in (rows or stepped)],+ **({"one_step": step} if step else {}),+ **({"steps": meta["steps"]} if stepped else {}),+ "settle": [f"--cycles {d}={c}" for c in sorted({1, *(row["cycles"] for row in rows)})]})if k is not None and k > 1:if not any(row["cycles"] == k for row in screen["suspects"]):cycle_warnings.append(f"{d}: --cycles {k} given, but the screen found no return at 1/{k} of it; "@@ -677,8 +734,9 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:*(f"--cycles {e['dir']}=<{'|'.join(s.rpartition('=')[2] for s in e['settle'])}>" for e in stopped)]command = " ".join(rerun)message = ("video-cycle-align: " + "; ".join(_suspect_line(e) for e in stopped)- + ". Stopped before anything was rewritten: pixels cannot tell two cycles from one cycle whose steps look alike. "- "Count the cycles in each (look at it, or ask a vision model how often each foot lands), then run, with each count "+ + ". Stopped before anything was rewritten: pixels cannot tell two cycles from one cycle whose steps look alike"+ + (", nor one step from a cycle" if any("one_step" in e for e in stopped) else "")+ + ". Count the cycles in each (look at it, or ask a vision model how often each foot lands), then run, with each count "f"filled in (1: it holds one, aligned as it is; more: one cycle is taken out of it): {command}"" — or add --multi-cycle warn to align the set as it is (docs/loop-repair.md section 4)")if report_path is not None:@@ -688,11 +746,11 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:"cycles_given": {str(loops[i][0]): k for i, k in given.items()}, "feet_given": {str(loops[i][0]): f for i, f in told.items()}})raise CycleSuspects(message, suspects, command)cycle_warnings += [f"{_suspect_line(e)}; aligned as it is (--multi-cycle warn) — at the set's length it plays "- f"{max(row['cycles'] for row in e['candidates'])} times as fast as the rest if it does"+ + ("one step where the rest play two, if it is one" if "one_step" in e else+ f"{max(row['cycles'] for row in e['candidates'])} times as fast as the rest if it does")for e in suspects if e["status"] == "warned"]lengths = [len(f) for f in sources]- # A loop kept two cycles long counts one cycle's length toward the set's, and is made that many times as long.- target = length if length is not None else round(statistics.median(n / kept[i] for i, n in enumerate(lengths)))+ target = length if length is not None else round(statistics.median(lengths))located: list[dict[str, str]] = []def lazy(a: Image.Image, b: Image.Image, t: float) -> Image.Image:@@ -707,7 +765,7 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:aligned = []for i, ((d, *_), frames, view) in enumerate(zip(loops, sources, views or [None] * len(loops))):try:- out, facts = resample(frames, target * kept[i], lazy, between=between)+ out, facts = resample(frames, target, lazy, between=between)strike = foot_strike(out, view=view, foot=start_foot, given=told.get(i))except rife_mod.RifeNotInstalled as exc:raise rife_mod.RifeNotInstalled(f"{d}: {exc}") from exc@@ -719,18 +777,16 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:record = {**facts, "drawings": drawings, "retake": again, "turned_by": start, "turned_on": strike["by"], "view": view, "start_foot": strike["start_foot"],"start_foot_source": strike["start_foot_source"],# the two strikes as they stand in the rebuilt cycle/: the larger first- "strikes": [(k - start) % len(out) for k in strike["strikes"]],+ "strikes": [(k - start) % target for k in strike["strikes"]],**{key: strike[key] for key in ("foot", "foot_why", "foot_given", "foot_unnamed_why", "foot_disagrees") if key in strike},"stride_swing": strike["stride_swing"], "reach_swing": strike["reach_swing"],"fps": round(fps, 4), "source": SOURCE_DIR, "cycles_given": given.get(i), "cycle_screen": screens[i],**({"cycle_taken": taken[i]} if i in taken else {}),- # only on a loop its cutter declared more than one cycle long: every other loop's record is as before- **({"cycles_kept": kept[i]} if "cycles" in loops[i][2] else {}),- "made_at": [(k - start) % len(out) for k in facts["made_at"]]}+ "made_at": [(k - start) % target for k in facts["made_at"]]}if "nearest_at" in facts:- record["nearest_at"] = sorted((k - start) % len(out) for k in facts["nearest_at"])+ record["nearest_at"] = sorted((k - start) % target for k in facts["nearest_at"])if "smear" in facts:- record["smear"] = sorted(({**m, "at": (m["at"] - start) % len(out)} for m in facts["smear"]), key=lambda m: m["at"])+ record["smear"] = sorted(({**m, "at": (m["at"] - start) % target} for m in facts["smear"]), key=lambda m: m["at"])aligned.append((out[start:] + out[:start], record))rows = []for (d, meta_path, meta, _), (out, record) in zip(loops, aligned):@@ -784,9 +840,10 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:"report lists under `unnamed_feet` (repeatable; LOOP is named as for --cycles): that loop starts as ""--start-foot lands, recorded start_foot_source given")parser.add_argument("--multi-cycle", choices=MULTI_CYCLE, default="fail",- help="a loop that may hold two or three cycles (a half or a third of it returns to a pose on the motion's path) "- "and has no --cycles: fail (default) stops the set before anything is rewritten, the report naming it under "- "`suspects`; warn aligns it as it is and names it in the warnings")+ help="a loop that may hold two or three cycles (a half or a third of it returns to a pose on the motion's path), "+ "or may be one step (its cut's report: `cycle.step_screen`), and has no --cycles: fail (default) stops the "+ "set before anything is rewritten, the report naming it under `suspects` (`one_step` for the latter: cut it "+ "again with video-loop --steps 1 once its steps are counted); warn aligns it as it is and names it in the warnings")parser.add_argument("--state", help="the set's motion state (walk, run), for loops cut before video-loop wrote it in the strip metadata: ""its gait floor is the shortest cycle the screen looks for")parser.add_argument("--between", choices=BETWEEN, default=DEFAULT_BETWEEN,diff --git a/sprite_gen/video/batch.py b/sprite_gen/video/batch.pyindex 5832719..b686dfe 100644--- a/sprite_gen/video/batch.py+++ b/sprite_gen/video/batch.py@@ -723,6 +723,12 @@ def run_item(result["loop"]["fundamental"] = {"period": lp["cycle"]["fundamental"]["period"],"suspects": [{k: row.get(k) for k in ("period", "cycles", "pose", "steps")}for row in lp["cycle"]["fundamental"]["suspects"]]}+ if "steps" in lp["cycle"]:+ # the cut's steps are known: its frame count is two steps — one cycle — not twice its siblings' one+ result["loop"]["steps"] = lp["cycle"]["steps"]["count"]+ if (lp["cycle"].get("step_screen") or {}).get("suspect"):+ # the cut may be one step of a cycle twice as long (recorded, not cut again)+ result["loop"]["step_screen"] = {k: lp["cycle"]["step_screen"][k] for k in ("lag", "ratio", "depth", "coverage")}if lp.get("motion_anchor", {}).get("applied") is False:result["loop"]["motion_anchor"] = lp["motion_anchor"]if "rife" in (lp.get("jump_repair") or {}):@@ -833,9 +839,15 @@ def align_gaits(results: list[dict[str, Any]], root: Path, mode: str, *, interpofile=sys.stderr)continueexcept align_mod.CycleSuspects as exc:- names = ", ".join(Path(e["dir"]).parent.name if Path(e["dir"]).name == "loop" else e["name"] for e in exc.suspects if e["status"] == "stopped")+ def said(entries: list[dict[str, Any]]) -> str:+ return ", ".join(Path(e["dir"]).parent.name if Path(e["dir"]).name == "loop" else e["name"] for e in entries)+ stopped = [e for e in exc.suspects if e["status"] == "stopped"]+ held = [e for e in stopped if e["candidates"]]+ step = [e for e in stopped if "one_step" in e]out[state] = {"ok": True, "applied": False, "reason": "cycle-suspects",- "why": f"{names} may hold more than one cycle — each loop keeps its own length until its cycles are counted",+ "why": " and ".join([*([f"{said(held)} may hold more than one cycle"] if held else []),+ *([f"{said(step)} may be one step (cut it again with video-loop --steps 1 if it is)"] if step else [])])+ + " — each loop keeps its own length until its cycles are counted","suspects": exc.suspects, "command": exc.command, "report": str(root / f"{state}.cycle-align.json")}print(f"video-set: warning: {state}: cycles not aligned — {out[state]['why']}; count them and run "f"`sprite-gen video-cycle-align --cycles <loop>=<k>` ({exc}) (docs/loop-repair.md section 4)", file=sys.stderr)@@ -885,7 +897,9 @@ def write_table(results: list[dict[str, Any]], path: Path, *, both: bool = Falsestatus = "OK (uncorrected; review gait)"if "jump_repair" in lp:status += " (jump not repaired: no RIFE)"- lines.append(f"| {_view_label(r, both)} | {r['state']} | {lp.get('kind', 'periodic')} | {lp['cycle']} | {lp['period'] if lp['period'] is not None else '-'} | {lp['seam_ratio']:.2f} | {lp['n_out']} | {status} |")+ # a cut whose steps are known is two of them; one the step screen suspects may be one+ cycle = f"{lp['cycle']}" + (f" ({lp['steps']} steps)" if lp.get("steps") else " (one step?)" if lp.get("step_screen") else "")+ lines.append(f"| {_view_label(r, both)} | {r['state']} | {lp.get('kind', 'periodic')} | {cycle} | {lp['period'] if lp['period'] is not None else '-'} | {lp['seam_ratio']:.2f} | {lp['n_out']} | {status} |")else:lines.append(f"| {_view_label(r, both)} | {r['state']} | - | - | - | - | - | FAIL: {r.get('error', '')[:80]} |")text = "\n".join(lines) + "\n"diff --git a/sprite_gen/video/local_cycle.py b/sprite_gen/video/local_cycle.pyindex 9fe568f..add854d 100644--- a/sprite_gen/video/local_cycle.py+++ b/sprite_gen/video/local_cycle.py@@ -7,6 +7,9 @@ same two-step duration prior; an isolated matching endpoint is insufficient.The local period taken is screened for two or three cycles and the findingrecorded (`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 as+long that the window could not hold (`step_screen`), never cut longer on it:+only a count of the steps (`video-loop --steps`) cuts again."""from __future__ import annotationsimport math@@ -47,6 +50,16 @@ def _measure(distances, trajectory, start, length, profile):'ratio': ratio, 'context_repeat_over_step': error/step, 'drift_line_residual_analysis_px': residual}+def _closure(distances, start, length):+ """How far a cut's wrap is from the clip's own way on there: its last frame against the clip's frame+ before its first, and the frame before its last against the one before that (the speed into the+ wrap), over the cut's mean playback step. None for a cut with fewer than two clip frames before it."""+ step = float(np.diag(distances[start:start+length, start:start+length], 1).mean())+ if start < 2 or step <= 1e-10:+ return None+ return float(distances[start+length-1, start-1] + distances[start+length-2, start-2])/2/step++def _read(measured):"""A cut's pop as `cycle.seam_pop` records it: the jump, or why its top band could not be read."""return {'skipped': measured['skipped']} if 'skipped' in measured else {'pop': measured['pop']}@@ -65,14 +78,16 @@ def _held(measured):return {'skipped': measured['skipped']} if 'skipped' in measured else {'seam': measured['seam'], 'closes': measured['closes']}-def _held_rank(candidates, calm, chosen, wrap_pop, held_edge, length_cap=None):+def _held_rank(candidates, calm, chosen, wrap_pop, held_edge, length_cap=None, double=True):"""Below the top band (`held_edge`, repair.held_edge on the side the popping first choice holds itspart): among the calm candidates, those whose held side closes, the same score tolerance, then the- smallest held seam. When no one-cycle candidate closes it, windows twice a candidate's length- (`cycles` 2): a part swinging once in two cycles closes only there. Such a window is two cycles of- a repeat the search confirmed, not itself seen repeating; it is taken when its held side closes and- its top does not pop, the smallest held seam first. A window longer than `length_cap` (an explicit- --max-len) is not one. Returns (picked or None, record)."""+ smallest held seam. When no candidate closes it, windows twice a candidate's length: the candidate+ was one step of a walk whose arm, and the part it holds, swing once a cycle — two steps — and close+ only there (`steps` 2: the window is one cycle, `step_lengths` the candidates it is two of — each one+ step). Such a window is two lengths of a repeat the search confirmed, not itself seen repeating; it+ is taken when its held side closes and its top does not pop, the smallest held seam first. A window longer than `length_cap`+ (an explicit --max-len) is not one, and none is read without `double` (the steps were counted,+ `video-loop --steps`). Returns (picked or None, record)."""side = held_edge.side(chosen['start'], chosen['length'])if 'skipped' in side:return None, {'method': 'held-side-edge-v1', 'skipped': side['skipped']}@@ -93,14 +108,17 @@ def _held_rank(candidates, calm, chosen, wrap_pop, held_edge, length_cap=None):cutoff = min(row['score'] for row in closing)*1.15+1e-8picked = min((row for row in closing if row['score'] <= cutoff),key=lambda row: (row['held_edge'], row['seam_pop'], row['score'], row['start'], row['length']))- record.update(cycles=1, chosen={'start': picked['start'], 'length': picked['length'], 'seam': picked['held_edge'], 'closes': True})+ record.update(doubled=False, chosen={'start': picked['start'], 'length': picked['length'], 'seam': picked['held_edge'], 'closes': True})return picked, record+ if not double:+ record['two_step'] = {'read': False, 'why': 'the steps were counted (--steps): no window twice as long is read'}+ return None, recordlengths = sorted({2*row['length']+d for row in candidates for d in (-1, 0, 1)})if length_cap is not None:over = [length for length in lengths if length > length_cap]lengths = [length for length in lengths if length <= length_cap]if over:- record['two_cycle_capped'] = {'max_len': length_cap, 'lengths_over': [over[0], over[-1]]}+ record['two_step_capped'] = {'max_len': length_cap, 'lengths_over': [over[0], over[-1]]}if not lengths:return None, recordwindows = []@@ -118,18 +136,20 @@ def _held_rank(candidates, calm, chosen, wrap_pop, held_edge, length_cap=None):if 'skipped' in top or top['pops']:counts['top_pops'] += 1 # a top that pops, or one that could not be read, is not takencontinue- windows.append({'start': start, 'length': length, 'cycles': 2, 'period_local': round(length/2),+ windows.append({'start': start, 'length': length, 'period_local': length,+ 'steps': {'count': 2, 'by': 'held-edge',+ 'step_lengths': sorted({row['length'] for row in candidates if abs(2*row['length']-length) <= 1})},'held_edge': measured['seam'], 'seam_pop': top['pop'],- 'repeat': 'two cycles of a confirmed repeat, not itself seen repeating'})- record['two_cycle'] = {'lengths': [lengths[0], lengths[-1]], **counts, 'closing': len(windows)}+ 'repeat': 'two lengths of a confirmed repeat (two steps, one cycle), not itself seen repeating'})+ record['two_step'] = {'read': True, 'lengths': [lengths[0], lengths[-1]], **counts, 'closing': len(windows)}if windows:picked = min(windows, key=lambda row: (row['held_edge'], row['seam_pop'], row['start'], row['length']))- record.update(cycles=2, chosen={'start': picked['start'], 'length': picked['length'], 'seam': picked['held_edge'], 'closes': True})+ record.update(doubled=True, chosen={'start': picked['start'], 'length': picked['length'], 'seam': picked['held_edge'], 'closes': True})return picked, recordreturn None, record-def _shape_rank(candidates, chosen, wrap_pop, held_edge=None, length_cap=None):+def _shape_rank(candidates, chosen, wrap_pop, held_edge=None, length_cap=None, double=True):"""Choose again when the chosen cut's top pops at the wrap (`wrap_pop`, repair.seam_pop on theanalysed frames): among the candidates whose top was read and does not pop, the same scoretolerance, then the smallest pop. Nothing is measured past the first choice when it does not pop,@@ -137,9 +157,10 @@ def _shape_rank(candidates, chosen, wrap_pop, held_edge=None, length_cap=None):own beat is chosen exactly as before. A candidate whose top could not be read is not chosen.With `held_edge` (loop.HeldEdge), a popping first choice has its held part read below the top too- (`_held_rank`): a cut whose held side closes is taken first, one or two cycles long. Where none+ (`_held_rank`): a cut whose held side closes is taken first, one or two lengths long. Where nonecloses, the choice is the top band's, and `held_edge.chosen` records that it does not close (the- jolt warns, repair.held_edge_verdict). A two-cycle window is never longer than `length_cap`."""+ jolt warns, repair.held_edge_verdict). A window two lengths long is never longer than `length_cap`,+ nor read without `double`."""first = wrap_pop(chosen['start'], chosen['length'])record = {'method': 'top-band-wrap-v1', 'reference': first['reference'],'first_choice': {'start': chosen['start'], 'length': chosen['length'], **_read(first)},@@ -158,11 +179,11 @@ def _shape_rank(candidates, chosen, wrap_pop, held_edge=None, length_cap=None):record.update(measured=len(candidates)-unread, unread=unread)held = Noneif held_edge is not None:- picked, held = _held_rank(candidates, calm, chosen, wrap_pop, held_edge, length_cap)+ picked, held = _held_rank(candidates, calm, chosen, wrap_pop, held_edge, length_cap, double)record['held_edge'] = heldif picked is not None:record.update(applied=True, chosen={'start': picked['start'], 'length': picked['length'], 'pop': picked['seam_pop'],- **({'cycles': 2} if picked.get('cycles') == 2 else {})})+ **({'steps': 2} if 'steps' in picked else {})})return picked, recordif not calm:record['why'] = 'every candidate whose top was read pops at the wrap; the first choice is kept'@@ -178,19 +199,62 @@ def _shape_rank(candidates, chosen, wrap_pop, held_edge=None, length_cap=None):return picked, record+def counted(distances, trajectory, *, min_len, max_len, periodicity_min, signals=None):+ """A cut of a length someone counted (`video-loop --steps`) where the clip is too short to see a+ window that long repeat (`detect` found none): the counted length stands for the repeat. Every+ window [min_len, max_len] long with two clip frames before it is read, and the one whose wrap is+ nearest the clip's own way on there is taken (`_closure`, the earliest on a tie); whether it closes+ is the seam gate's word. Raises ValueError where no window has room."""+ n = len(distances)+ rows = []+ for length in range(min_len, max_len+1):+ for start in range(2, n-length+1):+ measured = _closure(distances, start, length)+ if measured is None:+ continue+ step = float(np.diag(distances[start:start+length, start:start+length], 1).mean())+ x = np.arange(length)+ segment = trajectory[start:start+length]+ rows.append({'start': start, 'length': length, 'period_local': length, 'closure': measured,+ 'ratio': float(distances[start+length-1, start])/step,+ 'drift_line_residual_analysis_px': float(np.abs(segment-np.polyval(np.polyfit(x, segment, 1), x)).mean()),+ 'half_period_guard': {'applied': False}})+ if not rows:+ raise ValueError(f"no window {min_len}-{max_len} frames long has two clip frames before it in {n}")+ rows.sort(key=lambda row: (row['closure'], row['start'], row['length']))+ chosen = rows[0]+ return {**chosen, 'kind': 'periodic', 'method': 'counted-window-v1',+ 'repeat': 'not seen in the clip: the counted length stands for it', 'choice': 'closure',+ 'period_global': None, 'periodicity_min': periodicity_min, 'review_recommended': True,+ 'candidate_count': len(rows), 'candidates': rows[:REFUSED_SHOWN],+ 'step_screen': period_mod.step_screen(distances, start=chosen['start'], length=chosen['length'],+ periodicity_min=periodicity_min, signals=signals)}++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):+ held_edge=None, length_cap=None, double=True, closure=False):"""`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`).`held_edge` (loop.HeldEdge) reads the held side below the top of a cut chosen again; the cut it- takes may be two cycles long (`cycles` 2 in the result), but never longer than `length_cap`, an- explicit --max-len: the caller's ceiling on the cut, which `max_len` alone does not mark (the- state's default window is one too)."""+ takes may be two lengths long (`steps` in the result: two steps, one cycle), but never longer than+ `length_cap`, nor with `double` false.++ `length_cap` is the caller's own ceiling on the cut — an explicit --max-len, or the window a count+ of steps sets (`video-loop --steps`) — which `max_len` alone does not mark (the state's default+ window is one too). It is the window's top as given: the share of the clip (`max_fraction`) bounds+ only a window the caller did not set. Each window still needs its repeat seen in the clip.++ 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`). The+ cut 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."""n = len(distances)- # A cycle has to be seen repeating: half the clip by default, more for the gait fallback.- lo, hi = max(6, min_len), min(max_len, int(n*max_fraction))+ # 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.+ lo = max(6, min_len)+ hi = min(max_len, length_cap) if length_cap is not None else min(max_len, int(n*max_fraction))if hi < lo:raise ValueError(f"automatic motion cycle window [{lo}, {hi}] has no repeated cycle")candidates = []@@ -277,22 +341,37 @@ def detect(distances, trajectory, *, min_len, max_len, gait_floor,candidates.sort(key=lambda row: (row['score'], row['start'], row['length']))# Equivalent-quality candidates: prefer the earliest demonstrated repeat.cutoff = candidates[0]['score']*1.15+1e-8- chosen = min((r for r in candidates if r['score'] <= cutoff),- key=lambda row: (row['start'], row['score'], row['length']))+ equivalent = [r for r in candidates if r['score'] <= cutoff]+ if closure:+ # A length counted, not found: its window was never the search's, and the earliest of the+ # equivalent cuts need not be the one that closes — the one whose wrap the clip itself plays is.+ for row in equivalent:+ row['closure'] = _closure(distances, row['start'], row['length'])+ chosen = min(equivalent, key=lambda row: (row['closure'] is None, row['closure'] or 0.0, row['start'], row['score'], row['length']))+ else:+ chosen = min(equivalent, key=lambda row: (row['start'], row['score'], row['length']))shape = Noneif wrap_pop is not None:- chosen, shape = _shape_rank(candidates, chosen, wrap_pop, held_edge, length_cap)+ chosen, shape = _shape_rank(candidates, chosen, wrap_pop, held_edge, length_cap, double)+ if 'ratio' not in chosen:+ # 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')+ 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 {**chosen, 'fundamental': fundamental, 'kind': 'periodic', 'method': 'local-repeat-drift-v1','period_global': None, 'periodicity_min': periodicity_min,'review_recommended': True, 'candidate_count': len(candidates),'best_score': candidates[0]['score'], 'equivalent_score_tolerance': .15,'candidates': candidates[:12],+ **({'choice': 'closure'} if closure else {}),**({'seam_pop': shape} if shape is not None else {}),+ 'step_screen': steps,}diff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.pyindex 4ac3356..6c761f4 100644--- a/sprite_gen/video/loop.py+++ b/sprite_gen/video/loop.py@@ -90,6 +90,14 @@ ONE_SHOT_MIN_LEN = 4 # a one-shot's length is the clip's own fact; only a degenGAIT_DOUBLE_TOL = 0.25GAIT_DOUBLE_SEARCH = 3 # frames either side of 2x the step where the full gait's own minimum may sitGAIT_NEAR_EXACT_STEP_FRACTION = 0.10 # no ambiguity extension when repeat error is tiny compared with a playback step+# `--steps`: how many steps the cut `--anchor motion-auto` takes holds, as counted by whoever looked at+# it (docs/loop-repair.md section 3, "The step screen"). 1 cuts again two of its lengths long, 2 keeps it.+STEPS = (1, 2)+# A cut two steps long (one cycle) that the clip holds less than this share of a cycle past is cut and+# warned about (`cycle.coverage`): its repeat is barely in the clip, and the seam gate says whether it+# closes. The search itself sees a window repeat only with a quarter of its length past it in the clip,+# so a cut under this was taken on the count alone (local_cycle.counted).+COVERAGE_MIN = 0.25ANCHOR_MODES = ("none", "feet", "body", "motion", "motion-auto")BODY_ANCHOR_BAND = 0.6 # --anchor body reads the wrap offset from the top 60 % of the first frame's box: head and torso, not the legsBODY_ANCHOR_SEARCH = 24 # px either side searched for the last frame's horizontal offset against the first@@ -923,6 +931,47 @@ class HeldEdge:return {"skipped": str(exc), "reference": repair_mod.HELD_EDGE_REFERENCE}+def _counted(cycle: dict[str, Any], steps: int, *, 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+ its lengths long, [2L-1, 2L+1], as long as the caller's ceiling — not half the clip — with the same+ search (a repeat seen in the clip, the top band and the held side read again) save that the cut whose+ wrap the clip itself plays is taken among the equivalent ones (`local_cycle._closure`), and no window+ twice that. A clip too short to see such a window repeat is cut all the same, the count standing+ for the repeat (`local_cycle.counted`, `unseen` says why); `cycle.coverage` and the seam gate say the+ rest. Recorded `steps` (`first_cut`: the cut counted)."""+ first = {"start": cycle["start"], "length": cycle["length"]}+ if steps == 2:+ cycle["steps"] = {"count": 2, "by": "given", "given": 2}+ return cycle+ lo, hi = 2 * first["length"] - 1, 2 * first["length"] + 1+ signals = leg_signals(frames)+ try:+ found = local_cycle.detect(D, trajectory, min_len=lo, max_len=hi, length_cap=hi, signals=signals,+ wrap_pop=wrap_pop_on(moved), held_edge=HeldEdge(moved), double=False, closure=True, **detect)+ except ValueError as unseen:+ # Too short a clip to see the cycle repeat: the count stands for it (`cycle.coverage` says how short).+ try:+ found = local_cycle.counted(D, trajectory, min_len=lo, max_len=hi, periodicity_min=detect["periodicity_min"], signals=signals)+ except ValueError as exc:+ failed = ValueError(f"--steps 1: the cut of {first['length']} frames from {first['start']} is one step, and the clip "+ f"({len(D)} frames) has no window {lo}-{hi} frames long to cut: {exc}")+ failed.diagnostics = {**getattr(unseen, "diagnostics", {}), "steps": {"given": 1, "first_cut": first, "window": [lo, hi]}} # type: ignore[attr-defined]+ raise failed from exc+ found["unseen"] = str(unseen)+ found["steps"] = {"count": 2, "by": "given", "given": 1, "first_cut": first, "window": [lo, hi]}+ return found+++def coverage_verdict(cycle: dict[str, Any]) -> list[str]:+ """A cut two steps long whose clip holds under COVERAGE_MIN of a cycle past it, in words; empty+ otherwise (and for a cut whose steps are not known)."""+ if "steps" not in cycle or cycle["coverage"] >= COVERAGE_MIN:+ return []+ return [f"the cut is two steps long ({cycle['length']} frames, one cycle) and the clip holds {cycle['coverage']:.2f} of a cycle "+ f"past it (under {COVERAGE_MIN:g}): its repeat is barely seen — the seam says whether it closes; a longer take shows it repeat"]++def run_loop(frames_dir: Path,out_dir: Path,@@ -949,7 +998,10 @@ def run_loop(jolt_max: float | None = None,head_step_max: float | None = None,size_hold: str = "auto",+ steps: int | None = None,) -> dict[str, Any]:+ if steps is not None and steps not in STEPS:+ raise SystemExit(f"video-loop: --steps {steps}: the cut holds {' or '.join(map(str, STEPS))} steps here")if size_hold not in SIZE_HOLD_MODES:raise SystemExit(f"video-loop: unknown --size-hold {size_hold!r}; expected one of {', '.join(SIZE_HOLD_MODES)}")if repair not in REPAIR_MODES:@@ -968,6 +1020,8 @@ def run_loop(if anchor == "motion-auto" and (cycle_mode not in ("auto", "periodic") or not profile_for(state).gaitor start is not None or length is not None):raise SystemExit("video-loop: --anchor motion-auto requires walk/run with automatic or periodic selection; no fixed cut")+ if steps is not None and anchor != "motion-auto":+ raise SystemExit("video-loop: --steps counts the steps in the cut --anchor motion-auto takes; pass --anchor motion-auto")if cycle_mode not in CYCLE_MODES:raise SystemExit(f"video-loop: unknown --cycle {cycle_mode!r}; expected one of {', '.join(CYCLE_MODES)}")frames_dir = frames_dir.expanduser().resolve()@@ -1059,6 +1113,8 @@ def run_loop(if hasattr(second, "diagnostics"):failed.diagnostics = second.diagnostics # type: ignore[attr-defined]raise failed from first+ if steps is not None:+ cycle = _counted(cycle, steps, D=D, trajectory=trajectory, frames=source_frames, moved=moved, detect=detect)elif cycle_mode == "fixed":if start is None or length is None:raise SystemExit("video-loop: --cycle fixed needs --start and --length")@@ -1097,6 +1153,9 @@ def run_loop(raise SystemExit(f"video-loop: {exc}") from excraisei, L = cycle["start"], cycle["length"]+ if "steps" in cycle:+ # A cut two steps long is one cycle: how much of a second the clip holds past it.+ cycle["coverage"] = round((n - L) / L, 4)# The same, over the cut alone: a clip held for part of its length is held where the cut is.report_base["cycle_drawings"] = held_mod.measure_cycle(clip_steps, start=i, length=L, fps=fps)# playback density, not a fixed count: a long cycle gets more frames so every state plays at@@ -1170,6 +1229,7 @@ def run_loop(warnings += repair_mod.seam_pop_verdict(jolt, head_step_max=repair_mod.HEAD_STEP_REFERENCE)# 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)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,@@ -1201,10 +1261,10 @@ def run_loop(if state:# `video-cycle-align` reads the gait floor of this state when it screens a loop for two cycles.strip_meta["state"] = str(state).strip().lower()- if cycle.get("cycles", 1) > 1:- # A cut two cycles long, taken so a part swinging once in two closes (local_cycle._held_rank):- # `video-cycle-align` keeps both, at twice the set's length, instead of asking for a count.- strip_meta["cycles"] = cycle["cycles"]+ if "steps" in cycle:+ # A cut whose steps are known — counted (`--steps`) or two candidate lengths taken so a held part+ # closes (local_cycle._held_rank): `video-cycle-align` reads a return half way as its step.+ strip_meta["steps"] = cycle["steps"]["count"]# `video-cycle-align` reads the hold here, over the cut (`cycle_drawings`) and over the clip# (`drawings`, where the cut is too short to read): read on the keyed steps, since `--anchor# motion-auto` moves each frame of a pair apart in the cut it writes (sprite_gen/video/held.py).@@ -1332,6 +1392,12 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:parser.add_argument("--head-step-max", type=float, default=None, help=f"walk/run: fail the repaired loop when the head's largest sideways move in one frame exceeds this %% of the body height. Default: no gate — reported, and over {repair_mod.HEAD_STEP_REFERENCE} is a warning line")parser.add_argument("--facing", choices=FACINGS, default="right", help="which way the body faces in the frames (default right): the hair the jump search watches is behind it")parser.add_argument("--size-hold", choices=SIZE_HOLD_MODES, default="auto", help="--anchor motion-auto: auto (default) scales a clip whose height, read one cycle on (the same pose a cycle later), changes by 1 %% or more over the clip back to its first frame's size before the cycle search, so the loop's last frame is the size of its first (recorded as size_hold, with the evidence); off: search the frames as filmed")+ parser.add_argument("--steps", type=int, choices=STEPS, default=None,+ help="--anchor motion-auto: how many steps the cut it takes without this holds, as counted by whoever looked "+ "at the loop (how often each foot lands) — the report's `cycle.step_screen` names a cut that may be one "+ "step. 1: the cut is one step, so the walk is cut again two of its lengths long (the window [2L-1, 2L+1], "+ "not bounded by half the clip), recorded `cycle.steps`; 2: the cut is kept, recorded. Either way the strip "+ "metadata says `steps: 2`, which `video-cycle-align` reads")parser.add_argument("--name", default="loop", help="basename for strip/gif/webp outputs")parser.add_argument("--report", type=Path)@@ -1349,7 +1415,7 @@ def run(**kwargs: object) -> int:anchor_regions=kwargs.get("anchor_region"),repair=str(kwargs.get("repair") or "auto"), facing=str(kwargs.get("facing") or "right"),jolt_max=kwargs.get("jolt_max"), head_step_max=kwargs.get("head_step_max"), # type: ignore[arg-type]- size_hold=str(kwargs.get("size_hold") or "auto"),+ size_hold=str(kwargs.get("size_hold") or "auto"), steps=kwargs.get("steps"), # type: ignore[arg-type])summary = {k: payload[k] for k in ("state", "frames_total", "window", "cycle_seconds", "n_out", "delay_ms", "resampled_seam_ratio", "specks_dropped", "report")}summary["cycle"] = {k: payload["cycle"].get(k) for k in ("kind", "start", "length", "period_global", "ratio", "review_recommended", "half_period_guard", "fundamental")}@@ -1364,8 +1430,11 @@ def run(**kwargs: object) -> int:"seam_pop": payload["jolt"]["seam_pop"].get("pop")}if payload["cycle"].get("seam_pop", {}).get("applied"):summary["cycle"]["seam_pop"] = payload["cycle"]["seam_pop"]- if payload["cycle"].get("cycles", 1) > 1:- summary["cycle"]["cycles"] = payload["cycle"]["cycles"]+ if "steps" in payload["cycle"]:+ summary["cycle"]["steps"] = payload["cycle"]["steps"]+ summary["cycle"]["coverage"] = payload["cycle"]["coverage"]+ if "step_screen" in payload["cycle"]:+ summary["cycle"]["step_screen"] = payload["cycle"]["step_screen"]if payload.get("jump_repair", {}).get("replaced"):summary["jump_repair"] = {k: payload["jump_repair"][k] for k in ("replaced", "score_max_before", "score_max_after")}summary["strip"] = {k: payload["strip"][k] for k in ("path", "frames", "w", "h", "body_h", "delay_ms")}diff --git a/sprite_gen/video/period.py b/sprite_gen/video/period.pyindex e608e48..a69adb5 100644--- a/sprite_gen/video/period.py+++ b/sprite_gen/video/period.py@@ -177,3 +177,85 @@ def screen(period: int, *, D: np.ndarray, prof: dict[int, float], minima: list[idef local_minima(prof: dict[int, float]) -> list[int]:"""The lags of `prof` no deeper than either neighbour."""return [lag for lag in prof if lag - 1 in prof and lag + 1 in prof and prof[lag] <= prof[lag - 1] and prof[lag] <= prof[lag + 1]]+++# The other way round (docs/loop-repair.md section 3, "The step screen"): a walk filmed slower than its+# window can hold is cut one step long — the legs drawn alike, the step repeats in pixels — and nothing+# shorter than the cut is there to suspect. The lag twice the cut, read over the whole clip, repeats+# better than the cut itself where the arms or a held part tell the two steps apart.+STEP_SEARCH = 3 # frames either side of twice the cut where the cycle's own lag may sit+STEP_PAIRS_MIN = 4 # frame pairs a lag must have in the clip to be read+STEP_RATIO_MAX = 0.85 # the lag twice the cut over the cut's own lag, same frames: at or under this, a suspect+++def leg_peaks(values: list[float]) -> list[int]:+ """The step signal's peaks over a cut read as a ring: 1-2-1 smoothed, a frame that is the largest+ within a sixth of the ring either side, first of a plateau, standing 30 % of the signal's range over+ the least there. A cycle shows two, a step one. Recorded, never decided by."""+ v = np.asarray(values, dtype=float)+ n = len(v)+ if n < 3:+ return []+ s = np.array([(v[k - 1] + 2 * v[k] + v[(k + 1) % n]) / 4 for k in range(n)])+ r, spread = max(1, n // 6), float(s.max() - s.min())+ out = []+ for k in range(n):+ near = [s[(k + d) % n] for d in range(-r, r + 1)]+ if s[k] == max(near) and s[(k - 1) % n] < s[k] and s[k] - min(near) >= 0.3 * spread:+ out.append(k)+ return out+++def step_screen(D: np.ndarray, *, start: int, length: int, periodicity_min: float,+ signals: dict[str, list[float]] | None) -> dict[str, Any]:+ """Whether a gait's cut (`start`, `length`) may be one step of a cycle twice as long — never what+ is cut. Over the whole clip (not the search window): the lag within STEP_SEARCH of twice the cut+ whose mean distance is least (`lag`), and, over every frame with both lags in the clip (`pairs`),+ its distance over the cut's own (`ratio`); how far that lag dips under the clip's profile from half+ the cut to the lags read (`depth`); how much of a second cycle the clip holds past one cycle of that+ lag, `coverage` (n − lag) / lag; and the step signal's peaks over the cut (`leg_peaks`, a record+ only). A **suspect** repeats at the lag (`depth` at least `periodicity_min`) and better than at the+ cut (`ratio` at most STEP_RATIO_MAX). A true cycle repeats about as well a cycle on (its drift makes+ it a little worse); a step repeats better two cut lengths on, where the arms and a held part come+ back too. Pixels cannot tell a cycle on a frame count that is not whole (it repeats better at its+ double, being whole there) from a step, so only someone who counts the steps settles it — and the+ count comes back as `video-loop --steps`."""+ n = len(D)+ record: dict[str, Any] = {"method": "two-cut-lengths-v1", "length": length,+ "searched": [2 * length - STEP_SEARCH, 2 * length + STEP_SEARCH],+ "ratio_max": STEP_RATIO_MAX, "periodicity_min": periodicity_min}+ if signals is None:+ record["leg_peaks"] = {"by": None, "why": "no frames to read the legs from"}+ else:+ legs = legs_mod.step_signal({k: v[start:start + length] for k, v in signals.items()})+ record["leg_peaks"] = ({"by": legs["by"], "count": len(leg_peaks(legs["values"]))} if legs.get("by") is not None+ else {"by": None, "why": legs["why"]})++ def mean(lag: int) -> float:+ return float(D[np.arange(n - lag), np.arange(lag, n)].mean())++ lags = [lag for lag in range(2 * length - STEP_SEARCH, 2 * length + STEP_SEARCH + 1) if n - lag >= STEP_PAIRS_MIN]+ if not lags:+ record.update(lag=None, suspect=False,+ why=f"the clip ({n} frames) holds fewer than {STEP_PAIRS_MIN} frame pairs {record['searched'][0]} or more frames apart: "+ "twice the cut is not read")+ return record+ profile = {lag: mean(lag) for lag in range(max(2, length // 2), lags[-1] + 1)}+ lag = min(lags, key=lambda k: (profile[k], k))+ js = np.arange(n - lag)+ at_cut, at_lag = float(D[js, js + length].mean()), float(D[js, js + lag].mean())+ baseline = float(np.mean(list(profile.values())))+ ratio = round(at_lag / at_cut, 4) if at_cut > 0 else None+ depth = round((baseline - profile[lag]) / baseline, 4) if baseline > 0 else 0.0+ record.update(lag=lag, pairs=int(js.size), ratio=ratio, depth=depth, coverage=round((n - lag) / lag, 4))+ if depth < periodicity_min:+ record.update(suspect=False, why=f"{lag} frames on dips {depth:.2f} under the clip's profile, under {periodicity_min:.2f}: not a repeat")+ elif ratio is None or ratio > STEP_RATIO_MAX:+ record.update(suspect=False, why=f"{lag} frames on repeats {ratio}x as far as the cut's own {length}, over {STEP_RATIO_MAX}: "+ "no better two cut lengths on")+ else:+ record.update(suspect=True, why=f"{lag} frames on repeats {ratio:.2f}x as far as the cut's own {length} (at most {STEP_RATIO_MAX}) "+ f"and dips {depth:.2f} under the clip's profile: the cut may be one step of a cycle {lag} frames "+ "long, or a cycle that repeats better at its double — pixels cannot tell; count the steps in "+ "the loop (video-loop --steps)")+ return recorddiff --git a/sprite_gen/video/repair.py b/sprite_gen/video/repair.pyindex bc64d80..433bca5 100644--- a/sprite_gen/video/repair.py+++ b/sprite_gen/video/repair.py@@ -321,13 +321,16 @@ def held_edge_verdict(shape: dict[str, Any] | None) -> list[str]:return []line = (f"the held part does not close at the wrap on the {held['side']} side of the silhouette, below its top: "f"{chosen['seam']:.2f}x its rows' median step (over {held['reference']:g}); ")- capped = held.get("two_cycle_capped")+ capped = held.get("two_step_capped")if capped:- # An explicit --max-len is the caller's ceiling: windows two cycles long past it are not read.+ # An explicit --max-len is the caller's ceiling: windows two lengths long past it are not read.low, high = capped["lengths_over"]- return [line + f"no window one cycle long closes it, and windows two cycles long ({low}-{high} frames) are over "+ return [line + f"no window one length long closes it, and windows two lengths long ({low}-{high} frames) are over "f"--max-len {capped['max_len']}, so they were not read"]- return [line + "no window one or two cycles long closes it — it swings on a beat of its own"]+ if not held.get("two_step", {}).get("read", True):+ # The steps were counted (video-loop --steps): the cut is the count's, nothing longer is read.+ return [line + "no window of the counted length closes it"]+ return [line + "no window one or two lengths long closes it — it swings on a beat of its own"]def measure_jolt(frames: list[Image.Image], *, facing: str = "right") -> dict[str, Any]:diff --git a/tests/video/test_loop_prop_seam.py b/tests/video/test_loop_prop_seam.pyindex be698a3..c46be8e 100644--- a/tests/video/test_loop_prop_seam.py+++ b/tests/video/test_loop_prop_seam.py@@ -78,7 +78,7 @@ def test_motion_auto_does_not_cut_where_the_staff_jumps(tmp_path):# One step long, or two where the staff below the tip closes only there: a staff swaying every 61# frames turns back at the wrap of every one-step cut whose tip closes (docs/loop-repair.md# section 3, "The held side"), and a window two steps long is marked so.- if cycle.get("cycles") == 2:+ if "steps" in cycle:assert cycle["length"] in (2 * STEP - 1, 2 * STEP, 2 * STEP + 1)else:assert cycle["length"] in (STEP - 1, STEP, STEP + 1)diff --git a/tests/video/test_loop_prop_seam_held.py b/tests/video/test_loop_prop_seam_held.pyindex 3adbee7..3762002 100644--- a/tests/video/test_loop_prop_seam_held.py+++ b/tests/video/test_loop_prop_seam_held.py@@ -1,12 +1,13 @@# SPDX-License-Identifier: Apache-2.0-"""A held staff that swings once in two steps closes below the hand only on a cut two steps long+"""A held staff that swings once a cycle closes below the hand only on a cut two steps long(docs/loop-repair.md section 3, "The held side").-The walker steps every 24 frames; the staff it holds turns about the hand once every 48, its tip-above the head one way and its foot below the hand the other. A cut one step long whose top closes-takes the staff where its tip passes the same place moving the other way: the top band reads no-jump, and the foot swings back at the wrap. `--anchor motion-auto` reads the held side's edge on a-cut whose top popped, and takes a window two steps long when no one-step cut closes it.+The walker's legs come back every 24 frames — a step, as the search reads it; the staff it holds+turns about the hand once every 48, once a cycle of two steps, as the arm that holds it swings, its+tip above the head one way and its foot below the hand the other. A cut one step long whose top+closes takes the staff where its tip passes the same place moving the other way: the top band reads+no jump, and the foot swings back at the wrap. `--anchor motion-auto` reads the held side's edge on a+cut whose top popped, and takes a window two steps long — one cycle — when no one-step cut closes it.Synthetic frames only; the staff's foot is known in closed form, so the tests read the cut against it."""@@ -102,14 +103,17 @@ def test_motion_auto_takes_two_steps_where_the_held_staff_closes_only_there(heldcalm_one_step = [r for r in cycle["candidates"] if r.get("held_edge") is not None]assert calm_one_step and all(r["held_edge"] >= repair.HELD_EDGE_REFERENCE for r in calm_one_step)assert min(_foot_miss(r["start"], r["length"]) for r in calm_one_step) > 1.5- # So the cut is two steps long, and the staff's foot closes there.- assert cycle["cycles"] == 2 and cycle["length"] in (2 * STEP - 1, 2 * STEP, 2 * STEP + 1)+ # So the cut is two steps long — one cycle, the step it is two of recorded — and the staff's foot closes there.+ assert cycle["length"] in (2 * STEP - 1, 2 * STEP, 2 * STEP + 1) and cycle["period_local"] == cycle["length"]+ steps = cycle["steps"]+ assert steps["count"] == 2 and steps["by"] == "held-edge" and set(steps["step_lengths"]) <= {STEP - 1, STEP, STEP + 1}+ assert cycle["coverage"] == round((FRAMES - cycle["length"]) / cycle["length"], 4)held_edge = shape["held_edge"]- assert held_edge["side"] == "right" and held_edge["cycles"] == 2+ assert held_edge["side"] == "right" and held_edge["doubled"] is Trueassert held_edge["chosen"] == {"start": cycle["start"], "length": cycle["length"], "seam": held_edge["chosen"]["seam"], "closes": True}- assert shape["chosen"]["cycles"] == 2 and shape["applied"] is True+ assert shape["chosen"]["steps"] == 2 and shape["applied"] is Truestrip = json.loads((root / "out" / "loop.strip.json").read_text())- assert strip["cycles"] == 2 and strip["cycle_frames"] == cycle["length"]+ assert strip["steps"] == 2 and "cycles" not in strip and strip["cycle_frames"] == cycle["length"]assert not any("held part" in line for line in report["jolt"]["warnings"])@@ -121,9 +125,9 @@ def test_a_held_part_that_swings_with_the_step_is_cut_one_step_long(tmp_path):cycle = report["cycle"]shape = cycle["seam_pop"]assert shape["first_choice"]["pop"] > repair.SEAM_POP_REFERENCE and shape["applied"] is True- assert "cycles" not in cycle and cycle["length"] in (STEP - 1, STEP, STEP + 1)- assert shape["held_edge"]["cycles"] == 1 and shape["held_edge"]["chosen"]["closes"] is True- assert "two_cycle" not in shape["held_edge"]+ assert "steps" not in cycle and cycle["length"] in (STEP - 1, STEP, STEP + 1)+ assert shape["held_edge"]["doubled"] is False and shape["held_edge"]["chosen"]["closes"] is True+ assert "two_step" not in shape["held_edge"]assert _foot_miss(cycle["start"], cycle["length"], STEP) <= 0.5@@ -133,23 +137,23 @@ def test_a_held_part_no_window_closes_is_kept_on_the_top_bands_choice_and_warnedreport = _cut(tmp_path, _keyed(tmp_path, tip_swing=SWING, foot_swing=37))cycle = report["cycle"]held_edge = cycle["seam_pop"]["held_edge"]- assert "cycles" not in cycle and held_edge["two_cycle"]["closing"] == 0+ assert "steps" not in cycle and held_edge["two_step"]["closing"] == 0assert held_edge["chosen"]["closes"] is False and held_edge["chosen"]["seam"] >= repair.HELD_EDGE_REFERENCElines = [line for line in report["jolt"]["warnings"] if "held part does not close" in line]assert len(lines) == 1 and "right side" in lines[0]-def test_an_explicit_max_len_is_not_widened_by_a_window_two_cycles_long(tmp_path):+def test_an_explicit_max_len_is_not_widened_by_a_window_two_steps_long(tmp_path):"""--max-len 25 is the caller's ceiling: the windows two steps long (47-49 frames) that would closethe staff are over it and are not read. The cut is the top band's, one step long, and the jolt saysthe held part does not close and why nothing longer was looked at."""report = _cut(tmp_path, _keyed(tmp_path), "--max-len", "25")cycle = report["cycle"]- assert cycle["length"] <= 25 and "cycles" not in cycle+ assert cycle["length"] <= 25 and "steps" not in cycleheld_edge = cycle["seam_pop"]["held_edge"]- assert held_edge["two_cycle_capped"] == {"max_len": 25, "lengths_over": [2 * STEP - 1, 2 * STEP + 1]}- assert "two_cycle" not in held_edge and held_edge["chosen"]["closes"] is False- assert "cycles" not in json.loads((tmp_path / "out" / "loop.strip.json").read_text())+ assert held_edge["two_step_capped"] == {"max_len": 25, "lengths_over": [2 * STEP - 1, 2 * STEP + 1]}+ assert "two_step" not in held_edge and held_edge["chosen"]["closes"] is False+ assert "steps" not in json.loads((tmp_path / "out" / "loop.strip.json").read_text())(line,) = [line for line in report["jolt"]["warnings"] if "held part does not close" in line]assert "over --max-len 25" in line@@ -157,7 +161,7 @@ def test_an_explicit_max_len_is_not_widened_by_a_window_two_cycles_long(tmp_pathdef test_a_walk_whose_top_does_not_pop_reads_nothing_below_it(tmp_path):report = _cut(tmp_path, _keyed(tmp_path, staff=False))shape = report["cycle"]["seam_pop"]- assert shape["applied"] is False and "held_edge" not in shape and "cycles" not in report["cycle"]+ assert shape["applied"] is False and "held_edge" not in shape and "steps" not in report["cycle"]assert not any(r.get("held_edge") is not None for r in report["cycle"]["candidates"])@@ -219,10 +223,13 @@ def test_held_edge_verdict_speaks_only_for_a_held_side_that_does_not_close():(line,) = repair.held_edge_verdict({"held_edge": {"side": "right", "reference": 1.2,"chosen": {"start": 0, "length": 23, "skipped": "the clip has no two frames"}}})assert "could not be read at this cut" in line- capped = {"held_edge": {**misses["held_edge"], "two_cycle_capped": {"max_len": 25, "lengths_over": [45, 47]}}}+ capped = {"held_edge": {**misses["held_edge"], "two_step_capped": {"max_len": 25, "lengths_over": [45, 47]}}}(line,) = repair.held_edge_verdict(capped)- assert "no window one cycle long closes it" in line and "(45-47 frames) are over --max-len 25" in line+ assert "no window one length long closes it" in line and "(45-47 frames) are over --max-len 25" in lineassert "beat of its own" not in line+ counted = {"held_edge": {**misses["held_edge"], "two_step": {"read": False, "why": "the steps were counted"}}}+ (line,) = repair.held_edge_verdict(counted)+ assert "no window of the counted length closes it" in line and "beat of its own" not in line# --- choosing on it ---------------------------------------------------------------------------@@ -259,54 +266,62 @@ def _pop(table, default=0.0):ROWS = [{"start": 0, "length": 24, "score": 1.0}, {"start": 3, "length": 24, "score": 1.01}, {"start": 6, "length": 24, "score": 1.05}]-def test_shape_rank_takes_a_one_cycle_cut_whose_held_side_closes():+def test_shape_rank_takes_a_one_length_cut_whose_held_side_closes():candidates = [dict(r) for r in ROWS]fake = _FakeHeld({(3, 24): 1.0, (6, 24): 0.5})chosen, record = local_cycle._shape_rank(candidates, candidates[0], _pop({(0, 24): 14.0}), fake)- assert chosen["start"] == 6 and record["held_edge"]["cycles"] == 1+ assert chosen["start"] == 6 and record["held_edge"]["doubled"] is Falseassert record["chosen"] == {"start": 6, "length": 24, "pop": 0.0}- assert all(length == 24 for _, length in fake.read) # nothing two cycles long was read+ assert all(length == 24 for _, length in fake.read) # nothing two lengths long was read-def test_shape_rank_takes_two_cycles_when_no_one_cycle_cut_closes_and_never_an_unread_one():+def test_shape_rank_takes_two_steps_when_no_one_length_cut_closes_and_never_an_unread_one():candidates = [dict(r) for r in ROWS]fake = _FakeHeld({(3, 24): "the clip has no two frames either side of the cut to read its wrap against",(10, 48): 0.9, (12, 47): 0.4, (20, 49): 0.3})chosen, record = local_cycle._shape_rank(candidates, candidates[0], _pop({(0, 24): 14.0, (20, 49): 12.0}), fake)- # (20, 49) closes below but its top pops: not taken. (12, 47) has the smallest held seam left.- assert (chosen["start"], chosen["length"], chosen["cycles"]) == (12, 47, 2)+ # (20, 49) closes below but its top pops: not taken. (12, 47) has the smallest held seam left: two+ # steps of 24 — one cycle, screened as one (`period_local` is its own length).+ assert (chosen["start"], chosen["length"], chosen["period_local"]) == (12, 47, 47)+ assert chosen["steps"] == {"count": 2, "by": "held-edge", "step_lengths": [24]}held = record["held_edge"]- assert held["cycles"] == 2 and held["unread"] == 1 and held["two_cycle"]["closing"] == 2- assert held["two_cycle"]["top_pops"] == 1 and held["two_cycle"]["lengths"] == [47, 49]+ assert held["doubled"] is True and held["unread"] == 1 and held["two_step"]["closing"] == 2+ assert held["two_step"]["top_pops"] == 1 and held["two_step"]["lengths"] == [47, 49]assert candidates[1]["held_edge"] is None and candidates[1]["held_edge_skipped"]- assert record["chosen"] == {"start": 12, "length": 47, "pop": 0.0, "cycles": 2}+ assert record["chosen"] == {"start": 12, "length": 47, "pop": 0.0, "steps": 2}-def test_shape_rank_reads_no_window_two_cycles_long_over_the_length_cap():+def test_shape_rank_reads_no_window_two_lengths_long_over_the_length_cap_nor_once_the_steps_are_counted():table = {(10, 48): 0.9, (12, 47): 0.4, (20, 49): 0.3}- # Under a cap of 46 no window two cycles long is read: the top band's choice, and the record says why.+ # Under a cap of 46 no window two lengths long is read: the top band's choice, and the record says why.candidates = [dict(r) for r in ROWS]fake = _FakeHeld(dict(table))chosen, record = local_cycle._shape_rank(candidates, candidates[0], _pop({(0, 24): 14.0}), fake, length_cap=46)- assert (chosen["start"], chosen["length"]) == (3, 24) and "cycles" not in chosen+ assert (chosen["start"], chosen["length"]) == (3, 24) and "steps" not in chosenassert all(length <= 46 for _, length in fake.read)held = record["held_edge"]- assert held["two_cycle_capped"] == {"max_len": 46, "lengths_over": [47, 49]} and "two_cycle" not in held+ assert held["two_step_capped"] == {"max_len": 46, "lengths_over": [47, 49]} and "two_step" not in held# A cap of 48 reads 47 and 48 only: (20, 49) is over it, so (12, 47) is taken.candidates = [dict(r) for r in ROWS]fake = _FakeHeld(dict(table))chosen, record = local_cycle._shape_rank(candidates, candidates[0], _pop({(0, 24): 14.0}), fake, length_cap=48)- assert (chosen["start"], chosen["length"], chosen["cycles"]) == (12, 47, 2)- assert record["held_edge"]["two_cycle"]["lengths"] == [47, 48] and max(length for _, length in fake.read) == 48- assert record["held_edge"]["two_cycle_capped"] == {"max_len": 48, "lengths_over": [49, 49]}+ assert (chosen["start"], chosen["length"], chosen["steps"]["count"]) == (12, 47, 2)+ assert record["held_edge"]["two_step"]["lengths"] == [47, 48] and max(length for _, length in fake.read) == 48+ assert record["held_edge"]["two_step_capped"] == {"max_len": 48, "lengths_over": [49, 49]}+ # Counted steps (`double` false): the length is the count's, and nothing twice it is read.+ candidates = [dict(r) for r in ROWS]+ fake = _FakeHeld(dict(table))+ chosen, record = local_cycle._shape_rank(candidates, candidates[0], _pop({(0, 24): 14.0}), fake, double=False)+ assert (chosen["start"], chosen["length"]) == (3, 24) and all(length == 24 for _, length in fake.read)+ assert record["held_edge"]["two_step"] == {"read": False, "why": "the steps were counted (--steps): no window twice as long is read"}def test_shape_rank_without_a_closing_window_keeps_the_top_bands_choice_and_records_it():candidates = [dict(r) for r in ROWS]chosen, record = local_cycle._shape_rank(candidates, candidates[0], _pop({(0, 24): 14.0}), _FakeHeld({}, frames=60))- assert chosen["start"] == 3 and record["chosen"]["pop"] == 0.0 and "cycles" not in chosen+ assert chosen["start"] == 3 and record["chosen"]["pop"] == 0.0 and "steps" not in chosenassert record["held_edge"]["chosen"] == {"start": 3, "length": 24, "seam": 5.0, "closes": False}- assert record["held_edge"]["two_cycle"]["closing"] == 0+ assert record["held_edge"]["two_step"]["closing"] == 0# A side that cannot be read: the top band's choice, and the record says why.candidates = [dict(r) for r in ROWS]chosen, record = local_cycle._shape_rank(candidates, candidates[0], _pop({(0, 24): 14.0}), _FakeHeld({}, side="no head"))@@ -322,29 +337,32 @@ def test_shape_rank_reads_no_held_side_when_the_first_choice_does_not_pop():# --- the set -----------------------------------------------------------------------------------def test_cycle_align_keeps_a_two_cycle_loop_two_cycles_at_twice_the_set_length(held, tmp_path):- """The two-step loop is counted already: not a suspect to stop on, resampled to twice the length- the set takes from its one-step loop, and still marked two cycles."""+def test_cycle_align_aligns_a_two_step_loop_as_the_one_cycle_it_is(held, tmp_path):+ """The loop cut two steps long is one cycle: it returns half way at its second step, which is no+ suspect (status `steps`), and it is resampled to the set's length like the rest — the set's length+ the median of the loops as cut, nothing kept twice as long."""root, report = held- one_step = tmp_path / "plain"- plain = _cut(one_step, _keyed(one_step, staff=False))+ other = tmp_path / "plain"+ plain = _cut(other, _keyed(other, staff=False))lengths = [report["cycle"]["length"], plain["cycle"]["length"]]- out = align.align_set([root / "out", one_step / "out"], between="nearest")+ out = align.align_set([root / "out", other / "out"], between="nearest")two, one = out["loops"]- target = round(float(np.median([lengths[0] / 2, lengths[1]])))- assert out["length"] == target and two["to"] == 2 * target and one["to"] == target- assert two["cycles_kept"] == 2 and "cycles_kept" not in one- assert all(e["status"] == "declared" for e in out["suspects"] if e["dir"] == str((root / "out").resolve()))- assert json.loads((root / "out" / "loop.strip.json").read_text())["cycles"] == 2- assert "cycles" not in json.loads((one_step / "out" / "loop.strip.json").read_text())- # A count given for it is still the last word: one cycle taken out of it, no longer marked two.- out = align.align_set([root / "out", one_step / "out"], between="nearest", cycles={str(root / "out"): 2})- assert out["loops"][0]["cycles_kept"] == 1 and "cycle_taken" in out["loops"][0]- assert "cycles" not in json.loads((root / "out" / "loop.strip.json").read_text())---# What v2.35.0 wrote for a loop cut one cycle long (no `cycles` in its strip metadata): aligning it-# writes exactly these, so a set without a held part is rewritten as before.+ target = round(float(np.median(lengths)))+ assert out["applied"] is True and out["length"] == target and two["to"] == target and one["to"] == target+ assert "cycles_kept" not in two and "cycles_kept" not in one+ mine = [e for e in out["suspects"] if e["dir"] == str((root / "out").resolve())]+ assert mine and all(e["status"] == "steps" and e["steps"] == 2 and [c["cycles"] for c in e["candidates"]] == [2] for e in mine)+ assert isinstance(report["cycle"]["ratio"], float) # a window two lengths long reads its wrap as a candidate does+ assert json.loads((root / "out" / "loop.strip.json").read_text())["steps"] == 2+ assert "steps" not in json.loads((other / "out" / "loop.strip.json").read_text())+ # A count given for it is still the last word: one half taken out of it, no longer two steps.+ out = align.align_set([root / "out", other / "out"], between="nearest", cycles={str(root / "out"): 2})+ assert "cycle_taken" in out["loops"][0]+ assert "steps" not in json.loads((root / "out" / "loop.strip.json").read_text())+++# What v2.35.0 wrote for a loop whose steps nobody counted (no `steps` in its strip metadata):+# aligning it writes exactly these, so a set without a held part is rewritten as before.STRIP_KEYS_2350 = {"body_h", "body_height_target", "body_ref", "body_src_h", "cell_cap", "cell_height_cap", "cycle_align","cycle_drawings", "cycle_frames", "cycle_seconds", "delay_ms", "drawings", "drift_px", "foot_anchor","foot_sway_px", "foot_x", "frames", "h", "kind", "loop", "motion_anchor", "scale", "state", "subsampled",@@ -362,7 +380,7 @@ def test_cycle_align_writes_a_loop_without_a_held_part_as_before(tmp_path):shutil.copytree(src / "out", tmp_path / name)dirs.append(tmp_path / name)out = align.align_set(dirs, between="nearest")- assert all("cycles_kept" not in row for row in out["loops"])+ assert all("cycles_kept" not in row and "steps" not in row for row in out["loops"])for d in dirs:meta = json.loads((d / "loop.strip.json").read_text())assert set(meta) == STRIP_KEYS_2350 and set(meta["cycle_align"]) == CYCLE_ALIGN_KEYS_2350diff --git a/tests/video/test_one_step_cut.py b/tests/video/test_one_step_cut.pynew file mode 100644index 0000000..462cc11--- /dev/null+++ b/tests/video/test_one_step_cut.py@@ -0,0 +1,254 @@+# SPDX-License-Identifier: Apache-2.0+"""A walk slower than its window is cut one step long; the step screen says so, and a count of the+steps cuts it again (docs/loop-repair.md section 3, "The step screen").++The walker's cycle is 42 frames, 1.75 s at 24 fps — longer than the walk window holds in a three-second+clip (half of it, 36). Its legs are drawn alike, so one step on (21 frames) they have swapped and the+picture is the same; its arms are shaded apart, so one step on they have swapped and show it. The+search finds the step and cuts it: the loop walks on one leg, and its arms jump at the wrap. Twice the+cut, 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.++Synthetic frames only; the arm's place is known in closed form, so the tests read the cut against it."""++from __future__ import annotations++import json+import math+import shutil+from pathlib import Path++import pytest+from PIL import Image, ImageDraw++from sprite_gen.video import align, batch, loop, period++CYCLE, FRAMES = 42, 73+++def _arm(k: float, cycle: float = CYCLE) -> float:+ """The near arm's sideways place against the body, px; the far arm is its mirror."""+ return 16 * math.sin(2 * math.pi * k / cycle)+++def _strider(k: int, cycle: float = CYCLE) -> Image.Image:+ """A side walker: legs drawn alike, half a cycle apart; arms opposite, the far one darker."""+ ph = 2 * math.pi * k / cycle+ im = Image.new("RGBA", (260, 220))+ d = ImageDraw.Draw(im)+ x = 60 + round(k * 0.5)+ y = 40 + round(3 * math.cos(2 * ph))+ sw = _arm(k, cycle)+ d.rectangle((x + 14 - sw - 4, y + 34, x + 14 - sw + 4, y + 72), fill=(150, 150, 150, 255)) # far arm, behind+ 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))+ d.rectangle((x, y + 30, x + 28, y + 84), fill=(200, 80, 80, 255))+ d.rectangle((x + 2, y, x + 26, y + 28), fill=(230, 200, 170, 255))+ d.rectangle((x + 14 + sw - 4, y + 34, x + 14 + sw + 4, y + 72), fill=(225, 225, 225, 255)) # near arm, in front+ d.point((x + 6, y + 40 + k % 11), fill=(250, 250, 250, 255)) # no two frames the same picture+ return im+++def _keyed(root: Path, cycle: float = CYCLE, frames: int = FRAMES) -> Path:+ keyed = root / "keyed"+ keyed.mkdir(parents=True)+ for k in range(frames):+ _strider(k, cycle).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 _arm_miss(start: int, length: int, cycle: float = CYCLE) -> float:+ """How far the cut's wrap is from the arm's own way on, in place and in speed, over the largest+ step the arm takes inside the cut: the last frame against the clip's frame before the first."""+ a = lambda k: _arm(k, cycle) # noqa: E731+ s, L = start, length+ inner = max(abs(a(k + 1) - a(k)) for k in range(s, s + L - 1))+ place = abs(a(s + L - 1) - a(s - 1))+ speed = abs((a(s + L - 1) - a(s + L - 2)) - (a(s - 1) - a(s - 2)))+ return max(place, speed) / inner++[email protected](scope="module")+def slow(tmp_path_factory) -> tuple[Path, Path, dict]:+ root = tmp_path_factory.mktemp("slow")+ keyed = _keyed(root)+ return root, keyed, _cut(root / "out", keyed)+++def test_a_walk_cut_one_step_long_is_named_by_the_step_screen(slow):+ _, _, report = slow+ cycle = report["cycle"]+ # The cycle does not fit the window: the step is cut, and its arm jumps at the wrap.+ assert cycle["length"] in (CYCLE // 2 - 1, CYCLE // 2, CYCLE // 2 + 1)+ assert _arm_miss(cycle["start"], cycle["length"]) > 3+ # Either the cut is a whole cycle, or the screen says it may be one step — v2.35.0 said nothing.+ screen = cycle.get("step_screen") or {}+ assert screen.get("suspect") is True, screen+ assert screen["lag"] in (CYCLE - 1, CYCLE, CYCLE + 1) and screen["ratio"] <= period.STEP_RATIO_MAX+ assert screen["depth"] >= loop.PERIODICITY_MIN and screen["pairs"] == FRAMES - screen["lag"]+ assert screen["coverage"] == round((FRAMES - screen["lag"]) / screen["lag"], 4)+ # Nothing is cut on it, and nothing else speaks: no warning, no `steps`.+ assert "steps" not in cycle and not any("step" in line for line in report["jolt"]["warnings"])+++def _same_but_the_screen(a: Path, b: Path) -> None:+ for name in ("loop.strip.png", "loop.gif", "loop.webp", "loop.strip.json"):+ assert (a / name).read_bytes() == (b / name).read_bytes(), name+ frames = sorted(p.name for p in (a / "cycle").glob("*.png"))+ assert 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)+ left, right = (json.loads((d / "loop.loop.report.json").read_text().replace(str(d), "@")) for d in (a, b))+ left["cycle"].pop("step_screen")+ right["cycle"].pop("step_screen")+ assert left == right++[email protected]("cycle, suspect", [(CYCLE, True), (23.5, True), (25, False)])+def test_the_step_screen_changes_nothing_but_its_own_record(tmp_path, monkeypatch, cycle, suspect):+ """A one-step cut, a cycle on a frame count that is not whole (23.5 frames: twice it repeats+ better, being whole there — a suspect that is no step) and a whole cycle of 25: with the screen+ or without it, every image, the strip metadata and the report are the same but for its record."""+ keyed = _keyed(tmp_path, cycle)+ report = _cut(tmp_path / "screened", keyed)+ assert report["cycle"]["step_screen"]["suspect"] is suspect+ monkeypatch.setattr(period, "step_screen", lambda *a, **k: {"stubbed": True})+ _cut(tmp_path / "unscreened", keyed)+ _same_but_the_screen(tmp_path / "screened", tmp_path / "unscreened")+++def test_steps_1_cuts_the_walk_again_two_steps_long_where_its_arms_close(slow, tmp_path):+ root, keyed, first = slow+ report = _cut(tmp_path / "out", keyed, "--steps", "1")+ cycle = report["cycle"]+ assert cycle["length"] in (CYCLE - 1, CYCLE, CYCLE + 1)+ L = first["cycle"]["length"]+ assert cycle["steps"] == {"count": 2, "by": "given", "given": 1,+ "first_cut": {"start": first["cycle"]["start"], "length": L}, "window": [2 * L - 1, 2 * L + 1]}+ # The arms close at the wrap: the last frame is where, and moves as, the frame before the first.+ assert _arm_miss(cycle["start"], cycle["length"]) <= 1.0+ # Two steps in it, the clip holding most of a second cycle past it: no warning about its coverage.+ assert cycle["step_screen"]["leg_peaks"] == {"by": "stride", "count": 2}+ assert cycle["coverage"] == round((FRAMES - cycle["length"]) / cycle["length"], 4) > loop.COVERAGE_MIN+ assert cycle["choice"] == "closure" and not any("two steps long" in line for line in report["jolt"]["warnings"])+ strip = json.loads((tmp_path / "out" / "loop.strip.json").read_text())+ assert strip["steps"] == 2 and strip["cycle_frames"] == cycle["length"]+++def test_steps_2_keeps_the_cut_and_records_the_count(slow, tmp_path):+ root, keyed, first = slow+ report = _cut(tmp_path / "out", keyed, "--steps", "2")+ assert {k: report["cycle"][k] for k in ("start", "length")} == {k: first["cycle"][k] for k in ("start", "length")}+ assert report["cycle"]["steps"] == {"count": 2, "by": "given", "given": 2}+ assert json.loads((tmp_path / "out" / "loop.strip.json").read_text())["steps"] == 2+ for name in ("loop.strip.png", "loop.gif", "loop.webp"):+ assert (tmp_path / "out" / name).read_bytes() == (root / "out" / name).read_bytes()+++def test_a_counted_cut_the_clip_cannot_see_repeat_is_cut_and_warned_about(tmp_path):+ """50 frames hold the 42-frame cycle with 8 to spare: no window that long is seen repeating. The+ count stands for the repeat, the cut whose wrap the clip plays is taken, and its coverage — under a+ quarter of a cycle past it — is a warning, not a failure; the seam gate judges it as any cut."""+ keyed = _keyed(tmp_path, frames=50)+ report = _cut(tmp_path / "out", keyed, "--steps", "1")+ cycle = report["cycle"]+ assert cycle["length"] in (CYCLE - 1, CYCLE, CYCLE + 1) and cycle["method"] == "counted-window-v1"+ assert "no periodic cycle found" in cycle["unseen"]+ assert cycle["coverage"] == round((50 - cycle["length"]) / cycle["length"], 4) < loop.COVERAGE_MIN+ (line,) = [line for line in report["jolt"]["warnings"] if "two steps long" in line]+ assert f"holds {cycle['coverage']:.2f} of a cycle past it" in line+ assert report["resampled_seam_ratio"] <= loop.SEAM_RATIO_MAX+++def test_an_explicit_window_past_half_the_clip_is_the_window(slow, tmp_path):+ """--min-len 41 --max-len 43 asks for the cycle the window could not hold. v2.35.0 cut the ceiling+ back to half the clip (36) and found no window [41, 36]; the caller's ceiling is the ceiling."""+ _, keyed, _ = slow+ report = _cut(tmp_path / "out", keyed, "--min-len", str(CYCLE - 1), "--max-len", str(CYCLE + 1))+ assert report["cycle"]["length"] in (CYCLE - 1, CYCLE, CYCLE + 1) and report["window"] == [CYCLE - 1, CYCLE + 1]+++def test_steps_needs_motion_auto(slow, tmp_path):+ _, keyed, _ = slow+ with pytest.raises(SystemExit, match="--steps counts the steps in the cut --anchor motion-auto takes"):+ loop.main(["--frames-dir", str(keyed), "--out-dir", str(tmp_path / "out"), "--state", "walk", "--steps", "1"])+++# --- the set ----------------------------------------------------------------------------------++def _set(root: Path, side: Path) -> list[Path]:+ """A set of the slow walker cut as a whole cycle (front, by its window) and the side given."""+ dirs = []+ for name, source in (("front", root / "front"), ("side", side)):+ shutil.copytree(source, root / "set" / name)+ dirs.append(root / "set" / name)+ return dirs+++def test_cycle_align_stops_on_a_loop_that_may_be_one_step_and_names_the_count_that_settles_it(slow, tmp_path):+ root, keyed, _ = slow+ whole = _keyed(tmp_path / "whole", cycle=25)+ _cut(tmp_path / "front", whole)+ dirs = _set(tmp_path, root / "out")+ with pytest.raises(align.CycleSuspects) as stop:+ align.align_set(dirs, between="nearest")+ (entry,) = stop.value.suspects+ assert entry["dir"] == str(dirs[1].resolve()) and entry["status"] == "stopped" and entry["candidates"] == []+ assert entry["one_step"]["lag"] in (CYCLE - 1, CYCLE, CYCLE + 1) and entry["one_step"]["report"] == str((dirs[1] / "loop.loop.report.json").resolve())+ assert entry["settle"] == [f"--cycles {dirs[1].resolve()}=1"]+ assert "may be one step" in str(stop.value) and "--steps 1" in str(stop.value)+ # Nothing was rewritten: the side loop is as cut.+ assert (dirs[1] / "loop.strip.png").read_bytes() == (root / "out" / "loop.strip.png").read_bytes()+ # warn aligns it as it is and says so; a count of one cycle settles it.+ out = align.align_set(dirs, between="nearest", multi_cycle="warn")+ assert out["applied"] is True and any("one step where the rest play two" in line for line in out["warnings"])+ out = align.align_set(dirs, between="nearest", cycles={str(dirs[1]): 1})+ assert out["applied"] is True and out["suspects"][0]["status"] == "counted"+++def test_cycle_align_takes_the_loop_cut_again_on_its_count(slow, tmp_path):+ root, keyed, _ = slow+ whole = _keyed(tmp_path / "whole", cycle=25)+ _cut(tmp_path / "front", whole)+ _cut(tmp_path / "recut", keyed, "--steps", "1")+ dirs = _set(tmp_path, tmp_path / "recut")+ out = align.align_set(dirs, between="nearest")+ lengths = [json.loads((d / "loop.loop.report.json").read_text())["cycle"]["length"] for d in dirs]+ assert out["applied"] is True and out["length"] == round((lengths[0] + lengths[1]) / 2)+ (entry,) = out["suspects"] # its half is its step: no suspect to stop on+ assert entry["dir"] == str(dirs[1].resolve()) and entry["status"] == "steps" and [c["cycles"] for c in entry["candidates"]] == [2]+ assert all("cycles_kept" not in row for row in out["loops"])+++# --- video-set ----------------------------------------------------------------------------++def test_video_set_names_a_loop_that_may_be_one_step_and_its_table_says_so(slow, tmp_path, capsys):+ """A video-set item keeps the cut's report beside its loop directory (`<item>/loop.report.json`):+ the alignment reads the step screen there, and the set stops on the side walk with what settles it."""+ _, keyed, _ = slow+ rows = []+ for direction, source in (("front", _keyed(tmp_path / "whole", cycle=25)), ("side", keyed)):+ item = tmp_path / f"{direction}-walk"+ lp = loop.run_loop(source, item / "loop", fps=24.0, state="walk", min_len=None, max_len=None, n_out=None,+ seam_max=loop.SEAM_RATIO_MAX, name=f"{direction}-walk", report_path=item / "loop.report.json",+ anchor="motion-auto", repair="off")+ rows.append({"item": f"{direction}-walk", "direction": direction, "state": "walk", "dir": str(item), "ok": True,+ "loop": {"cycle": lp["cycle"]["length"], "period": None, "seam_ratio": 1.0, "n_out": lp["n_out"],+ **({"step_screen": lp["cycle"]["step_screen"]} if lp["cycle"]["step_screen"]["suspect"] else {})}})+ out = batch.align_gaits(rows, tmp_path, "auto", interpolate=None, between="nearest")+ walk = out["walk"]+ assert walk["applied"] is False and walk["reason"] == "cycle-suspects"+ assert walk["why"].startswith("side-walk may be one step (cut it again with video-loop --steps 1 if it is)")+ assert walk["suspects"][0]["one_step"]["report"] == str((tmp_path / "side-walk" / "loop.report.json").resolve())+ assert "cycles not aligned" in capsys.readouterr().err+ table = batch.write_table(rows, tmp_path / "table.md")+ assert f"| {rows[1]['loop']['cycle']} (one step?) |" in table and f"| {rows[0]['loop']['cycle']} |" in table+ rows[1]["loop"] = {**rows[1]["loop"], "cycle": 42, "steps": 2}+ rows[1]["loop"].pop("step_screen")+ assert "| 42 (2 steps) |" in batch.write_table(rows, tmp_path / "table.md")