Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
fix(video-loop): the pixel search's cut stands where the crossings miss a pass or no cut of two steps closes in its place
Soohong Kimc781872a5957
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1befd44..ec48af6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,9 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the## Unreleased+- **Fix: `video-loop --anchor motion-auto` keeps the pixel search's cut where the clip's crossings miss a pass, and where no cut of two steps closes in its place.** Seen from behind on a diagonal, the far foot passes hidden behind the near one, so the feet are seen apart once a cycle and together through the other step, its pass among them; in a clip on twos or threes a pass can also fall between two drawings. The count then sees one crossing a cycle, calls the clip's own cycle one step, and cut two cycles with `steps: 2` — which the set alignment read as settling its two-cycle screen, so the loop walked twice as fast as the rest of the set. A cut the count calls an odd number of steps has the legs swapped a cut on; where the clip a cut on is the same picture instead — frame by frame along the cut, its frame a cut on at most 1.0 of the cut's playback steps off (`local_cycle.same_picture`, `SAME_PICTURE_MAX`) — no legs were swapped, the count missed a crossing, and the search's cut stands, its count `uncertain` (`same-picture`, `step_count.search.same_picture`), no `steps` written. And a search's cut the count does not refute — a two out of phase, or uncertain — now gives way only to a two-step cut that passed the gates (in phase, its top calm, its wrap within the seam gate of its step, its seam under the flow limit) and whose seam the gate passes; where none does, the search's cut is kept (`step_count.declined`, a warning line), where before a cut whose seam the gate refuses replaced a loop it passed. A search's cut the count refutes — one step or three, each seen — still gives way to the two-step cut, closing or not. On the synthetic walkers the far foot hiding behind the near reads 0.03 to 0.48 playback steps a cut on, and the half step the count was made for 2.12; a clip the search finds no cycle in and whose crossings miss a pass a cycle is still cut two cycles long ([loop-repair](docs/loop-repair.md) section 3, "The step count").+- **Tests** — `tests/video/test_walk_steps.py` (a walker seen from behind on a diagonal, on twos and on threes, whose far foot passes hidden: the clip's one cycle, not two, no `steps`; a walker on threes whose big tail closes on no cut of two steps: the search's cut, which passes, where the two-step cut failed the seam gate; the half-step walker reads over the same-picture bound; on `by_steps` itself, a search's cut two steps out of phase stands where every two-step cut's seam fails the gate and gives way where one passes, a cut refuted one step gives way to a two-step cut whose seam fails, and a one-step cut that is the same picture a cut on is kept).+- **New: `video-loop --anchor motion-auto` closes a two-step cut's wrap that a part on its own beat leaves open, with the clip's frames a cycle apart.** A walk cut two steps long by the clip's crossings closes for the legs; a tail swinging round on a beat of its own closes on no cut of two steps, so the seam gate refused every one — and the eased retime does not reach it, since the part turns back at the wrap, where its frames read off the flow against the way. The clip goes on past the cut, and its frame a cycle after one of the cut's shows the legs at the same point of the walk. Under `--repair auto` (and `on`), where such a cut's wrap reads over `--seam-max` on its frames as corrected (`loop.wrap_on_cells`), the frames beside the wrap are made again before the jump repair (`repair.overlap_wrap`): each by RIFE between its two frames of one time — the clip's frame a cycle apart, moved by the analysis translation between the two and corrected as the cut frame was (`loop.cycle_apart`), and the cut's own — so the wrap plays a step the clip filmed and the part goes over to the cut's way over those frames, each frame at its own time. The weights (`repair.overlap_weights`) are the ease in and out x²(3 − 2x), held off it only in the steps where the rest of the body or a body measure, read on the line between the two frames, would go past its bound; a weight of 0 or 1 shows a frame whole, with no call, and a frame at one weight is made once, whatever the run. Four frames, then six, eight, ten and twelve (`OVERLAP_WIDTHS`), on the side — after the wrap or before it — whose frames a cycle apart differ least, never past half the loop; a run is taken only where no made frame has an interpolation fault — a part torn among them, below — the gate passes it, the loop played round still covers two steps (`loop.ring_steps`), no body measure — the foot line, the torso, the ground — moves a pixel past the largest step of the stretch as the loop plays it (the eased retime's bound on the same torso, never the clip's frames a cycle apart: the part going over pulls the body's mass, which is reported, while a torso the clip's frame a cycle on shows elsewhere would slide) — the part steps no further than over the stretch, no new rush is read, no window of the rest of the body steps further than its own largest step over the stretch, and no frame is left further off the flow over its limit (`rejected_for`). The jump repair after it makes nothing from, beside or again over those frames (`jump_repair.overlapped`). A frame made between two frames a cycle apart bridges the part's whole move at once, and where the part swings over a smaller one — a tail across a hand — RIFE drags the small part apart with it, which on art painted without a line no other reading sees: each frame is also read with RIFE's sixteen single passes (`rife.Rife.read`: the binary's eight flips and transposes, both ways in time, run one at a time with no augmentation and turned back, `rife.passes`) and refused as `torn` where the forward passes' mean and the backward passes' mean put the colour and coverage more than 0.05 apart over more than 0.21 of a window a tenth of the body high (`rife.torn`, `interpolation_quality.TORN_WARN`); the frame delivered is still the binary's own. The frames are made the weight nearest a half first, and the first frame with a fault ends its run, the rest of it not made (`unmade`), so a clip whose part crosses another on every run is refused the overlapped wrap and kept as filmed for the gate to refuse. The report carries `wrap_overlap` (each try with the weights chosen, the frames made in play order and in the order made, and the run taken; the binary's calls), the summary names it, a warning line names the frame that ended each refused run, and without RIFE the wrap is cut as filmed with a warning line (`--repair on` refuses). Each frame made costs the binary 34 calls (its frame, and its sixteen passes in colour and coverage); at most forty frames, where every width is made whole and refused. On the test walker (front, 26 frames a cycle, the tail on a 41-frame beat) the cut 29/26 reads 6.23 at the gate as filmed and 3.17 after the jump repair alone; four frames after the wrap rush the tail and are refused, six are taken, and the loop passes at 1.04, two steps, in ten calls. On a second walker whose big tuft bobs on the loop and a cycle on is carried 8 px aside a frame, the walker in its place, four frames are taken at the ease (3.41 → 1.53 at the gate, four calls): the torso moves 0.05 px, the body's mass 3.95 px against the stretch's 0.71, reported; where the whole walker also stands 3 px aside a cycle on, its torso sliding, every run is held at 0.85 of the cut's own frame next to the wrap, the wrap stays open and the cut is kept as filmed for the gate to refuse. On a third walker, painted without a line and seen from behind, whose big tail swings from 48 to −8 degrees across its hand between two frames a cycle apart, the real RIFE's frames at weights 0.5 and 0.7 read torn 0.44 and 0.26 with no other fault; swung 10 degrees past no hand, its frames read 0.04 at most ([loop-repair](docs/loop-repair.md#the-overlapped-wrap--a-part-on-its-own-beat-that-no-cut-of-two-steps-closes)).- **Tests** — `tests/video/test_loop_overlap.py` (a front walker whose tail swings round on its own beat, refused at the seam on every cut of two steps, is closed at the wrap: each frame beside it made between the clip's frame a cycle apart and the cut's own at its eased weight, once a frame and weight, four frames refused for a rush and six taken, two steps on the loop played round, the body within its drift, the rest of it no faster, every other frame the clip's own and nothing made by the jump repair; on a walker whose big tuft a cycle on is carried aside, every run's drift bound is the stretch's own as the loop plays it — the torso's, which stands still there, never the clip's frames a cycle apart — and the body's mass is reported beside it; with the tuft alone carried over the run is taken near the ease, the torso within its pixel while the mass moves 2 px and more past its own; with the whole walker also standing aside a cycle on, its torso sliding, no run moves it more than a pixel in a step on the frames shown, drawn again, the frame next to the wrap is held off the ease and the cut is kept as filmed; `--repair off` refused as before; without RIFE cut as filmed with a warning, and with `--repair on` refused asking for it; a made frame with a fault ends its run there — the frame nearest a half made first, the rest not made — every width refused and the cut kept as filmed; a stand-in whose passes disagree over a patch of the body ends every run at its first frame as torn, the warning naming it; the real RIFE (marked `real_rife`) drags the painted walker's hand apart between its frames a cycle apart and the frames are refused as torn, no other reading refusing them, while a swing past no hand reads nothing; a weighting search on lines drawn by hand: the ease where nothing binds, held off it in the one step a window of the rest of the body is bounded in, none where a body measure may not move); `tests/video/test_rife.py` (`Rife.read` makes the frame as every call does and then sixteen single passes with no augmentation, the pair flipped and transposed and run both ways in time: with a binary that hands back its first frame, turned back, they disagree by exactly how far the pair differs and only there; `rife.torn` reads a patch a window wide where the passes disagree and not lines a pixel or two wide, scattered pixels, a faint patch or a frame with no body).- **Behavior change: `video-loop --anchor motion-auto` cuts a walk two steps long — the left foot forward once and the right once — wherever the clip shows its feet pass.** Left foot forward and right foot forward are nearly the same silhouette from the side or a diagonal, so the pixel search could take one step for a cycle (a half step loop: one foot goes forward), three steps where a tail on its own beat repeated there (the wrap puts the nearer foot back: a stomp in place), or refuse a slow walk whose cycle its window could not hold. The feet are now read (`crossings.read`): where they are seen apart, each run of frames with them together is a crossing; where they never are (front, back), the foot band's lean about the body's axis changing side is, and the lean must turn over a step on. Every crossing counted is one the clip shows whole: a run cut by the clip's first or last frame counts only where its twin confirms it, every step a cut plays — on both sides of its wrap — lies within √2 of the clip's own step, and a cut is two steps only when the walk's phase advances by two over it, its wrap joins two points of a step within [1/√2 − 1, √2 − 1] of each other under every bound of what the clip does not show, and the loop as played shows two crossings too (`two`; `refuted` one or three steps; anything else `uncertain`, never two). The search's cut is kept, every image as before, where it is a two within 1.5 frames of phase; otherwise the cut is the two-step cut in phase whose top band does not pop at the wrap, whose wrap is within the seam gate of its step and whose seam is the smoothest by the flow reading (both seam frames under `repair.FLOW_LIMIT`, within 0.5 of the smoothest, the wrap nearest the clip's own way on), read on the frames moved as the cut will be corrected, of any length the count allows inside an explicit `--min-len`/`--max-len` (`method: observed-two-steps-v1`); of the first four, the first whose seam the gate will pass, read as the gate reads it (`loop.seam_on_cells`), is taken. A window that holds no two steps of a walk whose steps are seen is refused, naming both (`no cut of two steps in --max-len 25: …`), never cut one step long. A clip whose feet are not read is cut exactly as before. The report records `cycle.step_count` (the crossings, the step range, the verdict of the cut taken and of the search's cut, `chosen_by`); a cut on two steps records `cycle.steps` `{count: 2, by: crossings}` and `strip.json` `steps: 2`, so `video-cycle-align` reads its half-way return as its step, and the step screen's pixel suspicion is settled (`pixel_suspect`). Where the clip shows its steps but no cut of two, the search runs again refusing the cuts the crossings refute, and a refusal lists each window's count, those refuted last. `--steps` is still the word on the search's cut. `repair.clip_flow_states` and `repair.ring_scores` read the flow of every cut of a clip on one path; `flow_scores` and the repair read as before ([loop-repair](docs/loop-repair.md) section 3, "The step count").diff --git a/docs/loop-repair.md b/docs/loop-repair.mdindex dc32a53..796cc43 100644--- a/docs/loop-repair.md+++ b/docs/loop-repair.md@@ -890,8 +890,9 @@ crossings, joined at the wrap where the walk itself goes on, is one cycle (`cros| `unconfirmed` | frames no reading confirms: a run of feet together cut by the clip's first or last frame that its twin does not confirm, the frames before the first side is seen, a change the clip ends on || `step_range` | the clip's own step (the median between crossings) and the range a step must lie in, a factor of √2 either way || `readable`, `why`, `alternation` | whether the clip shows its steps: three crossings or more, and in sign mode a lean that turns over a step on (correlation one step on at most **−0.7**, `crossings.ALTERNATION_MAX`) |-| `cut`, `search` | the cut taken and the pixel search's own cut (or why it found none), each with its `verdict`, `code`, `k` (steps covered), `phase` and `ring` |+| `cut`, `search` | the cut taken and the pixel search's own cut (or why it found none), each with its `verdict`, `code`, `k` (steps covered), `phase` and `ring`; the search's cut counted an odd number of steps also with `same_picture` (the clip a cut on, in its playback steps) || `chosen_by` | `search` (kept), `two steps` (chosen on the count), and the search again where the count refutes its cut (`searched_again`) |+| `declined` | the best two-step cut, where none closed and the search's cut stood: its `cut`, `phase`, whether it passed the gates (`gated`) and its `seam` |**Counting a cut.** Every crossing counted is one the clip shows whole. A cut s/L plays frames s tos+L−1 and then frame s again where the clip itself plays frame s+L; the wrap joins two frames the clip@@ -912,6 +913,18 @@ far the wrap is from joining the same point of the walk, in frames, the worst ovthree crossings): the search's cut, exactly as before. Only `cycle.step_count` is new.- The search's cut is a two within **1.5** frames of phase (`crossings.PHASE_TOLERANCE`): kept, everyimage and frame as the search alone cuts it.+- The count says the search's cut is an odd number of steps — one or three, the legs swapped a cut on —+ but the clip a cut on is the same picture: frame by frame along the cut, its frame a cut on lies at most+ **1.0** of the cut's playback steps off (`local_cycle.same_picture`, `SAME_PICTURE_MAX`;+ `step_count.search.same_picture`). A step on, the legs are swapped, and a swap that draws nearer than+ the next frame is none: the count missed a crossing, and proves nothing. Seen from behind on a+ diagonal, the far foot passes hidden behind the near one, so the feet are seen apart once a cycle and+ together through the other step, its pass among them; in a clip on twos or threes a pass can fall+ between two drawings. The search's cut is kept, every image as the search alone cuts it, its count+ `uncertain` (`same-picture`), and no `steps` is written: the set alignment screens it as any loop. On+ the synthetic walkers of `tests/video/test_walk_steps.py` the frame a cut on lies 0.03 to 0.48+ playback steps off where the far foot hides (on twos and threes), and 2.12 on the half step the count+ was made for, legs drawn alike and a tail on its own beat.- Otherwise the cut is among the cuts that cover two steps — any start, any length the count allows,inside an explicit `--min-len`/`--max-len` but not the state's window, half the clip or the gaitfallback's ceiling (a walk slower than the window is cut two steps long). Those in phase, if any, are@@ -936,6 +949,15 @@ far the wrap is from joining the same point of the walk, in frames, the worst ovThe pixel search's repeat rule is not asked: a part off the legs' beat — a tail on its own beat —repeats on its own, and its seam is the flow repair's (section 2). `step_count.repeat` records thesearch's word on the cut, and a cut it would refuse, or one that passed no gate, is a warning line.+- A search's cut the count does not refute — a two out of phase, or uncertain — gives way only to a+ two-step cut that closes: one of the cuts that passed the gates above (in phase, its top calm, its wrap+ within the seam gate of its step, its seam under the flow limit) whose seam the gate passes. Where none+ does, the search's cut is kept, every image as the search alone cuts it (`steps` written where it is a+ two), and `step_count.declined` names the best two-step cut, its phase, whether it passed the gates and its+ seam, with a warning line. A cut that plays a step a clip shows unevenly, or a part on its own beat that closes on+ no two steps, would otherwise trade a loop that passes for one the seam gate refuses. Only a search's+ cut the count refutes — one step or three, each seen — is given up for a two-step cut that does not+ close, and the seam gate says whether the loop passes.- The clip shows its steps but no cut of two: the search's cut, unless the count refutes it — then thesearch runs again refusing what the crossings refute, and a search that finds nothing lists eachrefused window's count (`cycle.candidates[].step_count`), those the crossings refute last.@@ -949,7 +971,10 @@ crossings are not asked.**What crossings cannot see**: a hold the step range absorbs (a 13-frame step held to 17), a still run ofthe feet together inside the clip as long as a pass, and a wobble that reaches the reading's sides at astep's beat read as steps; a narrow step that opens the feet only just past the reading's threshold-reads at that threshold. Four-legged gaits are read as one foot band (`legs.strike_signals`), as before.+reads at that threshold. A pass hidden behind the other foot, or between two drawings, leaves one+crossing a cycle, and the count reads a cycle as one step: the clip's own repeat overrules it where the+pixel search found it (the same picture a cut on, above); where the search found no cycle, the cut is two+cycles long and says `steps: 2`. Four-legged gaits are read as one foot band (`legs.strike_signals`), as before.### The step screen — a slow walk cut one step longdiff --git a/docs/loop-review.md b/docs/loop-review.mdindex 17261b0..3a3f455 100644--- a/docs/loop-review.md+++ b/docs/loop-review.md@@ -118,7 +118,9 @@ A walk whose two steps look alike — its legs drawn alike, from the side or a done step long (or, past a tail on its own beat, three), and the search has nothing to refuse it on:the step repeats. Where the clip shows its feet pass, the cut is counted on those crossings and istwo steps long — any length the count allows, past the window for a slow walk — joined at the walk's-own point (`cycle.step_count`; [loop repair](loop-repair.md) section 3, "The step count"). Where it+own point (`cycle.step_count`; [loop repair](loop-repair.md) section 3, "The step count"). The search's+cut stands where the clip a cut on is the same picture though the count says one step (a pass hidden+behind the other foot or between drawings), and where no cut of two steps closes in its place. Where itdoes not, the cut is screened the other way, over the whole clip (`cycle.step_screen`): where twice itrepeats better than it, the report names it a suspect and nothing else changes. Look at the loop andcount its steps (how often each foot lands); `video-loop --steps 1` cuts it again two of its lengthsdiff --git a/docs/video-pipeline.md b/docs/video-pipeline.mdindex d1a351f..dcb77d3 100644--- a/docs/video-pipeline.md+++ b/docs/video-pipeline.md@@ -763,7 +763,9 @@ was 17). `video-loop` therefore:that closes only on two steps is cut two steps long — one cycle (`cycle.steps`, "The heldside"). Where the clip shows its steps, the cut is two of them — read off the crossings of thefeet, joined at the walk's own point, the smoothest seam first — and the search's cut is kept- where it already is that (`cycle.step_count`, "The step count"). Where it does not, the cut taken+ where it already is that, where the clip a cut on is the same picture though the count says one+ step (a pass it did not see), and where no cut of two steps closes in its place+ (`cycle.step_count`, "The step count"). Where it does not, the cut takenis screened for one step of a cycle twice as long, over the whole clip (`cycle.step_screen`, "Thestep screen"); nothing is cut on it, and `--steps` is the count that cuts again.diff --git a/sprite_gen/video/local_cycle.py b/sprite_gen/video/local_cycle.pyindex 542d068..9f35d62 100644--- a/sprite_gen/video/local_cycle.py+++ b/sprite_gen/video/local_cycle.py@@ -25,6 +25,10 @@ REFUSED_SHOWN = 12 # refused windows a failed search reports, as many as a founSEAM_FLOW_BAND = 0.5REPEAT_OVER_STEP_MAX = 2 # `detect` refuses a repeat further off than two playback steps ('repeat error over two steps')SEAM_TRIES = 4 # two-step cuts, best first, whose seam is read as the seam gate reads it before one is taken (`by_steps`)+# The clip a cut on, frame by frame along the cut, at most this many of the cut's playback steps off: the same picture+# again (`same_picture`). An odd count of steps swaps the legs a cut on, and a step drawn nearer than the next frame+# is no swap: the count missed a crossing.+SAME_PICTURE_MAX = 1.0def _around(start, length):@@ -425,9 +429,22 @@ def _calm(row):return 'pops' in row['top'] and not row['top']['pops']+def same_picture(distances, start, length):+ """How far the clip one cut on lies from the cut, frame by frame along it, in the cut's playback steps: the mean of+ each frame's distance to the frame `length` on, over the cut's mean step. None where under half the cut has a+ frame one cut on in the clip, or the cut does not move."""+ n = len(distances)+ js = np.arange(start, start+length)+ js = js[js+length < n]+ step = float(np.diag(distances[start:start+length, start:start+length], 1).mean())+ if len(js) < length/2 or step <= 1e-10:+ return None+ return float(distances[js, js+length].mean())/step++def _rank(rows, *, flow_limit, seam_max, in_phase):- """Two-step cuts, best first, and whether the first passed the gates: in phase (`in_phase`), its top band calm at- the wrap (`_calm`: a thin part the flow hardly sees, a staff, does not jump), its wrap over its step (`ratio`) at+ """Two-step cuts, best first, and how many of the first passed the gates: in phase (`in_phase`), its top band calm+ at the wrap (`_calm`: a thin part the flow hardly sees, a staff, does not jump), its wrap over its step (`ratio`) atmost `seam_max` (what the seam gate holds a loop to) and both seam frames' flow off under `flow_limit`, the worsewithin SEAM_FLOW_BAND of the smoothest such cut's, then the wrap nearest the clip's own way on (`_closure`); afterthose the rest, in phase first, then calm, then under the flow limit, then under `seam_max`, then by the worse flow."""@@ -438,7 +455,7 @@ def _rank(rows, *, flow_limit, seam_max, in_phase):rest = sorted((row for row in rows if row not in band),key=lambda row: (not in_phase(row), not _calm(row), _worse(row) >= flow_limit, row['ratio'] > seam_max, _worse(row),row['start'], row['length']))- return band + rest, bool(band)+ return band + rest, len(band)def by_steps(distances, trajectory, reading, *, found, refused, min_len, max_len, seam_flow, wrap_pop, seam_gate, flow_limit,@@ -451,6 +468,10 @@ def by_steps(distances, trajectory, reading, *, found, refused, min_len, max_lenunder two steps): the search's cut, as it chose it.- The search's cut covers two steps (`two`) and its wrap joins the walk at its own point (`reading.in_phase`):that cut, as it chose it.+ - The crossings count the search's cut an odd number of steps — the legs swapped a cut on — but the clip a cut+ on is the same picture (`same_picture`, at most SAME_PICTURE_MAX playback steps along the cut): no swap, so the+ count missed a crossing (a foot passing hidden behind the other) and proves nothing. The search's cut, as it+ chose it, its count `uncertain` (`same-picture`).- Else the cuts [min_len, max_len] frames long that cover two steps, any start, however long — the window thatbinds the search binds no count; none, and the search's word stands. Those in phase, if any, else all, areread at the wrap (`seam_flow(start, length)`: the flow off of the cut's last and first frames; `wrap_pop`, the@@ -459,6 +480,9 @@ def by_steps(distances, trajectory, reading, *, found, refused, min_len, max_lenwhere none the first, and the gate says whether it closes (`method: observed-two-steps-v1`). The pixelsearch's own repeat rule is not asked: a part off the legs' beat (a tail) repeats on its own and its seam isthe flow repair's; `repeat` records it.+ - A search's cut the count does not refute (`two` out of phase, `uncertain`) is replaced only by a two-step cut+ that closes: one of the cuts that passed the gates (`_rank`) whose seam the seam gate passes. Where none does,+ the search's cut, as it chose it (`declined`: the best two-step cut and why it does not close).A cut taken on two steps records `steps` (count 2, by crossings): `video-cycle-align` reads a return half wayas its step, and the step screen's pixel suspicion of one step (`step_screen`) is settled, kept as@@ -470,12 +494,22 @@ def by_steps(distances, trajectory, reading, *, found, refused, min_len, max_lenif found is not None:record['cut'] = reading.judge(found['start'], found['length'])return found, record+ searched = Noneif found is not None:- counted = reading.judge(found['start'], found['length'])- record['search'].update({k: counted[k] for k in ('verdict', 'code', 'k', 'phase') if k in counted})- if reading.in_phase(counted):- record.update(chosen_by='search', cut=counted)+ searched = reading.judge(found['start'], found['length'])+ record['search'].update({k: searched[k] for k in ('verdict', 'code', 'k', 'phase') if k in searched})+ if reading.in_phase(searched):+ record.update(chosen_by='search', cut=searched)return _two_steps(found, record), record+ if searched['verdict'] == 'refuted' and searched['k'][0] % 2:+ near = same_picture(distances, found['start'], found['length'])+ record['search']['same_picture'] = {'over_step': None if near is None else round(near, 3), 'max': SAME_PICTURE_MAX}+ if near is not None and near <= SAME_PICTURE_MAX:+ record.update(chosen_by='search', cut={+ **searched, 'verdict': 'uncertain', 'code': 'same-picture',+ 'why': f"the crossings count {searched['why']}, but the clip a cut on is the same picture ({near:.2f} playback "+ f"steps along the cut, at most {SAME_PICTURE_MAX:g}): no legs swapped, a crossing unseen"})+ return found, recordtwos = reading.twos(min_len, max_len)record['two_cuts'] = len(twos)if not twos:@@ -492,7 +526,7 @@ def by_steps(distances, trajectory, reading, *, found, refused, min_len, max_lenrows.append({'start': start, 'length': length, 'phase': counted['phase'], 'counted': counted,'seam_flow': seam_flow(start, length), 'top': wrap_pop(start, length), 'closure': _closure(distances, start, length),'ratio': float(distances[start+length-1, start])/step if step > 1e-10 else math.inf})- ranked, gated = _rank(rows, flow_limit=flow_limit, seam_max=seam_max, in_phase=lambda row: reading.in_phase(row['counted']))+ ranked, band = _rank(rows, flow_limit=flow_limit, seam_max=seam_max, in_phase=lambda row: reading.in_phase(row['counted']))tried = []for row in ranked[:SEAM_TRIES]:tried.append({'start': row['start'], 'length': row['length'], 'seam': round(seam_gate(row['start'], row['length']), 3)})@@ -503,7 +537,13 @@ def by_steps(distances, trajectory, reading, *, found, refused, min_len, max_lenelse (tried[0]['start'], tried[0]['length'])))record['seam_gate'] = {'max': seam_max, 'tried': tried}start, length = picked['start'], picked['length']- record.update(chosen_by='two steps', cut=picked['counted'], gated=gated, flow_limit=flow_limit, seam_max=seam_max)+ if searched is not None and searched['verdict'] != 'refuted' and not (passed and ranked.index(picked) < band):+ # A cut the count does not refute stands until a two-step cut closes in its place.+ record.update(chosen_by='search', cut=searched, flow_limit=flow_limit, seam_max=seam_max, declined={+ 'cut': [start, length], 'phase': picked['phase'], 'gated': ranked.index(picked) < band,+ 'seam': next(t['seam'] for t in tried if (t['start'], t['length']) == (start, length))})+ return (_two_steps(found, record) if searched['verdict'] == 'two' else found), record+ record.update(chosen_by='two steps', cut=picked['counted'], gated=bool(band), flow_limit=flow_limit, seam_max=seam_max)# The pixel search's own word on this cut: its repeat, read as `detect` reads a window it refused.radius, js = _around(start, length)measured = _measure(distances, trajectory, start, length, _profile(distances, js, radius, max(6, min_len), length))@@ -516,7 +556,7 @@ def by_steps(distances, trajectory, reading, *, found, refused, min_len, max_lencycle = {'start': start, 'length': length, 'period_local': length, 'ratio': picked['ratio'],'closure': picked['closure'], 'seam_flow': picked['seam_flow'], 'top': picked['top'], 'kind': 'periodic', 'method': 'observed-two-steps-v1','repeat': 'two steps seen in the clip, joined at the walk\'s own point',- 'period_global': None, 'periodicity_min': periodicity_min, 'review_recommended': not gated,+ 'period_global': None, 'periodicity_min': periodicity_min, 'review_recommended': not band,'candidate_count': len(rows),'candidates': [{'start': row['start'], 'length': row['length'], 'phase': row['phase'], 'seam_flow': row['seam_flow']['off'],'seam_pop': row['top'].get('pop'), 'ratio': round(row['ratio'], 3),@@ -539,7 +579,8 @@ def _two_steps(cycle, record):def step_verdict(cycle):"""The step count's warnings, in words: a cut taken on two steps whose seam the pixel search refuses (a part off- the legs' beat) or that passed no gate, and a clip that shows its steps but no cut of two."""+ the legs' beat) or that passed no gate, a search's cut kept where no two-step cut closes, and a clip that shows+ its steps but no cut of two."""counted = cycle.get('step_count')if not counted or not counted.get('readable'):return []@@ -557,6 +598,13 @@ def step_verdict(cycle):out.append(f"the cut {s}/{L} covers two steps by the clip's crossings, and {counted['repeat']['why']}; the seam's "f"worst window is {cycle['seam_flow']['window'][worst]} of the body's box, turning "f"{cycle['seam_flow']['turn'][worst]:+.2f} there — the flow repair reads it")+ elif 'declined' in counted:+ declined = counted['declined']+ out.append(f"the clip shows cuts of two steps, but none closes — in phase, its top calm, its wrap within "+ f"{counted['seam_max']:g} of its step, its seam under the flow limit {counted['flow_limit']:g} and the seam "+ f"gate passed (the best, {declined['cut'][0]}/{declined['cut'][1]}: phase {declined['phase']:+.1f} frames, "+ f"seam {declined['seam']:g}): the search's cut {s}/{L} stands, {counted['cut']['verdict']} by the count "+ f"({counted['cut']['why']})")elif 'two_cuts' in counted and counted['two_cuts'] == 0:out.append(f"the clip shows its steps (crossings {counted['crossings']}) but no cut of two: the cut {s}/{L} is "f"{counted['cut']['verdict']} ({counted['cut']['why']}) — count its steps")diff --git a/tests/video/test_walk_steps.py b/tests/video/test_walk_steps.pyindex 2e7e5e0..3e9ac6f 100644--- a/tests/video/test_walk_steps.py+++ b/tests/video/test_walk_steps.py@@ -12,6 +12,10 @@ Each walker is drawn so the pixel search alone makes one of the faults a walk lo- a slow front walk in a short clip, refused outright (no periodic cycle found);- a walk that stalls, its cut playing the stalled step.+And two the count alone gets wrong, where the search's cut stands: a held walk seen from behind whose far foot+passes hidden (one crossing a cycle, the cycle counted one step), and a walk on threes whose tail closes on no cut+of two steps.+A walk the search already cuts two steps long, joined at the walk's own point, is cut exactly as before; a bodywhose feet cannot be read is cut as before. Synthetic frames only."""@@ -78,6 +82,51 @@ def _front(k: float, *, cycle: float, phase: float = 0, tail_cycle: float = 1, treturn im+def _behind(k: int, *, cycle: int, hold: int) -> Image.Image:+ """A walker seen from behind on a diagonal, drawn on twos or threes (`hold`): the near leg swings ahead and back,+ and the far one is seen beside it only while it is behind — ahead, it stands hidden behind the near leg. The feet+ are seen apart once a cycle and together through the other step, its pass hidden among them: one crossing shows a+ cycle. Arms opposite, the far one darker; each repeat of a drawing redrawn a little (a pixel aside, a few tones)."""+ redraw = k % hold+ ph = 2 * math.pi * (k - redraw) / cycle+ im = Image.new("RGBA", (300, 220))+ d = ImageDraw.Draw(im)+ x, y = 90 + redraw, 40 + round(3 * math.cos(2 * ph))+ sw = 16 * math.sin(ph)+ near = x + 14 + sw+ far = x + 14 - sw if sw > 0 else near+ d.rectangle((x + 14 - sw - 4, y + 34, x + 14 - sw + 4, y + 72), fill=(150, 150, 150, 255))+ d.rectangle((far - 5, y + 80, far + 5, y + 126), fill=(50, 50, 60, 255))+ d.rectangle((near - 5, y + 80, near + 5, y + 126), fill=(70, 70, 80, 255))+ d.rectangle((x, y + 30, x + 28, y + 84), fill=(200 + 12 * redraw, 80, 80, 255))+ d.rectangle((x + 2, y, x + 26, y + 28), fill=(230, 200, 170, 255))+ d.rectangle((x + 14 + sw - 4, y + 34, x + 14 + sw + 4, y + 72), fill=(225, 225, 225, 255))+ return im+++def _tailed(k: int) -> Image.Image:+ """A side walker on threes, 30 frames a cycle, its legs hurrying through each pass and slowing apart, with a big+ tail swinging on a beat of its own (34 frames); each repeat of a drawing redrawn a few tones."""+ redraw = k % 3+ t = k - redraw+ u = 2 * math.pi * t / 30+ ph = u - 0.25 * math.sin(u)+ im = Image.new("RGBA", (300, 220))+ d = ImageDraw.Draw(im)+ x, y = 90, 40 + round(3 * math.cos(2 * ph))+ sw = 16 * math.sin(ph)+ d.rectangle((x + 14 - sw - 4, y + 34, x + 14 - sw + 4, y + 72), fill=(150, 150, 150, 255))+ for sign in (1, -1):+ lx = x + 14 + 14 * sign * math.sin(ph)+ d.rectangle((lx - 5, y + 80, lx + 5, y + 126), fill=(60, 60, 70, 255))+ a = 0.8 * math.sin(2 * math.pi * t / 34)+ d.line((x, y + 50, x - 70 * math.cos(a), y + 50 - 70 * math.sin(a)), fill=(180, 120, 40, 255), width=12)+ d.rectangle((x, y + 30, x + 28, y + 84), fill=(200 + 3 * redraw, 80, 80, 255))+ d.rectangle((x + 2, y, x + 26, y + 28), fill=(230, 200, 170, 255))+ d.rectangle((x + 14 + sw - 4, y + 34, x + 14 + sw + 4, y + 72), fill=(225, 225, 225, 255))+ return im++def _blob(k: int) -> Image.Image:"""A legless body bouncing every 16 frames: one foot band, nothing to step."""im = Image.new("RGBA", (200, 200))@@ -124,6 +173,8 @@ def test_a_half_step_diagonal_walk_is_cut_two_steps(tmp_path):counted = _two_steps(report, 29)assert counted["mode"] == "gap" and counted["step_range"][1] == 14.5assert counted["search"]["verdict"] == "refuted" and counted["search"]["k"] == [1] and counted["search"]["cut"][1] in (14, 15)+ # The step a cut on is no repeat of the picture: the tail has moved on.+ assert counted["search"]["same_picture"]["over_step"] > local_cycle.SAME_PICTURE_MAXstrip = json.loads((tmp_path / "out" / "loop.strip.json").read_text())assert strip["steps"] == 2 and strip["cycle_frames"] == report["cycle"]["length"]# The step screen's pixel suspicion of a cycle twice as long is settled by the count.@@ -173,6 +224,42 @@ def test_a_walk_that_stalls_is_not_cut_across_the_stalled_step(tmp_path):assert counted["search"]["code"] == "step-long"[email protected]("cycle, hold", [(20, 2), (24, 3)])+def test_a_held_walk_whose_far_foot_hides_is_cut_one_cycle(tmp_path, cycle, hold):+ """Seen from behind on a diagonal, on twos or threes, the far foot passes hidden behind the near one: one crossing+ shows a cycle, and the count takes the cycle for one step. The search's cut is the clip's cycle, the same picture a+ cut on, which the count calls one step; a step on the legs are swapped, and a swap nearer than the next frame is+ none — the count missed a crossing. The search's cut stands, one cycle, and no `steps` is written (the parent+ engine cut it two cycles long, `steps: 2`, the set alignment's two-cycle screen settled by it)."""+ report = _cut(tmp_path / "out", _keyed(tmp_path, lambda k: _behind(k, cycle=cycle, hold=hold)))+ c = report["cycle"]+ counted = c["step_count"]+ assert c["length"] == cycle and "steps" not in c+ assert "steps" not in json.loads((tmp_path / "out" / "loop.strip.json").read_text())+ assert report["drawings"]["hold"] == hold and report["status"] == "passed"+ assert counted["mode"] == "gap" and abs(counted["step_range"][1] - cycle) <= 1+ assert counted["search"]["verdict"] == "refuted" and counted["search"]["k"] == [1]+ assert counted["search"]["same_picture"]["over_step"] <= local_cycle.SAME_PICTURE_MAX+ assert counted["chosen_by"] == "search" and counted["cut"]["verdict"] == "uncertain" and counted["cut"]["code"] == "same-picture"+ assert c["method"] == "local-repeat-drift-v1"+++def test_a_cut_of_two_steps_that_does_not_close_leaves_the_searchs_cut(tmp_path):+ """On threes, a big tail on its own beat: the search's cut is one the count does not refute (it plays feet held+ together past a pass: uncertain), and every cut of two steps leaves the tail open at the wrap, out of phase, its+ seam over the gate. The search's cut stands and the loop passes; the record and a warning line name the two-step+ cut declined (the parent engine took it, and the seam gate failed the loop)."""+ report = _cut(tmp_path / "out", _keyed(tmp_path, _tailed))+ c = report["cycle"]+ counted = c["step_count"]+ assert report["status"] == "passed" and report["drawings"]["hold"] == 3+ assert counted["chosen_by"] == "search" and counted["search"]["verdict"] == "uncertain"+ assert [c["start"], c["length"]] == counted["search"]["cut"] and "steps" not in c+ assert counted["declined"]["gated"] is False and counted["declined"]["seam"] > report["seam_max"]+ assert all(t["seam"] > report["seam_max"] for t in counted["seam_gate"]["tried"])+ assert any("the search's cut" in w and "stands" in w for w in report["jolt"]["warnings"])++def _same_cut(a: Path, b: Path) -> None:for name in ("loop.strip.png", "loop.gif", "loop.webp"):assert (a / name).read_bytes() == (b / name).read_bytes(), name@@ -256,3 +343,51 @@ def test_the_search_refuses_what_the_crossings_refute_and_names_their_count(unceassert shown and all(row["step_count"]["verdict"] == "refuted" for row in shown)assert any("one step, each seen in the clip's crossings" == row["refused"] for row in shown)assert "refute after the rest" in refused.value.diagnostics["order"]+++def _choose(found: dict, *, period: int, seam: float) -> tuple[dict, dict]:+ """`by_steps` on a clip whose picture goes round every `period` frames, its feet passing every 15 (crossings at 8,+ 23 … 68), with the search's cut `found`: every two-step cut's seam reads `seam` at the gate, its top calm and its+ flow off 1.0 either side."""+ D = _distances(period=period, frames=FRAMES)+ reading = crossings.Reading(FRAMES, "gap", [(c, c) for c in (8.0, 23.0, 38.0, 53.0, 68.0)])+ return local_cycle.by_steps(+ D, np.zeros(FRAMES), reading, found=dict(found), refused=None, min_len=12, max_len=FRAMES,+ seam_flow=lambda s, L: {"off": [1.0, 1.0], "turn": [0.0, 0.0], "window": [[0, 0, 1, 1], [0, 0, 1, 1]]},+ wrap_pop=lambda s, L: {"pops": False, "pop": 0.1}, seam_gate=lambda s, L: seam, flow_limit=3.0, seam_max=2.0,+ gait_floor=12, periodicity_min=loop.PERIODICITY_MIN, signals=None)++[email protected]("seam, kept", [(3.0, True), (1.0, False)])+def test_a_cut_the_count_does_not_refute_gives_way_only_to_a_two_step_cut_that_closes(seam, kept):+ """The search's cut 10/33 covers two steps a fifth of a step off (out of phase, not refuted). A two-step cut in+ phase replaces it only where the seam gate passes it; where none passes, the search's cut stands and the record+ names the two-step cut it declined, with a warning line (the parent engine took the two-step cut either way)."""+ picked, record = _choose({"start": 10, "length": 33}, period=30, seam=seam)+ assert record["search"]["verdict"] == "two" and abs(record["search"]["phase"]) > crossings.PHASE_TOLERANCE+ if kept:+ assert (picked["start"], picked["length"]) == (10, 33) and record["chosen_by"] == "search"+ assert record["declined"]["seam"] == seam and record["declined"]["gated"] is True+ assert picked["steps"] == {"count": 2, "by": "crossings"}+ warned = local_cycle.step_verdict({**picked, "step_count": record})+ assert len(warned) == 1 and "the search's cut 10/33 stands" in warned[0]+ else:+ assert record["chosen_by"] == "two steps" and "declined" not in record and picked["length"] != 33+++def test_a_cut_the_count_refutes_gives_way_to_two_steps_closing_or_not():+ """A search's cut the count refutes, one step seen, is a fault of its own: the two-step cut is taken though its seam+ fails the gate, and the gate says whether the loop passes."""+ picked, record = _choose({"start": 10, "length": 15}, period=30, seam=3.0)+ assert record["search"]["verdict"] == "refuted" and record["search"]["k"] == [1]+ assert record["search"]["same_picture"]["over_step"] > local_cycle.SAME_PICTURE_MAX+ assert record["chosen_by"] == "two steps" and picked["steps"] == {"count": 2, "by": "crossings"}+++def test_a_one_step_cut_that_is_the_same_picture_a_cut_on_is_the_searchs_cycle():+ """The same count — one step — on a clip whose picture goes round every 15 frames: the frame a cut on is the+ frame itself, so no legs were swapped and the count missed a crossing. The search's cut stands, no steps written."""+ picked, record = _choose({"start": 10, "length": 15}, period=15, seam=1.0)+ assert (picked["start"], picked["length"]) == (10, 15) and "steps" not in picked+ assert record["chosen_by"] == "search" and record["cut"]["code"] == "same-picture" and record["cut"]["verdict"] == "uncertain"+ assert record["search"]["same_picture"]["over_step"] <= local_cycle.SAME_PICTURE_MAX