Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
feat(video-loop): a walk or run cut one step long under the gait floor is cut two lengths long where the clip as filmed comes back nearer two lengths on than one
Soohong Kime2081d5dd744
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f2da449..ea4374d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -82,9 +82,10 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the- **Fixed: `video-loop --anchor motion-auto` no longer refuses a walk or run for its opening frames alone.** Where `auto_motion.discover` finds no two regions through the whole clip (`automatic motion anchor needs two separated regions trackable throughout the clip`, or `found no stable textured region`), the analysis is read again on the clip after the fewest frames it opens on, fewer than the window's shortest cut, with which the anchor finds its two regions through the rest (`auto_motion.analyse_after_opening`, new exception `auto_motion.RegionsUnfound`). A clip filmed from a still opens on that still and on the standing pose the body sets off from, and the regions the middle of the clip shows may be out of the anchor's reach there; the refusal came before the search, so the gait fallback never ran. Those frames are left out of the search as a lead-in is (`lead_in.search_from`, every frame number the clip's own), recorded in the report's new `untracked_opening` (`frames`, `first`, `shorter_than`, `refused`) and, once a cut is found, a warning line `video-loop: warning: the automatic motion anchor found its two regions from frame <k> on, not from the clip's first frames: ...` that does not repeat the refusal's words. Where no such opening leaves the clip tracked, it is refused in the same words as before, followed by ` — nor through the clip after any of its first 1 to <n> frames left out (an opening shorter than the shortest cut, <n + 1> frames)`; where the cut the search took holds no two regions when its frames are read again for the correction, the refusal now ends ` — on the cut the search took (frames <a>-<b>)`. Tests: `tests/video/test_auto_motion_opening.py` (a synthetic walker whose first three frames carry its head and torso 90 px forward: refused as filmed before, now cut after them with every frame number the clip's own; the same walker without them unchanged; the lean again mid-clip refused with the new words).-**Upgrading from 3.5.0: a walk or run cut shorter than its state's gait floor, its steps not counted, now says so (`cycle.half_step` and a warning line); every cut and image is as before.**+**Upgrading from 3.5.0: a walk or run cut shorter than its state's gait floor, its steps not counted, is now cut two steps long under `--anchor motion-auto` where the clip as filmed comes back nearer two lengths on than one, and says so where it does not (`cycle.half_step` and a warning line); every other cut keeps every byte.**- **New: `video-loop` names a half-step cut.** A walk or run loops on an even number of steps (two, one cycle). The half-period guard reads the gait floor (`LoopProfile.min_seconds`) in whole frames, rounded, so a run cut 8 frames long at 24 fps (0.33 s, under the run's 0.35 s) is taken as two steps. Such a periodic cut whose steps nothing counted (no `cycle.steps`) is kept, recorded in `cycle.half_step` (`rule`, `state`, `seconds`, `gait_floor`, `why`, `two_steps`; in the stdout summary too) and named in a warning line that suggests `--steps 1`; the line repeats no refusal's words. Python callers: `loop.half_step`, `loop.half_step_verdict`, `loop.HALF_STEP_RULE`. Docs: [video-pipeline.md](docs/video-pipeline.md) section 4. **Tests**: `tests/video/test_loop_half_step.py`.+- **Changed: `video-loop --anchor motion-auto` cuts such a cut two lengths long where the clip says it holds two steps.** One step on, the legs are back in place with near and far swapped, and where they are drawn alike the silhouette repeats; the body's turn, the shading across the torso and the folds of the clothes come back only two steps on. Each length of [2L − 1, 2L + 1] is cut as `--steps 1` cuts it, and about each cut's wrap (two frames either side of its first) the frames as filmed are read two lengths on over one length on; the nearest at most 0.85 (`period.STEP_RATIO_MAX`, the step screen's bound) whose seam and seam pop gates pass is taken, recorded `cycle.steps` `{"count": 2, "by": "two-lengths", ...}` and `cycle.two_lengths` (`first_cut`, `tried`, `cut`, `taken`; in the stdout summary too). It is read on the frames as filmed, not on the search's distances, which move every frame by one vertical slope fitted over the clip: a slope tilted by frames that open higher moves frames two steps apart further than one step apart where the body runs in place, so two lengths on read no nearer there. A cut the clip gives no two is kept and named as above, the warning line saying why (`cycle.half_step.two_lengths`). Python callers: `loop.two_lengths_on`, `loop.TWO_LENGTHS_AROUND`. **Tests**: `tests/video/test_loop_two_lengths.py`.## v3.5.0 - Widened square canvas framing for side walk and run stride and trailing parts, measured background matte cutout for flat backgrounds of any colour, and failure when a cutout removes nothingdiff --git a/docs/loop-repair.md b/docs/loop-repair.mdindex 4745222..7d7b491 100644--- a/docs/loop-repair.md+++ b/docs/loop-repair.md@@ -1414,7 +1414,10 @@ not whole — a cycle of 23.5 frames cut at 24 repeats better at 47, being wholeonly 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 withoutit; 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+lag past the clip (fewer than 4 pairs) is not read: `lag` null, not a suspect. A cut under the gait+floor is the exception: it is one step by its length, and the clip is asked whether it holds two about+the doubled cut's wrap, on the frames as filmed — not over the whole clip — and cut two lengths long+where it does ([video pipeline](video-pipeline.md) section 4, "A cut under the gait floor"). The synthetic walkerof `tests/video/test_one_step_cut.py` — a 42-frame cycle, legs drawn alike and arms shaded apart, 73frames, its feet read as unseen — is cut at 21 (`ratio` 0.48, a suspect); the same drawing on a25-frame cycle is cut at 25 (`ratio` 1.53), and on 23.5 frames at 24 (`ratio` 0.66: a suspect that is a@@ -1433,7 +1436,9 @@ the cut it takes without `--steps` holds.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]}`, with- `counted_window` beside `window` where an explicit window left only part of [2L − 1, 2L + 1].+ `counted_window` beside `window` where an explicit window left only part of [2L − 1, 2L + 1]. A cut+ under the gait floor that the clip itself gives two steps is cut the same way, one length at a time,+ and recorded `"by": "two-lengths"` without `given`.- **`--steps 2`**: the cut is a cycle already; it is kept, and recorded `{"count": 2, "by":"given", "given": 2}`.diff --git a/docs/video-pipeline.md b/docs/video-pipeline.mdindex f7f0954..90ca0b7 100644--- a/docs/video-pipeline.md+++ b/docs/video-pipeline.md@@ -414,17 +414,37 @@ and a true cycle half a drawing late are **the same picture**. So`video-loop` cuts the period it always cut, and only **records** what a half or a third of it shows(`cycle.fundamental`, `sprite_gen/video/period.py`).-**A cut under the gait floor is named a half step.** A walk or run loops on an even number of steps —-two, one cycle; a loop of one step plays the same leg leading every time round. The gait floor-(`LoopProfile.min_seconds`: walk 0.6 s, run 0.35 s) is the duration under which a period is one step,-and the half-period guard reads it in whole frames, rounded, to choose among candidates: a run cut 8-frames long at 24 fps (0.33 s) is taken. Such a periodic cut (`--cycle auto` or `periodic`) whose steps-nothing counted — no `cycle.steps`: not the clip's crossings, `--steps` or the held side's two lengths —-is kept as cut, recorded in `cycle.half_step` (`rule`, `state`, `seconds`, `gait_floor` in seconds and-frames, `why` the steps were not counted, `two_steps`: twice the cut and whether the clip holds it) and-named in a warning line (`loop.half_step`, `HALF_STEP_RULE`). Nothing is cut again on it: where the two-legs are drawn alike the pixels cannot count the steps, and a clip that draws the same leg forward every-step shows the same step twice in a cut two lengths long. `--steps 1` cuts it two lengths long.+**A cut under the gait floor is one step: the clip is asked for two, and the cut is named a half step+where it gives none.** A walk or run loops on an even number of steps — two, one cycle; a loop of one+step plays the same leg leading every time round. The gait floor (`LoopProfile.min_seconds`: walk 0.6 s,+run 0.35 s) is the duration under which a period is one step, and the half-period guard reads it in+whole frames, rounded, to choose among candidates: a run cut 8 frames long at 24 fps (0.33 s) is taken.+Such a periodic cut (`--cycle auto` or `periodic`) whose steps nothing counted — no `cycle.steps`: not+the clip's crossings, `--steps` or the held side's two lengths — is one step.++Under `--anchor motion-auto` it is cut two lengths long where the clip says it holds two+(`loop._two_lengths`). One step on, the legs are back in place with near and far swapped, and where the+two are drawn alike (one colour of trousers) the silhouette repeats; the body's turn, the shading across+the torso and the folds of the clothes come back only two steps on. So each length of [2L − 1, 2L + 1]+(inside an explicit `--min-len`/`--max-len`) is cut as `--steps 1` cuts it, and about each cut's wrap+(two frames either side of its first, `TWO_LENGTHS_AROUND`) the frames as filmed are read two lengths on+over one length on, the same frames (`two_lengths_on`). The nearest at most **0.85**+(`period.STEP_RATIO_MAX`, the step screen's bound for the same ratio, which the screen reads over the+whole clip, where a run that changes its pace does not repeat) is taken where the seam gate and the seam+pop gate pass it as they will the loop; `cycle.steps` is `{"count": 2, "by": "two-lengths", "first_cut",+"window"}` and `cycle.two_lengths` records `first_cut`, `tried` (each length's cut: `near`, `one`,+`ratio`, or why it was not read), `cut` and `taken`. The frames are read as filmed, not on the search's+distances: the analysis canvas moves every frame by the drift it reads, one vertical slope over the clip,+and a slope tilted by frames that open higher moves frames two steps apart further than one step apart+where the body runs in place, so two lengths on read no nearer there. A drift the clip does walk only+makes two lengths on read farther: it keeps a cut one step, never doubles one.++A cut the clip gives no two — two lengths on no nearer, one length on the same picture, no window to+cut, a gate that would not pass it — and a cut under any other anchor are kept as cut, recorded in+`cycle.half_step` (`rule`, `state`, `seconds`, `gait_floor` in seconds and frames, `why` the steps were+not counted, `two_steps`: twice the cut and whether the clip holds it, `two_lengths`: why the clip gave+none) and named in a warning line (`loop.half_step`, `HALF_STEP_RULE`). `--steps 1` cuts it two lengths+long.**The size is held before the search or cut** (`--size-hold auto`, the default). A walk or run clip filmed from its first frame only often grows or shrinks as it plays, so the frame one cycle after the first is not the first's size and the loop pops at the wrap. Under `--size-hold auto`, a walk or run cut automatically with `--anchor motion-auto` (before the cycle search) or cut by hand with `--cycle fixed` under any anchor (before the cut is read, over the whole clip) is held at its first frame's size. When a clip's height changes by 1 % or more over the clip, read one cycle on, frames are scaled back to the first frame's size about their feet. Where the size is held and the feet climb or sink by 1 % of the first frame's height or more over the clip, frames are also shifted so their feet stand on the first frame's row. This stops a receding walk's jump at the wrap from moving into place: the motion anchor's fine search corrects a climb within 28 rows over the cut but leaves the cut uncorrected when feet climb further than that, and the body anchor moves frames sideways only.diff --git a/sprite_gen/video/local_cycle.py b/sprite_gen/video/local_cycle.pyindex 572a876..ccde979 100644--- a/sprite_gen/video/local_cycle.py+++ b/sprite_gen/video/local_cycle.py@@ -12,7 +12,9 @@ long that the window could not hold (`step_screen`), never cut longer on it:only a count of the steps cuts again — given (`video-loop --steps`), or read offthe clip's own crossings (`by_steps`, sprite_gen/video/crossings.py): where theclip shows its steps, the cut is two of them, joined at the walk's own point,-the smoothest seam first.+the smoothest seam first. A cut under the gait floor is the exception: the+clip as filmed is read two lengths on about the doubled cut's wrap+(`loop._two_lengths`)."""from __future__ import annotationsimport mathdiff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.pyindex 77cfefd..0c6b674 100644--- a/sprite_gen/video/loop.py+++ b/sprite_gen/video/loop.py@@ -1682,7 +1682,7 @@ def _by_steps(cycle: dict[str, Any] | None, refused: ValueError | None, *, framedef _counted(cycle: dict[str, Any], steps: int, *, window: CutWindow, D: np.ndarray, trajectory: np.ndarray,frames: list[Image.Image], moved: list[np.ndarray], detect: dict[str, Any], cells: CutOnCells,- turn: body_turn_mod.Turn | None = None) -> dict[str, Any]:+ turn: body_turn_mod.Turn | None = None, by: str = "given", length: int | None = None) -> dict[str, Any]:"""The cut once its steps are counted (`--steps`): 2 keeps it; 1 cuts again in the window two ofits lengths long, [2L-1, 2L+1], inside the caller's bounds (`window.within`) — not half the clip —with the same search (a repeat seen in the clip, the top band and the held side read again) save that@@ -1691,19 +1691,21 @@ def _counted(cycle: dict[str, Any], steps: int, *, window: CutWindow, D: np.ndarbounds disagree: a failure, neither followed. Where they leave part of it, that part is read(`steps.window`, beside `steps.counted_window`). A clip too short to see such a window repeat is cutall the same, the count standing for the repeat (`local_cycle.counted`, `unseen` says why);- `cycle.coverage` and the seam gate say the rest. Recorded `steps` (`first_cut`: the cut counted). With `turn`, no cut- that holds a frame of a body turn is taken."""+ `cycle.coverage` and the seam gate say the rest. Recorded `steps` (`first_cut`: the cut counted; `by`, who counted+ it: "given", or "two-lengths" where the clip did, `_two_lengths`, which reads one `length` of the window at a time).+ With `turn`, no cut that holds a frame of a body turn is taken."""first = {"start": cycle["start"], "length": cycle["length"]}if steps == 2:cycle["steps"] = {"count": 2, "by": "given", "given": 2}return cycle+ asked = "--steps 1" if by == "given" else "two lengths"counted_window = [2 * first["length"] - 1, 2 * first["length"] + 1]- lo, hi = window.within(*counted_window)- record = {"count": 2, "by": "given", "given": 1, "first_cut": first, "window": [lo, hi]}+ lo, hi = window.within(*((length, length) if length is not None else counted_window))+ record = {"count": 2, "by": by, **({"given": 1} if by == "given" else {}), "first_cut": first, "window": [lo, hi]}if [lo, hi] != counted_window:record["counted_window"] = counted_windowif lo > hi:- exc = ValueError(f"--steps 1: the cut of {first['length']} frames from {first['start']} is one step, so the cycle is "+ exc = ValueError(f"{asked}: the cut of {first['length']} frames from {first['start']} is one step, so the cycle is "f"{counted_window[0]}-{counted_window[1]} frames long, and {window.said()} leaves none of that: the count "f"and the window disagree — drop one, or give a window that holds the cycle")exc.diagnostics = {**cycle, "steps": {**record, "window": None, "refused": f"outside {window.said()}"}} # type: ignore[attr-defined]@@ -1719,7 +1721,7 @@ def _counted(cycle: dict[str, Any], steps: int, *, window: CutWindow, D: np.ndarfound = local_cycle.counted(D, trajectory, min_len=lo, max_len=hi, periodicity_min=detect["periodicity_min"],signals=signals, pop_gate=cells.gate, turn=turn)except ValueError as exc:- failed = ValueError(f"--steps 1: the cut of {first['length']} frames from {first['start']} is one step, and the clip "+ failed = ValueError(f"{asked}: 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": record} # type: ignore[attr-defined]raise failed from exc@@ -1729,12 +1731,13 @@ def _counted(cycle: dict[str, Any], steps: int, *, window: CutWindow, D: np.ndardef _motion_auto(frames: list[Image.Image], files: list[Path], D: np.ndarray, trajectory: np.ndarray, analysis: dict[str, Any],- *, fps: float, window: CutWindow, prof: LoopProfile, steps: int | None, seam_max: float,+ *, fps: float, window: CutWindow, prof: LoopProfile, state: str, steps: int | None, seam_max: float,seam_pop_max: float | None, scratch: _Scratch, said: dict[str, Any],turn: body_turn_mod.Turn | None = None) -> tuple[dict[str, Any], list[Path], dict[str, Any]]:"""`--anchor motion-auto`'s cut of `frames` — the clip after its lead-in, held, `files` written of them and `D`,`trajectory` and `analysis` read on them (auto_motion.analyse): the search, the gait fallback after a first search- that finds nothing, then the count, given (`steps`, `_counted`) or the clip's crossings (`_by_steps`). Returns the+ that finds nothing, then the count, given (`steps`, `_counted`) or the clip's crossings (`_by_steps`) and, for a cut+ one step long that neither counted, the clip two lengths on (`_two_lengths`). Returns thecut, and the files and the analysis it was read on (the gait fallback's, where it scaled the frames back); `said`takes what the report adds (`automatic_motion_analysis` read again, `gait_fallback`), whether a cut is found or thesearch raises. With `turn` (body_turn.Turn), no cut that holds a frame of a body turn is taken."""@@ -1794,6 +1797,9 @@ def _motion_auto(frames: list[Image.Image], files: list[Path], D: np.ndarray, trelse:cycle = _by_steps(cycle, refused, frames=frames, analysis=analysis, D=D, trajectory=trajectory,window=window, searched=searched, detect=detect, seam_max=seam_max, cells=cells, turn=turn)+ # A cut one step long that nothing counted: the clip itself is asked for two (`_two_lengths`).+ cycle = _two_lengths(cycle, prof=prof, fps=fps, state=state, window=window, D=D, trajectory=trajectory, frames=frames,+ files=files, moved=moved, detect=detect, cells=cells, seam_max=seam_max, turn=turn)return cycle, files, analysis@@ -1836,14 +1842,28 @@ def coverage_verdict(cycle: dict[str, Any]) -> list[str]:# the duration under which a period is one step; the half-period guard reads it in whole frames, rounded, to choose among# the search's candidates (`detect_cycle`, `local_cycle.detect`), so a cut up to half a frame under it is taken. Such a# cut whose steps nothing counted (no `cycle.steps`: neither the clip's crossings, --steps nor the held side's two-# lengths) is named — `cycle.half_step` and a warning line — and kept: pixels cannot count steps where the legs are-# drawn alike, and a cut two of its lengths long is the count's to take (`--steps 1`).+# lengths) is one step. Under `--anchor motion-auto` the clip is asked for two (`_two_lengths`); a cut it does not+# give two to is named — `cycle.half_step` and a warning line — and kept.HALF_STEP_RULE = "a walk or run loops on an even number of steps — two, one cycle"+# The clip's word on a cut one step long (`_two_lengths`). One step on, the legs are back in place with near and far+# swapped, and where the two are drawn alike (one colour of trousers) the silhouette repeats; the body's turn, the+# shading across the torso and the folds of the clothes come back only two steps on. So the cut two lengths long —+# `--steps 1`'s own (`_counted`), at each length it reads — is read about its wrap, TWO_LENGTHS_AROUND frames either+# side of its first (two, so a clip drawn on twos shows two drawings there), on the frames as filmed+# (`distance_matrix`): the clip two lengths on over one length on, the same frames (`two_lengths_on`). The nearest at+# most period.STEP_RATIO_MAX — the step screen's bound for the same ratio, which it reads over the whole clip, where a+# run that changes its pace does not repeat — is taken where the seam gate and the seam pop gate pass it as they will+# the loop (`CutOnCells`). Not on the search's distances: the analysis canvas moves every frame by the drift it reads+# (`auto_motion.analyse`), and a drift read where the body runs in place (one slope over the clip, tilted by frames+# that open higher) moves frames two steps apart further than frames one step apart, so two lengths on reads no nearer+# there. A drift the clip does walk only moves two lengths on further: it keeps a cut one step, never doubles one.+TWO_LENGTHS_AROUND = 2def half_step(cycle: dict[str, Any], prof: LoopProfile, fps: float, *, state: str, clip_frames: int) -> dict[str, Any] | None:"""The record of a periodic walk or run cut shorter than its state's gait floor whose steps were not counted- (HALF_STEP_RULE); None for any other cut. `clip_frames` is what the clip holds after its lead-in."""+ (HALF_STEP_RULE); None for any other cut. `clip_frames` is what the clip holds after its lead-in. Where the clip+ was asked for two steps and did not give them (`cycle.two_lengths`, `_two_lengths`), `two_lengths` says why."""if not prof.gait or prof.min_seconds <= 0 or cycle.get("kind") != "periodic" or "steps" in cycle:return Noneseconds = cycle["length"] / fps@@ -1857,9 +1877,12 @@ def half_step(cycle: dict[str, Any], prof: LoopProfile, fps: float, *, state: stelse:why = (counted.get("cut") or {}).get("why") or "no count of two"two = 2 * cycle["length"]- return {"rule": HALF_STEP_RULE, "state": state, "seconds": round(seconds, 4),+ said = {"rule": HALF_STEP_RULE, "state": state, "seconds": round(seconds, 4),"gait_floor": {"seconds": prof.min_seconds, "frames": round(prof.min_seconds * fps)},"steps": "not counted", "why": why, "two_steps": {"frames": two, "in_clip": two <= clip_frames}}+ if "two_lengths" in cycle:+ said["two_lengths"] = cycle["two_lengths"]["why"]+ return saiddef half_step_verdict(cycle: dict[str, Any]) -> list[str]:@@ -1867,12 +1890,98 @@ def half_step_verdict(cycle: dict[str, Any]) -> list[str]:said = cycle.get("half_step")if not said:return []+ asked = f", and the clip gives it no two ({said['two_lengths']})" if "two_lengths" in said else ""return [f"the cut {cycle['start']}/{cycle['length']} plays {said['seconds']:.2f} s, under the {said['state']}'s gait floor of "f"{said['gait_floor']['seconds']:g} s, and its steps were not counted ({said['why']}): {HALF_STEP_RULE}, and a cut "- "this short is one, the same leg leading every time round (a half step) — count the steps in the loop "+ f"this short is one, the same leg leading every time round (a half step){asked} — count the steps in the loop "f"(video-loop --steps 1 cuts it two lengths long, {said['two_steps']['frames']} frames)"]+def two_lengths_on(D: np.ndarray, start: int, length: int, step: int) -> dict[str, Any] | None:+ """About a cut's first frame (TWO_LENGTHS_AROUND frames either side of its wrap, from `start`): the mean distance to+ the frame `length` on (`near`) and to the frame `step` on (`one`), over the same frames, and `ratio` near over one —+ None where one `step` on is the same picture, which two lengths on can come back no nearer than. None where no such+ frame has the one `length` on in the clip."""+ js = np.arange(max(0, start - TWO_LENGTHS_AROUND), start + TWO_LENGTHS_AROUND)+ js = js[js + length < len(D)]+ if js.size == 0:+ return None+ near, one = float(D[js, js + length].mean()), float(D[js, js + step].mean())+ return {"context_pair_range": [int(js[0]), int(js[-1]) + 1], "near": round(near, 6), "one": round(one, 6),+ "ratio": round(near / one, 4) if one > 0 else None}+++def _two_lengths(cycle: dict[str, Any], *, prof: LoopProfile, fps: float, state: str, window: CutWindow, D: np.ndarray,+ trajectory: np.ndarray, frames: list[Image.Image], files: list[Path], moved: list[np.ndarray],+ detect: dict[str, Any], cells: CutOnCells, seam_max: float,+ turn: body_turn_mod.Turn | None = None) -> dict[str, Any]:+ """A motion-auto cut one step long (`half_step`: under the gait floor, its steps not counted), cut two lengths long+ where the clip says it holds two (TWO_LENGTHS_AROUND): that cut, `steps` by "two-lengths" and `two_lengths` (taken).+ Else the cut as it was, `two_lengths` (not taken, `why`), which `half_step` names. Any other cut, as it was.++ Each length of the window two lengths long ([2L-1, 2L+1] inside the caller's bounds, as --steps 1 reads it) is cut+ by --steps 1's own search at that length (`_counted`) and read (`two_lengths_on`, `tried`); nearest first, the+ first within period.STEP_RATIO_MAX that the seam gate and the seam pop gate pass is taken."""+ if half_step(cycle, prof, fps, state=state, clip_frames=len(frames)) is None:+ return cycle+ first = {"start": cycle["start"], "length": cycle["length"]}+ record: dict[str, Any] = {"read": "the frames as filmed, about the wrap", "first_cut": first,+ "ratio_max": period_mod.STEP_RATIO_MAX, "seam_max": seam_max, "tried": []}++ def kept(why: str) -> dict[str, Any]:+ cycle["two_lengths"] = {**record, "taken": False, "why": why}+ return cycle++ lo, hi = window.within(2 * first["length"] - 1, 2 * first["length"] + 1)+ if lo > hi:+ return kept(f"{window.said()} leaves no length of {2 * first['length'] - 1}-{2 * first['length'] + 1} frames to cut")+ filmed = distance_matrix(files)+ cuts: list[tuple[dict[str, Any], dict[str, Any]]] = []+ for length in range(lo, hi + 1):+ try:+ found = _counted(cycle, 1, window=window, D=D, trajectory=trajectory, frames=frames, moved=moved, detect=detect,+ cells=cells, turn=turn, by="two-lengths", length=length)+ except ValueError as exc:+ record["tried"].append({"length": length, "unread": str(exc)})+ continue+ row = {"start": found["start"], "length": found["length"]}+ read = two_lengths_on(filmed, found["start"], found["length"], first["length"])+ row.update(read if read is not None else {"unread": "the clip holds no frame two lengths on about its wrap"})+ if read is not None and read["ratio"] is None:+ row["unread"] = "one length on is the same picture, which two lengths on comes back no nearer than"+ record["tried"].append(row)+ if "unread" not in row:+ cuts.append((row, found))+ if not cuts:+ return kept(f"no cut {lo}-{hi} frames long is read two lengths on ({record['tried'][-1]['unread']})")+ cuts.sort(key=lambda pair: (pair[0]["ratio"], pair[0]["start"], pair[0]["length"]))+ for row, found in cuts:+ if row["ratio"] > period_mod.STEP_RATIO_MAX:+ break+ s, L = row["start"], row["length"]+ row["seam"] = round(cells.seam(s, L), 3)+ if row["seam"] > seam_max:+ row["gate"] = (f"its wrap on the cells is {row['seam']:g} of its step, over {seam_max:g}: the seam gate would "+ "not pass it")+ continue+ if cells.gate is not None:+ row["seam_pop"] = pop = cells.gate(s, L)+ if pop.get("over"):+ row["gate"] = (f"its top band jumps {pop['pop']:g} into its first frame, over {pop['max']:g}: the seam pop "+ "gate would not pass it")+ continue+ found["two_lengths"] = {**record, "cut": {"start": s, "length": L}, "taken": True}+ if "step_count" in cycle:+ found["step_count"] = cycle["step_count"]+ return found+ row = cuts[0][0]+ if "gate" in row:+ return kept(f"the cut {row['start']}/{row['length']} comes back two lengths on ({row['ratio']:.2f}x as far as one "+ f"length on), but {row['gate']}")+ return kept(f"about the wrap of the nearest, {row['start']}/{row['length']}, the clip two lengths on is {row['ratio']:.2f}x "+ f"as far as one length on, over {period_mod.STEP_RATIO_MAX:g}: the step comes back no nearer two steps on")++def _blend_wrap(frames: list[Image.Image], pin_file: Path, *, mode: str, anchor: str, cycle: dict[str, Any], fps: float,seam_max: float) -> tuple[list[Image.Image], dict[str, Any]]:"""`wrap_blend.apply` on a pinned cut, the pinned last frame cleaned as the cut's frames are (`_scrub`,@@ -2144,7 +2253,7 @@ def _cut_loop(report_base["lead_in"]["search_from"] = skipreport_base["automatic_motion_analysis"] = analysissearch = partial(_motion_auto, source_frames, files, D, trajectory, analysis, fps=fps, window=window, prof=prof,- steps=steps, seam_max=seam_max, seam_pop_max=seam_pop_max, scratch=scratch)+ state=state, steps=steps, seam_max=seam_max, seam_pop_max=seam_pop_max, scratch=scratch)# The body's turn (sprite_gen/video/body_turn.py), read on the clip as keyed against its first frame, the still,# lead-in or not: a cut that holds a frame of one is not taken while another holds a cycle. Where none does,# --body-turn warn takes the cut the search takes with the turn in, and says so; refuse refuses the clip in a line@@ -2918,6 +3027,8 @@ def run(**kwargs: object) -> int:summary["cycle"]["coverage"] = payload["cycle"]["coverage"]if "step_screen" in payload["cycle"]:summary["cycle"]["step_screen"] = payload["cycle"]["step_screen"]+ if "two_lengths" in payload["cycle"]:+ summary["cycle"]["two_lengths"] = payload["cycle"]["two_lengths"]if "half_step" in payload["cycle"]:summary["cycle"]["half_step"] = payload["cycle"]["half_step"]if "step_count" in payload["cycle"]:diff --git a/tests/video/test_loop_half_step.py b/tests/video/test_loop_half_step.pyindex 538b06a..744155b 100644--- a/tests/video/test_loop_half_step.py+++ b/tests/video/test_loop_half_step.py@@ -1,9 +1,11 @@# SPDX-License-Identifier: Apache-2.0-"""A walk or run cut shorter than its state's gait floor, its steps not counted, is named a half step.+"""A walk or run cut shorter than its state's gait floor, its steps not counted, is named a half step where the clip+gives it no two.A walk or run loops on two steps. The half-period guard reads the gait floor in whole frames, rounded, so a run cut 8-frames long at 24 fps (0.33 s, under the run's 0.35 s) is taken as a cycle; the cut stays as it was, and the report and-a warning line say it is one step (`cycle.half_step`, docs/video-pipeline.md section 4)."""+frames long at 24 fps (0.33 s, under the run's 0.35 s) is taken as a cycle. This walker repeats exactly every 8 frames,+so two lengths on comes back no nearer (tests/video/test_loop_two_lengths.py has one that does): the cut stays as it+was, and the report and a warning line say it is one step (`cycle.half_step`, docs/video-pipeline.md section 4)."""from __future__ import annotationsimport pytestdiff --git a/tests/video/test_loop_two_lengths.py b/tests/video/test_loop_two_lengths.pynew file mode 100644index 0000000..e51906f--- /dev/null+++ b/tests/video/test_loop_two_lengths.py@@ -0,0 +1,92 @@+# SPDX-License-Identifier: Apache-2.0+"""A walk or run cut one step long that nothing counted is cut two lengths long where the clip, as filmed, comes back+nearer two lengths on than one.++The walker's legs swing every 8 frames (0.33 s, under the run's gait floor), the same silhouette each time, while a+shirt down its torso lightens and darkens every 16: the steps' shading differs, the silhouette does not. Its first+frames stand a few pixels higher, which tilts the one vertical slope the motion anchor's analysis fits over the clip,+so on the search's distances 16 frames on reads no nearer than 8 and the search cuts one step. On the frames as filmed+16 frames on is the same picture (`loop._two_lengths`, docs/video-pipeline.md section 4)."""+from __future__ import annotations++import math++import numpy as np+import pytest+from PIL import Image, ImageDraw++from sprite_gen.video import loop+from tests.video import test_gait_fallback as walks+from tests.video.test_loop_half_step import REFUSALS+++def shaded(k, *, shirt=20, opening=4):+ """walks.walker on 8 frames a cycle, with a shirt whose grey swings by `shirt` every 16 frames, its first 12 frames+ `opening` px higher."""+ image = walks.walker(k, period=8)+ if shirt:+ x, y = walks.FOOT[0]-15, walks.FOOT[1]-120+ grey = round(140+shirt*math.cos(2*math.pi*k/16))+ ImageDraw.Draw(image).rectangle((x+17, y+40, x+27, y+74), fill=(grey, grey, grey, 255))+ if opening and k < 12:+ raised = Image.new('RGBA', image.size)+ raised.paste(image, (0, -opening))+ image = raised+ return image+++def test_two_lengths_on_reads_the_same_frames_two_lengths_and_one_length_on():+ n = 40+ D = np.ones((n, n), dtype=np.float32)+ for j in range(n-16):+ D[j, j+16] = D[j+16, j] = 0.25+ read = loop.two_lengths_on(D, 10, 16, 8)+ assert read == {'context_pair_range': [8, 12], 'near': 0.25, 'one': 1.0, 'ratio': 0.25}+ # Near the clip's end only the frames with one two lengths on are read; past it, none is.+ assert loop.two_lengths_on(D, 25, 16, 8)['context_pair_range'] == [23, 24]+ assert loop.two_lengths_on(D, 30, 16, 8) is None+ # One length on the same picture: two lengths on can come back no nearer, and no ratio is read.+ for j in range(n-8):+ D[j, j+8] = 0+ assert loop.two_lengths_on(D, 10, 16, 8)['ratio'] is None+++def test_a_half_step_the_clip_gives_no_two_says_why():+ cycle = {'kind': 'periodic', 'start': 2, 'length': 8, 'step_count': {'readable': False, 'why': 'no feet'},+ 'two_lengths': {'taken': False, 'why': 'about the wrap of the nearest, 4/16, the clip two lengths on is 1.02x '+ 'as far as one length on, over 0.85: the step comes back no nearer two steps on'}}+ said = loop.half_step(cycle, loop.profile_for('run'), 24.0, state='run', clip_frames=73)+ assert said['two_lengths'] == cycle['two_lengths']['why']+ line, = loop.half_step_verdict({**cycle, 'half_step': said})+ assert '(a half step), and the clip gives it no two (about the wrap of the nearest, 4/16' in line+ assert not any(words in line for words in REFUSALS)+++def test_a_run_cut_one_step_long_whose_shading_comes_back_two_lengths_on_is_cut_two_lengths_long(tmp_path, capsys):+ code, report, _ = walks.run(tmp_path, [shaded(k) for k in range(73)], '--size-hold', 'off', state='run')+ assert code == 0 and report['status'] == 'passed'+ cycle = report['cycle']+ doubled = cycle['two_lengths']+ # The search cut one step; the clip as filmed comes back two lengths on, at 16 frames and no other.+ assert doubled['taken'] and doubled['first_cut']['length'] == 8+ assert cycle['length'] == 16 and doubled['cut'] == {'start': cycle['start'], 'length': 16}+ assert cycle['steps']['by'] == 'two-lengths' and cycle['steps']['count'] == 2 and 'given' not in cycle['steps']+ ratios = {row['length']: row['ratio'] for row in doubled['tried']}+ assert set(ratios) == {15, 16, 17} and ratios[16] <= loop.period_mod.STEP_RATIO_MAX < min(ratios[15], ratios[17])+ assert 'half_step' not in cycle+ assert '(a half step)' not in capsys.readouterr().err+++def test_a_run_cut_one_step_long_alike_two_lengths_on_stays_one_step_and_is_named(tmp_path, capsys):+ code, report, _ = walks.run(tmp_path, [shaded(k, shirt=0) for k in range(73)], '--size-hold', 'off', state='run')+ assert code == 0 and report['status'] == 'passed'+ cycle = report['cycle']+ assert cycle['length'] == 8 and 'steps' not in cycle+ assert not cycle['two_lengths']['taken'] and 'no nearer' in cycle['two_lengths']['why']+ assert cycle['half_step']['two_lengths'] == cycle['two_lengths']['why']+ err = capsys.readouterr().err+ warned = [line for line in err.splitlines() if '(a half step)' in line]+ assert len(warned) == 1 and 'the clip gives it no two' in warned[0]+ assert not any(words in err for words in REFUSALS)