Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
fix(video): validate uncorrected loops after uncertain XY matches
Soohong Kim97ebc9c7381a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6e8b851..19a4ab1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,8 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the## Unreleased+- In `motion-auto`, an uncertain fine XY search-boundary match can emit the selected frames unchanged only after the existing rendered-cell seam gate and animation checks pass. Reports and the CLI expose the rejected measurement and unapplied correction. Other failures and explicit `motion` registration remain strict.+- Add explicit `video-loop --anchor motion` for reviewed fixed cuts with head and torso regions. Masked XY registration and boundary velocity determine one integer translation ramp; padded cycle PNGs retain the original keyed pixels. Reports record the inputs and shifts, and the unchanged seam threshold measures the rendered output. Automatic cycle selection and existing anchor defaults are unchanged; batch generation rejects this review-only mode before provider work.- Add opt-in `--anchor motion-auto` for walk/run in `video-loop` and `video-set`: discover stable texture regions, separate drift during local repeat analysis, and apply the same XY boundary-velocity ramp without manual cut/region inputs. Keep source motion and pixels in padded cycle frames; gate the rendered cells. Reports expose automatic tracking, candidate selection, and correction. Existing defaults stay unchanged.diff --git a/docs/loop-review.md b/docs/loop-review.mdindex 2144617..66447b0 100644--- a/docs/loop-review.md+++ b/docs/loop-review.md@@ -93,6 +93,15 @@ Automatic results carry `review_recommended=true`: these measurements cannotestablish limb identity or fix changing drawings. Validate unfamiliar body shapesand motions visually; no animal-wide quality claim follows from humanoid examples.+If the selected cycle's fine XY match reaches its bounded search edge,+`motion-auto` discards that uncertain correction and submits the unchanged selected+frames to the same rendered-cell seam gate. It emits them only if that gate and+normal animation verification pass. Reports and the CLI summary explicitly say+`applied: false`, retain the rejected match and record zero translations; this is+an uncorrected output, not a successful registration. Failed period selection,+unusable regions, coarse-search limits and other errors still fail. The explicit+`motion` mode also keeps its strict registration contract.+## Explicit adjustmentsIf the visible full cycle is clear but the automatic candidate is wrong, make the choicediff --git a/sprite_gen/video/auto_motion.py b/sprite_gen/video/auto_motion.pyindex 52eb988..116d192 100644--- a/sprite_gen/video/auto_motion.py+++ b/sprite_gen/video/auto_motion.py@@ -2,7 +2,8 @@"""Discover stable texture regions and remove drift for cycle ANALYSIS only.No semantic body labels, character profiles, learned weights or external models.-The emitted animation is still corrected by motion_anchor's single integer ramp.+Output correction uses one integer ramp, or explicitly abstains from an uncertain+fine match. The caller must still gate the rendered, uncorrected output."""from __future__ import annotations@@ -14,6 +15,27 @@ ANALYSIS_EDGE = 184SAMPLE_COUNT = 9+def correct_cycle(frames, regions, *, coarse_dx):+ """Do not turn an uncertain fine match into a potentially damaging shift.++ Returning unchanged pixels is not a pass: the loop owner always runs the+ rendered-cell seam gate and animation verification before accepting output.+ Other registration/discovery errors retain their failure contract.+ """+ try:+ return motion_anchor.correct_motion(frames, regions, coarse_dx=coarse_dx)+ except motion_anchor.FineSearchBoundaryError as exc:+ return frames, {+ "method": "uncorrected-after-uncertain-fine-match-v1",+ "applied": False, "reason": "fine-match-at-search-boundary",+ "registration_error": str(exc), "rejected_measurement": exc.measurement,+ "requires_rendered_seam_gate": True,+ "regions": [list(box) for box in regions], "coarse_dx_px": coarse_dx,+ "endpoint_xy": [0, 0], "shifts_xy": [[0, 0] for _ in frames],+ "padding_ltrb": [0, 0, 0, 0],+ }++def _center(a):y, x = np.nonzero(a[:, :, 3] > .1)if not len(x):diff --git a/sprite_gen/video/batch.py b/sprite_gen/video/batch.pyindex 998def4..5368e96 100644--- a/sprite_gen/video/batch.py+++ b/sprite_gen/video/batch.py@@ -188,6 +188,8 @@ def run_item(result["loop"] = {"kind": lp["cycle"].get("kind", "periodic"), "cycle": lp["cycle"]["length"], "period": lp["cycle"]["period_global"], "cycle_ratio": round(lp["cycle"]["ratio"], 3), "seam_ratio": lp["resampled_seam_ratio"], "n_out": lp["n_out"], "drift_px": lp["strip"].get("drift_px", 0), "gif": lp["gif"]["file"], "webp": lp["webp"]["file"], "strip": lp["strip"]["path"]}result["loop"]["review_recommended"] = lp["cycle"].get("review_recommended", False)result["loop"]["half_period_guard"] = lp["cycle"].get("half_period_guard")+ if lp.get("motion_anchor", {}).get("applied") is False:+ result["loop"]["motion_anchor"] = lp["motion_anchor"]result["ok"] = Trueexcept SystemExit as exc:result["ok"] = False@@ -201,6 +203,8 @@ def write_table(results: list[dict[str, Any]], path: Path) -> str:if r.get("ok"):lp = r["loop"]status = "OK (review gait)" if lp.get("review_recommended") else "OK"+ if lp.get("motion_anchor", {}).get("applied") is False:+ status = "OK (uncorrected; review gait)"lines.append(f"| {r['direction']} | {r['state']} | {lp.get('kind', 'periodic')} | {lp['cycle']} | {lp['period'] if lp['period'] is not None else '-'} | {lp['seam_ratio']:.2f} | {lp['n_out']} | {status} |")else:lines.append(f"| {r['direction']} | {r['state']} | - | - | - | - | - | FAIL: {r.get('error', '')[:80]} |")diff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.pyindex c601914..ec19a49 100644--- a/sprite_gen/video/loop.py+++ b/sprite_gen/video/loop.py@@ -852,7 +852,8 @@ def run_loop(if anchor == "motion-auto":anchor_regions, region_report = auto_motion.discover(frames, reference_index=0)report_base["automatic_motion_regions"] = region_report- frames, motion = motion_anchor.correct_motion(+ correct = auto_motion.correct_cycle if anchor == "motion-auto" else motion_anchor.correct_motion+ frames, motion = correct(frames, anchor_regions, coarse_dx=body_wrap_offset(frames, search=motion_anchor.COARSE_SEARCH),)except ValueError as exc:@@ -990,6 +991,8 @@ def run(**kwargs: object) -> int:summary["cycle"] = {k: payload["cycle"].get(k) for k in ("kind", "start", "length", "period_global", "ratio", "review_recommended", "half_period_guard")}if payload["periodic_attempt"]:summary["periodic_attempt"] = payload["periodic_attempt"]["why_rejected"]+ if payload.get("motion_anchor", {}).get("applied") is False:+ summary["motion_anchor"] = payload["motion_anchor"]summary["strip"] = {k: payload["strip"][k] for k in ("path", "frames", "w", "h", "body_h", "delay_ms")}print(json.dumps(summary, ensure_ascii=False, indent=2))return 0diff --git a/sprite_gen/video/motion_anchor.py b/sprite_gen/video/motion_anchor.pyindex e4d3a76..509ef0e 100644--- a/sprite_gen/video/motion_anchor.py+++ b/sprite_gen/video/motion_anchor.py@@ -19,6 +19,14 @@ COARSE_SEARCH = 64Box = tuple[int, int, int, int]+class FineSearchBoundaryError(ValueError):+ """A measured candidate is outside the trusted fine-registration interior."""++ def __init__(self, measurement: dict):+ super().__init__("motion anchor match reached search boundary; inspect the cut and regions")+ self.measurement = measurement++def parse_region(value: str) -> Box:try:coordinates = tuple(int(v.strip()) for v in value.split(","))@@ -102,7 +110,10 @@ def _register(references: list[tuple], moving: np.ndarray, center: tuple[int, incandidates.sort()score, dx, dy, costs = candidates[0]if abs(dx - cx) == rx or abs(dy - cy) == ry:- raise ValueError("motion anchor match reached search boundary; inspect the cut and regions")+ raise FineSearchBoundaryError({+ "dx": dx, "dy": dy, "cost": score, "region_costs": costs,+ "center_xy": [cx, cy], "search_radius_xy": [rx, ry],+ })return {"dx": dx, "dy": dy, "cost": score, "region_costs": costs}@@ -123,7 +134,11 @@ def correct_motion(frames: list[Image.Image], regions: list[Box], *, coarse_dx:measurements = []for k in (0, 1, 2, length - 3, length - 2, length - 1):center = (round(coarse_dx * k / (length - 1)), 0)- measurements.append({"k": k, **_register(references, _features(frames[k]), center)})+ try:+ measurements.append({"k": k, **_register(references, _features(frames[k]), center)})+ except FineSearchBoundaryError as exc:+ exc.measurement["k"] = k+ raisepositions = -np.array([[r["dx"], r["dy"]] for r in measurements], dtype=float)v_start = (positions[2] - positions[0]) / 2v_end = (positions[5] - positions[3]) / 2diff --git a/tests/video/test_auto_motion_uncorrected.py b/tests/video/test_auto_motion_uncorrected.pynew file mode 100644index 0000000..5a61e79--- /dev/null+++ b/tests/video/test_auto_motion_uncorrected.py@@ -0,0 +1,88 @@+"""An uncertain registration must not hide either its failure or a bad raw seam."""+import json+import math++import numpy as np+import pytest+from PIL import Image, ImageDraw+from sprite_gen.video import auto_motion, batch, loop, motion_anchor+++def bouncing_walker(k, *, bounce=60, drift=0):+ x = 110 + drift * k+ y = 95 + round(bounce * math.sin(k * 2 * math.pi / 24))+ im = Image.new("RGBA", (400, 300))+ d = ImageDraw.Draw(im)+ d.rectangle((x, y, x+28, y+30), fill=(210, 150, 60, 255))+ d.rectangle((x+20, y+8, x+24, y+12), fill=(10, 30, 50, 255))+ d.rectangle((x-3, y+32, x+30, y+78), fill=(20, 90, 180, 255))+ d.rectangle((x+10, y+35, x+15, y+73), fill=(210, 190, 40, 255))+ leg = round(12 * math.sin(k * 2 * math.pi / 24))+ d.rectangle((x+leg, y+79, x+6+leg, y+119), fill=(80, 30, 60, 255))+ d.rectangle((x+24-leg, y+79, x+30-leg, y+119), fill=(30, 60, 90, 255))+ return im+++def write_source(path, **kwargs):+ path.mkdir()+ for k in range(73):+ bouncing_walker(k, **kwargs).save(path / f"{k:03}.png")+ return path+++def test_real_boundary_match_emits_verified_unchanged_cycle_and_exposes_it(tmp_path, capsys):+ keyed = write_source(tmp_path / "keyed")+ out = tmp_path / "out"+ args = ["--frames-dir", str(keyed), "--out-dir", str(out), "--state", "walk"]+ assert loop.main(args + ["--anchor", "motion-auto"]) == 0+ summary = json.loads(capsys.readouterr().out)+ report = json.loads((out / "loop.loop.report.json").read_text())+ motion = report["motion_anchor"]+ assert summary["motion_anchor"] == motion+ assert motion["applied"] is False+ match = motion["rejected_measurement"]+ assert abs(match["dy"] - match["center_xy"][1]) == match["search_radius_xy"][1]+ assert motion["endpoint_xy"] == [0, 0]+ assert report["resampled_seam_ratio"] <= report["seam_max"] == 2+ assert report["gif"]["n_frames"] == report["webp"]["n_frames"] == report["n_out"]+ for k, p in enumerate(sorted((out / "cycle").glob("*.png"))):+ np.testing.assert_array_equal(np.asarray(Image.open(p)),+ np.asarray(bouncing_walker(report["cycle"]["start"] + k)))+ # The same real match remains an error for explicitly requested correction.+ fixed = args + ["--anchor", "motion", "--cycle", "fixed",+ "--start", str(report["cycle"]["start"]), "--length", str(report["cycle"]["length"])]+ for box in motion["regions"]:+ fixed += ["--anchor-region", ",".join(map(str, box))]+ with pytest.raises(SystemExit, match="search boundary"):+ loop.main(fixed)+++def test_uncertain_match_does_not_accept_bad_uncorrected_seam(tmp_path, monkeypatch):+ keyed = write_source(tmp_path / "keyed", bounce=3, drift=2)+ def uncertain(*args, **kwargs):+ raise motion_anchor.FineSearchBoundaryError({"k": 2, "dx": 14, "dy": 0})+ monkeypatch.setattr(motion_anchor, "correct_motion", uncertain)+ out = tmp_path / "out"+ with pytest.raises(SystemExit, match="loop seam ratio"):+ loop.main(["--frames-dir", str(keyed), "--out-dir", str(out), "--state", "walk",+ "--anchor", "motion-auto"])+ report = json.loads((out / "loop.loop.report.json").read_text())+ assert report["status"] == "failed" and report["resampled_seam_ratio"] > 2+ assert report["motion_anchor"]["applied"] is False+ assert not (out / "loop.gif").exists() and not (out / "loop.webp").exists()+++def test_other_registration_failures_are_not_converted_to_uncorrected_output():+ frames = [bouncing_walker(k) for k in range(24)]+ with pytest.raises(ValueError, match="coarse match reached"):+ auto_motion.correct_cycle(frames, [], coarse_dx=64)+ with pytest.raises(ValueError, match="no foreground"):+ auto_motion.correct_cycle(frames, [(0, 0, 5, 5)] * 2, coarse_dx=0)+++def test_batch_table_discloses_uncorrected_output(tmp_path):+ text = batch.write_table([{"ok": True, "direction": "side", "state": "walk", "loop": {+ "cycle": 24, "period": None, "seam_ratio": 1.0, "n_out": 24,+ "review_recommended": True, "motion_anchor": {"applied": False},+ }}], tmp_path / "table.md")+ assert "OK (uncorrected; review gait)" in textdiff --git a/tests/video/test_gait_guard_anchor_wide.py b/tests/video/test_gait_guard_anchor_wide.pyindex 0fa0196..f875abf 100644--- a/tests/video/test_gait_guard_anchor_wide.py+++ b/tests/video/test_gait_guard_anchor_wide.py@@ -213,7 +213,10 @@ def test_video_set_passes_shape_and_anchor_through(tmp_path: Path, monkeypatch,def fake_loop(frames_dir, out_dir, **kw):seen["anchor"] = kw.get("anchor")- return {"cycle": {"kind": "periodic", "length": 24, "period_global": 24, "ratio": 0.2}, "resampled_seam_ratio": 0.3, "n_out": 8, "gif": {"file": "g"}, "webp": {"file": "w"}, "strip": {"path": "s", "drift_px": 0}}+ report = {"cycle": {"kind": "periodic", "length": 24, "period_global": 24, "ratio": 0.2}, "resampled_seam_ratio": 0.3, "n_out": 8, "gif": {"file": "g"}, "webp": {"file": "w"}, "strip": {"path": "s", "drift_px": 0}}+ if anchor == "motion-auto":+ report["motion_anchor"] = {"applied": False, "reason": "fine-match-at-search-boundary"}+ return reportdef fake_video(image, prompt, out, report, *, duration, resolution, log):Path(out).write_bytes(b"x")@@ -232,6 +235,9 @@ def test_video_set_passes_shape_and_anchor_through(tmp_path: Path, monkeypatch,assert payload["ok"] == 1# the frames step is told to judge spill from the item's own canvas stillassert seen == {"shape": "wide", "anchor": anchor, "spill": ("auto", "canvas.png")}+ if anchor == "motion-auto":+ assert payload["items"][0]["loop"]["motion_anchor"]["applied"] is False+ assert "uncorrected" in (tmp_path / "set/table.md").read_text()def test_cheer_motion_template_names_no_limbs() -> None: