Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
fix(video): motion-auto reads the same motion from the same pixels on every machine
Soohong Kimb388b6df2da7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 39c941d..8de206c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,11 @@All notable public changes to `sprite-gen` are recorded here. Versions track the `version:` field in `SKILL.md` and `pyproject.toml`.+## Unreleased++- **Fix: `video-loop --anchor motion-auto` reads the same motion from the same pixels on every machine.** A patch of its region search that sits on a flat fill matches equally at several offsets; the FFTs that score them round differently between numpy builds (about 1e-14), and that rounding chose the offset. From the same frames a synthetic walk was tracked differently on Linux than on macOS, its distance matrix differed in most entries, and `tests/video/test_loop_prop_seam_held.py` failed on CI only (first choice popping 2.4 there, 11.7 on macOS). Now costs within 1e-9 of the lowest are one match (`auto_motion.MATCH_TIE`) and the offset nearest the centre the search was put on is taken; regions whose qualities tie on that grain are ranked by their box; and the drift lines that move the analysis frames are least-squares lines with exactly rounded sums (`auto_motion._line`), not `np.polyfit`, whose LAPACK solve rounded differently and tipped bilinear samples of those frames. The tracked offsets, the analysis frames and the distance matrix are now bit-identical on macOS arm64 and Linux x86-64; only the last digits of reported costs and scores differ. Footage whose patches never tie is cut as before: the same regions, offsets and cut, its analysis translations moved only in their last bits (about 1e-14), which can tip a bilinear sample and move a score in its sixth decimal. Drawn, flat-filled frames, where ties are the rule, are tracked — and may be cut — otherwise than v2.36.0 tracked them on any one machine.+- **`tests/video/test_auto_motion.py`** perturbs every FFT correlation by up to 1e-12 of its largest value, seed by seed: the tied offset taken on the flat torso, the regions found and every tracked offset are the same under all of them (under v2.36.0 eight seeds took six offsets, 14 px apart, and four seeds found four different region pairs), and the drift line is `np.polyfit`'s to 1e-12 and bit-identical in any order of its points. `test_a_held_part_that_swings_with_the_step_is_cut_one_step_long` draws its pennant on a 53-frame beat (phase 0.75): its first choice pops 12.6, no other candidate's top over 8.5, the cut taken closes below the hand at 0.0; on v2.35.0 with this fix it fails where v2.35.0 reads nothing below the top.+## v2.36.0 - 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).diff --git a/docs/loop-review.md b/docs/loop-review.mdindex 2c9e219..3b266b2 100644--- a/docs/loop-review.md+++ b/docs/loop-review.md@@ -80,13 +80,21 @@ counted as rejected candidates; absence of a usable pair is an explicit failure.The correlation at every offset of a search window comes out of FFTs: per channel,the masked patch sum, its squared sum and its product with the centered reference arewindow correlations, so the masked patch is never copied out once per offset. The-costs agree with that direct form to about 1e-6, and two offsets that tie within it-may swap. On three 3 s walk clips at 544 px the region search took 1.0 to 1.4 s of-CPU instead of 22.6 to 37.4 s, and full loops cut from the same frames gave the same-cycle and byte-identical strips.+costs agree with that direct form to about 1e-6. On three 3 s walk clips at 544 px the+region search took 1.0 to 1.4 s of CPU instead of 22.6 to 37.4 s, and full loops cut from+the same frames gave the same cycle and byte-identical strips.++FFT rounding is not the same on every machine (numpy's builds differ by about 1e-14), and+a patch on a flat fill slides: several offsets match it alike. Costs within 1e-9 of the+lowest (`auto_motion.MATCH_TIE`) are one match, and the offset nearest the centre the+search was put on is taken; regions whose qualities tie on that grain are ranked by their+box. Before this the rounding chose, and a synthetic walk was cut at another start on+Linux than on macOS from the same pixels.For selection only, the measured horizontal trajectory is locally fitted and the-vertical linear trend is removed. Local lag minima can then identify a repeat in+vertical linear trend is removed (least-squares lines with exactly rounded sums, not+np.polyfit, whose LAPACK solve rounds differently between machines: the line moves the+analysis frames by a fraction of a pixel, and its last bit can tip a bilinear sample). Local lag minima can then identify a repeat ina clip with changing drift or cadence. Selection requires repeat depth, activemotion around both boundaries, and a supported doubled recurrence when a shortstep falls below the gait floor. Candidate ranking also penalizes drift that adiff --git a/sprite_gen/video/auto_motion.py b/sprite_gen/video/auto_motion.pyindex b47e2af..8edef23 100644--- a/sprite_gen/video/auto_motion.py+++ b/sprite_gen/video/auto_motion.py@@ -7,12 +7,17 @@ fine match. The caller must still gate the rendered, uncorrected output."""from __future__ import annotations+import math+from PIL import Imagefrom sprite_gen._deps import npfrom sprite_gen.video import motion_anchorANALYSIS_EDGE = 184SAMPLE_COUNT = 9+# Two offsets' match costs closer than this are a tie: FFT rounding differs between machines by+# ~1e-14, two different pictures by far more than this.+MATCH_TIE = 1e-9def correct_cycle(frames, regions, *, coarse_dx):@@ -101,8 +106,13 @@ def _match(reference, moving, center, radius):energy += _correlate(values * values, weights, rows, cols) - total * total / countdenominator = np.sqrt(np.maximum(energy, 0.0)) * normcosts = 1 - product / np.maximum(1e-10, denominator)- iy, ix = np.unravel_index(costs.argmin(), costs.shape)- dx, dy = x-(xs+int(ix)), y-(ys+int(iy))+ # A patch on a flat fill matches equally at several offsets, and FFT rounding — not the same on+ # every machine — would pick among them. Costs within MATCH_TIE are one match; the evidence does+ # not decide between them, so the prior does: the offset nearest the centre the search was put on.+ tied = np.argwhere(costs <= costs.min()+MATCH_TIE)+ iy, ix = min(((int(iy), int(ix)) for iy, ix in tied),+ key=lambda at: ((x-(xs+at[1])-cx)**2+(y-(ys+at[0])-cy)**2, at))+ dx, dy = x-(xs+ix), y-(ys+iy)if abs(dx-cx) == radius or abs(dy-cy) == radius:raise ValueError("automatic motion anchor match reached search boundary")return np.array([dx, dy]), float(costs[iy, ix])@@ -149,7 +159,9 @@ def discover(frames: list[Image.Image], *, reference_index: int) -> tuple[list,smoothness = float(np.abs(np.diff(positions, n=2, axis=0)).mean()/body_h)quality = float(np.mean(errors)+.25*np.quantile(errors, .9)+.05*smoothness)candidates.append({'box': box, 'quality': quality, 'sample_costs': errors})- candidates.sort(key=lambda row: (row['quality'], row['box']))+ # Qualities are sums of match costs, so two regions that both track exactly tie but for FFT+ # rounding; read on MATCH_TIE's grain, such a tie is ordered by the box, the same on every machine.+ candidates.sort(key=lambda row: (round(row['quality']/MATCH_TIE), row['box']))if not candidates or candidates[0]['quality'] > .8:raise ValueError("automatic motion anchor found no stable textured region")chosen = []@@ -194,6 +206,20 @@ def discover(frames: list[Image.Image], *, reference_index: int) -> tuple[list,return regions, report+def _line(t, values):+ """(slope, intercept) of the least-squares line through (t, values), t whole numbers.++ Written out with exactly rounded sums rather than np.polyfit, whose LAPACK solve rounds+ differently from machine to machine: the line moves the analysis frames by a fraction of a+ pixel, and a last-bit change there can tip a bilinear sample to the next 8-bit level."""+ t = [int(v) for v in t]+ values = [float(v) for v in values]+ n, st, stt = len(t), sum(t), sum(v*v for v in t)+ sv, stv = math.fsum(values), math.fsum(a*b for a, b in zip(t, values))+ det = n*stt-st*st+ return (n*stv-st*sv)/det, (stt*sv-st*stv)/det++def analyse(frames: list[Image.Image], *, fps: float) -> tuple[np.ndarray, np.ndarray, dict]:_, report = discover(frames, reference_index=len(frames)//2)size = tuple(report['analysis_size'])@@ -206,10 +232,10 @@ def analyse(frames: list[Image.Image], *, fps: float) -> tuple[np.ndarray, np.ndtrajectory = []for k in range(n):js = np.arange(max(0, k-radius), min(n, k+radius+1))- trajectory.append(float(np.polyfit(js-k, positions[js, 0], 1)[1]))+ trajectory.append(_line(js-k, positions[js, 0])[1])trajectory = np.asarray(trajectory)trajectory -= trajectory[n//2]- dy_slope = float(np.polyfit(np.arange(n), positions[:, 1], 1)[0])+ dy_slope = _line(range(n), positions[:, 1])[0]shifts = np.column_stack((trajectory, dy_slope*(np.arange(n)-n//2)))pad = int(np.ceil(np.abs(shifts).max()))+4normalized = []diff --git a/tests/video/test_auto_motion.py b/tests/video/test_auto_motion.pyindex f62da3f..ef338aa 100644--- a/tests/video/test_auto_motion.py+++ b/tests/video/test_auto_motion.py@@ -83,8 +83,9 @@ def test_match_equals_the_gathered_masked_ncc():continueexpected = gathered_match(reference, moving, center, 12)best = min(expected.values())- # The flat synthetic torso matches itself at several vertical shifts; float noise picks- # among an exact tie in either implementation, so any member of the tie is right.+ # The flat synthetic torso matches itself at several vertical shifts. The direct form+ # rounds in float32, so its tie is read loosely; the FFT form takes, among its own tie+ # (MATCH_TIE), the offset nearest the centre it searched around.ties = [offset for offset, cost in expected.items() if cost <= best + 1e-5]assert tuple(got[0].tolist()) in tiesassert abs(got[1]-expected[tuple(got[0].tolist())]) < 1e-6@@ -95,6 +96,64 @@ def test_match_equals_the_gathered_masked_ncc():assert unique >= 12 and tied >= 1+def _rounding(monkeypatch, seed):+ """FFT rounding as another machine might do it: every correlation off by up to 1e-12 of its+ largest value — more than numpy's FFTs differ by between machines (~1e-14), far under MATCH_TIE."""+ rng = np.random.default_rng(seed)+ correlate = auto_motion._correlate++ def noisy(region, kernel, rows, cols):+ out = correlate(region, kernel, rows, cols)+ return out + rng.uniform(-1e-12, 1e-12, out.shape)*max(1.0, float(np.abs(out).max()))+ monkeypatch.setattr(auto_motion, '_correlate', noisy)+++def test_match_takes_the_tied_offset_nearest_the_centre_whatever_the_rounding(monkeypatch):+ """The flat torso slides: several offsets match it alike. Which one is taken is the prior's word+ (nearest the centre searched around), never the rounding's — on v2.36.0 the rounding picked."""+ a = auto_motion.motion_anchor._features(walker(0))+ moving = auto_motion.motion_anchor._features(walker(9))+ reference = auto_motion._reference(a, (44, 60, 72, 84))+ center = (-9, -1)+ expected = gathered_match(reference, moving, center, 12)+ best = min(expected.values())+ ties = [offset for offset, cost in expected.items() if cost <= best + 1e-5]+ assert len(ties) >= 3+ nearest = min(ties, key=lambda o: ((o[0]-center[0])**2+(o[1]-center[1])**2, -o[1], -o[0]))+ taken = set()+ for seed in range(8):+ _rounding(monkeypatch, seed)+ taken.add(tuple(auto_motion._match(reference, moving, center, 12)[0].tolist()))+ monkeypatch.undo()+ assert taken == {nearest}+++def test_region_discovery_is_the_same_whatever_the_rounding(monkeypatch):+ """Regions that track the synthetic walker exactly tie on quality but for the rounding: the+ regions, their order and every tracked offset are the same under any of it."""+ frames = [walker(k) for k in range(40)]+ seen = set()+ for seed in range(4):+ _rounding(monkeypatch, seed)+ regions, report = auto_motion.discover(frames, reference_index=20)+ seen.add((tuple(map(tuple, regions)), tuple(map(tuple, report['tracking_xy']))))+ monkeypatch.undo()+ assert len(seen) == 1+++def test_line_is_the_least_squares_line_and_the_same_in_any_order():+ """analyse's drift line: np.polyfit's, but written out with exactly rounded sums, so the order the+ points are summed in — which differs between machines' LAPACK — cannot reach its last bit."""+ rng = np.random.default_rng(3)+ t = np.arange(-12, 13)+ values = rng.normal(40, 9, len(t)).round(1)*0.7+ slope, intercept = auto_motion._line(t, values)+ np.testing.assert_allclose([slope, intercept], np.polyfit(t, values, 1), rtol=0, atol=1e-12)+ for seed in range(20):+ order = np.random.default_rng(seed).permutation(len(t))+ assert auto_motion._line(t[order], values[order]) == (slope, intercept)++def test_region_discovery_refuses_blank_input():with pytest.raises(ValueError, match='visible foreground'):auto_motion.discover([Image.new('RGBA', (100, 100)) for _ in range(6)], reference_index=0)diff --git a/tests/video/test_loop_prop_seam_held.py b/tests/video/test_loop_prop_seam_held.pyindex 3762002..e5e6afe 100644--- a/tests/video/test_loop_prop_seam_held.py+++ b/tests/video/test_loop_prop_seam_held.py@@ -118,10 +118,11 @@ def test_motion_auto_takes_two_steps_where_the_held_staff_closes_only_there(helddef test_a_held_part_that_swings_with_the_step_is_cut_one_step_long(tmp_path):- """A pennant at the tip sways on a beat of its own (61 frames) and pops at the first choice; the+ """A pennant at the tip sways on a beat of its own (53 frames) and pops at the first choice; thestaff stands straight above the hand and swings with the step below it, so a one-step cut whose- top closes closes below the hand too and is taken."""- report = _cut(tmp_path, _keyed(tmp_path, tip_amp=0, foot_swing=STEP, flag=(61, 3.0)))+ top closes closes below the hand too and is taken. The first choice's pop is 12.6 and no other+ candidate's reaches 8.5; the cut taken closes below the hand at 0.0 (over 1.2 does not)."""+ report = _cut(tmp_path, _keyed(tmp_path, tip_amp=0, foot_swing=STEP, flag=(53, 0.75)))cycle = report["cycle"]shape = cycle["seam_pop"]assert shape["first_choice"]["pop"] > repair.SEAM_POP_REFERENCE and shape["applied"] is True