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's jump frames are remade by RIFE, the rest stay the video's own
Soohong Kim78d3314a7cfe
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex fc8e4e2..08733c9 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -26,6 +26,14 @@ jobs:sudo cp /tmp/libwebp-1.6.0-linux-x86-64/bin/* /usr/local/bin/img2webp -h 2>&1 | grep -q -- -exact # img2webp -version exits 1 without an output file; -h is the honest probe+ - name: Install RIFE for video-loop's jump repair (rife-ncnn-vulkan 20221029 on Mesa llvmpipe, docs/loop-repair.md)+ run: |+ sudo apt-get install -y -qq libvulkan1 mesa-vulkan-drivers unzip+ curl -fsSL -o /tmp/rife.zip https://github.com/nihui/rife-ncnn-vulkan/releases/download/20221029/rife-ncnn-vulkan-20221029-ubuntu.zip+ echo '1e2c7ee7fa7daa326542d50622f0afedc80cf6f1858bda411d16385ffa5cdf68 /tmp/rife.zip' | sha256sum -c -+ sudo unzip -q /tmp/rife.zip -d /opt+ sudo ln -s /opt/rife-ncnn-vulkan-20221029-ubuntu/rife-ncnn-vulkan /usr/local/bin/rife-ncnn-vulkan+- uses: actions/setup-python@v5with:python-version: ${{ matrix.python-version }}diff --git a/docs/loop-repair.md b/docs/loop-repair.mdindex 3fd3246..5ea7686 100644--- a/docs/loop-repair.md+++ b/docs/loop-repair.md@@ -95,6 +95,42 @@ for the same model, and llvmpipe already gives the GPU's frame.sprite-gen ships none of these. A deployment that bakes the release zip into an image shipsthe zip's `LICENSE` with it.+## 2. Jump frames — `video-loop --repair auto`++A walk or run loop (`--state walk|run`) is read, after it is cut and anchored, as it will play:+cyclic, the last frame followed by the first, inside the union box of the body over the loop+(the strip cells' own crop). For every step k → k+1 two numbers are taken — the mean change of+coverage over the whole box, and over the hair behind the body, each divided by its own median+over the loop — and the larger is the step's score.++| Rule | Value | Why |+|---|---|---|+| A jump | a score of at least **1.4** (`JUMP_RATIO`) | the ponytail cuts the experiment found sat at 1.5–2.5; a smooth take's worst step sits near 1.3 |+| The hair box | (0, 0.30)–(0.45, 0.80) of the union box for a right-facing body; mirrored for `--facing left` | below the head and behind the body, where a ponytail cut at the wrong moment jumps |+| The frame remade | the frame after the jump; but when the step *into* frame k is a jump too and larger than the step after k+1, frame k itself (a single stray frame breaks two steps) | remaking the frame after a stray frame leaves the stray standing |+| How | RIFE's frame half way between the frame's two neighbours | every other frame stays the video's own |+| How many | at most **3** (`MAX_REPAIRS`), worst first, scores re-read after each | a loop that needs more is jolting everywhere, not jumping once |+| Never | a frame next to one already made | two made frames side by side are made from each other and melt the legs |++Re-making every frame (an offset of half a frame) is not offered: it softens the frames that+were fine, and it was judged "not corrected" (2026-10-03).++The report's `jump_repair` carries `replaced` (cycle frame indices), each round's step, score and+its whole/hair parts, `score_max_before` / `score_max_after`, why it stopped, and which+interpolator made the frames. When a frame was replaced the seam gate measures the rendered cells+(`seam_measurement: rendered-cells`), because the source frames no longer say what plays.++RIFE is located only when a frame is to be made. A loop with a jump and no RIFE fails with the+install line and `--repair off`, which cuts the loop as filmed and records+`jump_repair: {"applied": false, "why": "--repair off"}`. Other states are not touched+(`"why": "not a gait state (…)"`).++Checked on the 2026-10-03 takes (`retime.py` in the experiment folder is the reference): the+engine replaces the same frames as the experiment on every take tried — Lite side E1+[0, 16, 8] (score 1.75 → 1.42), Lite back-diagonal NE2 [13, 0] (1.60 → 1.43), Pro side E1+[3, 15, 19], Pro back-diagonal NE2 [9], Lite front S2 [0, 11, 14], and nothing in the smooth+Lite side E2. About 0.7 s a replaced frame on the Mac's GPU.+## Related- [video-pipeline.md](video-pipeline.md) — the pipeline these repairs run insidediff --git a/docs/video-pipeline.md b/docs/video-pipeline.mdindex 2d889a4..cc6794f 100644--- a/docs/video-pipeline.md+++ b/docs/video-pipeline.md@@ -397,6 +397,12 @@ Gates, all fail-loud: no period (profile flat, below the recorded `periodicity_mabove `--seam-max` (2.0), GIF/WebP re-opened and checked (frame count, `loop=0`,transparent corners, no RGB under alpha 0 in the WebP).+A walk or run loop then has its jump frames repaired before the strip is built: a frame that+breaks a step 1.4× the loop's median (whole body, or the hair behind it) is replaced by RIFE's+frame between its two neighbours, at most three and never two side by side (`--repair auto`,+the default; `--repair off` cuts as filmed). The report's `jump_repair` names the frames. See+[loop repair](loop-repair.md).+### One-shot actions — `--cycle auto|periodic|one-shot`A video model asked to jump "over and over" sometimes jumps once and stands for thediff --git a/sprite_gen/video/batch.py b/sprite_gen/video/batch.pyindex b45d928..aeddec3 100644--- a/sprite_gen/video/batch.py+++ b/sprite_gen/video/batch.py@@ -392,7 +392,8 @@ def run_item(result["frames"] = {k: fr[k] for k in ("fps", "frames", "alpha_zero_pct_min", "alpha_zero_pct_max")}result["frames"]["spill"] = fr.get("spill", {}).get("mode")lp = loop_mod.run_loop(Path(fr["keyed_dir"]), item_dir / "loop", fps=float(fr["fps"]), state=state, min_len=None, max_len=None, n_out=None, seam_max=loop_mod.SEAM_RATIO_MAX, name=item, report_path=item_dir / "loop.report.json", anchor=anchor, body_height=body_height,- cycle_mode="pinned" if state in PINNED_LOOP_STATES else "auto")+ cycle_mode="pinned" if state in PINNED_LOOP_STATES else "auto",+ facing=facing if direction == "side" else "right")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")diff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.pyindex 1a508eb..ec5dd70 100644--- a/sprite_gen/video/loop.py+++ b/sprite_gen/video/loop.py@@ -40,6 +40,8 @@ from sprite_gen._deps import npfrom sprite_gen.spec.runio import atomic_write_textfrom sprite_gen.util.gif_utils import save_clean_giffrom sprite_gen.video import motion_anchor, auto_motion, local_cycle, gait_fallback+from sprite_gen.video import repair as repair_mod+from sprite_gen.video import rife as rife_modANALYSIS_SIZE = 96 # thumbnail edge for the distance matrixSTRIP_MAX_CELLS = 64 # upper bound on cells even when they are narrow@@ -80,6 +82,10 @@ ANCHOR_MODES = ("none", "feet", "body", "motion", "motion-auto")BODY_ANCHOR_BAND = 0.6 # --anchor body reads the wrap offset from the top 60 % of the first frame's box: head and torso, not the legsBODY_ANCHOR_SEARCH = 24 # px either side searched for the last frame's horizontal offset against the firstFOOT_BAND = 0.08 # fraction of the frame's own height, measured up from its lowest opaque row+# Jump-frame repair (docs/loop-repair.md section 2). auto: walk and run loops get a RIFE frame in+# place of each frame that follows a jump; off: the loop is cut as filmed, and says so.+REPAIR_MODES = ("auto", "off")+FACINGS = ("right", "left")# A gait's period is a fact about the body, not about how long the clip runs: the@@ -770,6 +776,28 @@ def write_loop_report(target: Path, payload: dict[str, Any]) -> None:atomic_write_text(target, json.dumps(finite(payload), ensure_ascii=False, indent=2, allow_nan=False) + "\n")+def _repair_jumps(frames: list[Image.Image], interpolate: rife_mod.Interpolate | None, *, facing: str) -> tuple[list[Image.Image], dict[str, Any]]:+ """`repair_mod.repair_jumps`, with RIFE located only once a frame is to be made: a loop+ without a jump needs no binary. The report names the interpolator that made the frames."""+ made_by: list[dict[str, str]] = []++ def lazy(a: Image.Image, b: Image.Image, t: float) -> Image.Image:+ nonlocal interpolate+ if interpolate is None:+ located = rife_mod.Rife()+ made_by.append(located.describe())+ interpolate = located+ return interpolate(a, b, t)++ frames, record = repair_mod.repair_jumps(frames, lazy, facing=facing)+ record["applied"] = bool(record["replaced"])+ if made_by:+ record["interpolator"] = {"kind": "rife-ncnn-vulkan", **made_by[0]}+ elif record["replaced"]:+ record["interpolator"] = {"kind": "injected"}+ return frames, record++def run_loop(frames_dir: Path,out_dir: Path,@@ -790,7 +818,14 @@ def run_loop(body_height: int | None = None,anchor: str | None = None,anchor_regions: list[motion_anchor.Box] | None = None,+ repair: str = "auto",+ facing: str = "right",+ interpolate: rife_mod.Interpolate | None = None,) -> dict[str, Any]:+ if repair not in REPAIR_MODES:+ raise SystemExit(f"video-loop: unknown --repair {repair!r}; expected one of {', '.join(REPAIR_MODES)}")+ if facing not in FACINGS:+ raise SystemExit(f"video-loop: unknown --facing {facing!r}; expected one of {', '.join(FACINGS)}")if anchor is None:# gaits drift a few pixels over a cycle and the wrap shows it; in-place states do notanchor = "body" if profile_for(state).gait else "none"@@ -936,6 +971,20 @@ def run_loop(write_loop_report(target, {**report_base, "status": "failed", "error": error, "cycle": cycle})raise SystemExit(error) from excreport_base["motion_anchor"] = motion+ if repair == "auto" and prof.gait:+ report_base["jump_repair"] = None+ try:+ frames, report_base["jump_repair"] = _repair_jumps(frames, interpolate, facing=facing)+ except (ValueError, rife_mod.RifeUnavailable) as exc:+ error = (f"video-loop: {exc}; the loop has a jump frame to repair — install RIFE, or pass --repair off "+ "to cut it as filmed (docs/loop-repair.md)")+ shutil.rmtree(out_dir / FALLBACK_FRAMES_DIR, ignore_errors=True)+ write_loop_report(target, {**report_base, "status": "failed", "error": error, "cycle": cycle})+ raise SystemExit(error) from exc+ if report_base["jump_repair"]["replaced"]:+ report_base["seam_measurement"] = "rendered-cells"+ else:+ report_base["jump_repair"] = {"applied": False, "why": "--repair off" if repair == "off" else f"not a gait state ({state})"}cycle_dir.mkdir(parents=True, exist_ok=True)for old in cycle_dir.glob("frame-*.png"):old.unlink()@@ -972,8 +1021,8 @@ def run_loop(seam_idx = [i + j for j in idx]resampled_adjacent = float(np.mean([D[seam_idx[k], seam_idx[k + 1]] for k in range(len(seam_idx) - 1)]))resampled_seam = float(D[seam_idx[-1], seam_idx[0]])- if anchor in ("motion", "motion-auto"):- # Gate the actual corrected/resampled strip cells, with the same limit.+ if report_base["seam_measurement"] == "rendered-cells":+ # Gate the actual corrected/repaired/resampled strip cells, with the same limit.flat = np.stack([_small_features(im) for im in pick])resampled_adjacent = float(np.abs(flat[1:] - flat[:-1]).mean())resampled_seam = float(np.abs(flat[-1] - flat[0]).mean())@@ -1061,6 +1110,8 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:parser.add_argument("--body-height", type=int, help="scale so the STANDING height (the subject in the clip's first frame, i.e. the base still's pose) is this many px — the same value across states gives the same character size; --strip-height stays the cap")parser.add_argument("--anchor", choices=ANCHOR_MODES, default=None, help="motion-auto: automatic stable regions, local repeat selection and XY ramp (walk/run); motion: fixed cut with explicit regions; body (default for walk/run): measure the last-to-first head-and-torso offset once and spread it as a ramp over the cycle; feet: remove in-canvas drift (a straight-line trend) so every cell stands on the mean foot line; none: leave placement as filmed (default for other states)")parser.add_argument("--anchor-region", type=motion_anchor.parse_region, action="append", help="motion anchor only: repeat twice with head then torso x0,y0,x1,y1 in the first selected frame; requires --cycle fixed and at least 6 frames")+ parser.add_argument("--repair", choices=REPAIR_MODES, default="auto", help="auto (default): in a walk or run loop, a frame that follows a jump (a step 1.4x the median, whole body or the hair behind it) is replaced by RIFE's frame between its neighbours, at most 3 and never two side by side, recorded in the report (docs/loop-repair.md); off: cut as filmed")+ parser.add_argument("--facing", choices=FACINGS, default="right", help="which way the body faces in the frames (default right): the hair the jump search watches is behind it")parser.add_argument("--name", default="loop", help="basename for strip/gif/webp outputs")parser.add_argument("--report", type=Path)@@ -1076,6 +1127,7 @@ def run(**kwargs: object) -> int:body_height=kwargs.get("body_height"), # type: ignore[arg-type]anchor=kwargs.get("anchor"), # None resolves by state inside run_loopanchor_regions=kwargs.get("anchor_region"),+ repair=str(kwargs.get("repair") or "auto"), facing=str(kwargs.get("facing") or "right"),)summary = {k: payload[k] for k in ("state", "frames_total", "window", "cycle_seconds", "n_out", "delay_ms", "resampled_seam_ratio", "specks_dropped", "report")}summary["cycle"] = {k: payload["cycle"].get(k) for k in ("kind", "start", "length", "period_global", "ratio", "review_recommended", "half_period_guard")}@@ -1083,6 +1135,8 @@ def run(**kwargs: object) -> int:summary["periodic_attempt"] = payload["periodic_attempt"]["why_rejected"]if payload.get("motion_anchor", {}).get("applied") is False:summary["motion_anchor"] = payload["motion_anchor"]+ if payload.get("jump_repair", {}).get("replaced"):+ summary["jump_repair"] = {k: payload["jump_repair"][k] for k in ("replaced", "score_max_before", "score_max_after")}summary["strip"] = {k: payload["strip"][k] for k in ("path", "frames", "w", "h", "body_h", "delay_ms")}print(json.dumps(summary, ensure_ascii=False, indent=2))return 0diff --git a/sprite_gen/video/repair.py b/sprite_gen/video/repair.pynew file mode 100644index 0000000..3bf7148--- /dev/null+++ b/sprite_gen/video/repair.py@@ -0,0 +1,125 @@+# SPDX-License-Identifier: Apache-2.0+"""Jump frames in a walk loop, found by how much the body's coverage changes, replaced by RIFE.++A video model redraws thin hair a little differently every frame, and now and then a ponytail+lands somewhere it was not one frame earlier: one step of the loop changes far more than the+loop's usual step. That step is a jump; the frame after it is replaced by the frame RIFE makes+half-way between its two neighbours, and every other frame stays the video's own+(docs/loop-repair.md section 2). Re-making every frame instead (an offset of half a frame) also+softens the frames that were fine, and was judged "not corrected" (2026-10-03).++Measured on the loop as it plays — cyclic, the last frame followed by the first — and inside+the union box of the body over the whole loop, the way the strip cells are cut, so a frame's+score does not depend on where the canvas put the body.+"""++from __future__ import annotations++from typing import Any++from PIL import Image++from sprite_gen._deps import np+from sprite_gen.video.rife import Interpolate++# A step this many times the loop's median step (whole body, or the hair behind it) is a jump.+JUMP_RATIO = 1.4+# Frames replaced at most per loop. A loop that needs more is jolting everywhere, not jumping+# once, and a few made frames do not fix it (the jolt index, section 3, says so instead).+MAX_REPAIRS = 3+# The hair behind a right-facing body, below the head, as fractions of the union box: where a+# ponytail cut at the wrong moment jumps. A left-facing body has it on the other side.+HAIR_BOX_RIGHT = (0.0, 0.30, 0.45, 0.80)+ALPHA_SOLID = 8 # alpha at or above this is body, as everywhere in video-loop+BOX_MARGIN = 8 # px around the union box, the strip cells' own side margin+++def union_box(frames: list[Image.Image]) -> tuple[int, int, int, int]:+ """The body's box over the whole loop, widened by the strip cells' margin (the bottom stays on the feet)."""+ boxes = [f.getchannel("A").point(lambda v: 255 if v >= ALPHA_SOLID else 0).getbbox() for f in frames]+ boxes = [b for b in boxes if b]+ if not boxes:+ raise ValueError("every loop frame is fully transparent")+ return (min(b[0] for b in boxes) - BOX_MARGIN, max(0, min(b[1] for b in boxes) - BOX_MARGIN),+ max(b[2] for b in boxes) + BOX_MARGIN, max(b[3] for b in boxes))+++def hair_box(facing: str) -> tuple[float, float, float, float]:+ x0, y0, x1, y1 = HAIR_BOX_RIGHT+ return (x0, y0, x1, y1) if facing != "left" else (1 - x1, y0, 1 - x0, y1)+++def coverage(frames: list[Image.Image], box: tuple[int, int, int, int]) -> list[np.ndarray]:+ """Alpha 0..1 of every frame inside `box` (outside the frame counts as empty)."""+ return [np.asarray(f.crop(box), dtype=np.float32)[..., 3] / 255.0 for f in frames]+++def steps(alphas: list[np.ndarray], frac: tuple[float, float, float, float] | None = None) -> np.ndarray:+ """Mean coverage change from frame k to k+1, the last to the first at the end; inside `frac`+ (fractions of the box) when given."""+ if frac is not None:+ h, w = alphas[0].shape+ alphas = [a[int(h * frac[1]):int(h * frac[3]), int(w * frac[0]):int(w * frac[2])] for a in alphas]+ n = len(alphas)+ return np.array([float(np.abs(alphas[(k + 1) % n] - alphas[k]).mean()) for k in range(n)])+++def jump_scores(frames: list[Image.Image], *, facing: str = "right", box: tuple[int, int, int, int] | None = None) -> dict[str, Any]:+ """Per step: the whole body's change and the hair's, each over its own median; the score is the larger."""+ al = coverage(frames, box or union_box(frames))+ whole, hair = steps(al), steps(al, hair_box(facing))+ mw, mh = float(np.median(whole)), float(np.median(hair))+ w = whole / mw if mw > 0 else np.zeros_like(whole)+ h = hair / mh if mh > 0 else np.zeros_like(hair)+ return {"whole": w, "hair": h, "score": np.maximum(w, h)}+++def repair_jumps(frames: list[Image.Image], interpolate: Interpolate | None, *, facing: str = "right",+ ratio: float = JUMP_RATIO, max_frames: int = MAX_REPAIRS) -> tuple[list[Image.Image], dict[str, Any]]:+ """Replace the frame that breaks each jump with RIFE's frame between its neighbours, worst jump first.++ At most `max_frames`, and never next to a frame already made: two made frames side by side+ are made from each other and melt the legs. `interpolate` may be None while no jump is+ found; it is asked for only when a frame is to be made (a ValueError says so otherwise).+ Scores are re-read after each replacement, on the union box of the original loop."""+ out = list(frames)+ n = len(out)+ box = union_box(frames)+ first = jump_scores(out, facing=facing, box=box)+ record: dict[str, Any] = {+ "ratio": ratio, "max_frames": max_frames, "facing": facing, "hair_box": list(hair_box(facing)),+ "score_max_before": round(float(first["score"].max()), 4), "replaced": [], "rounds": [],+ }+ if n < 4:+ record.update(stopped="loop shorter than 4 frames", score_max_after=record["score_max_before"])+ return out, record+ replaced: list[int] = []+ stopped = f"{max_frames} frames replaced"+ scores = first+ for _ in range(max_frames):+ k = int(np.argmax(scores["score"]))+ score = float(scores["score"][k])+ if score < ratio:+ stopped = f"no step at or above {ratio}x the median"+ break+ # A jump is a step; the frame to remake is the one that broke it. A cut (the ponytail+ # lands somewhere new and stays) breaks only step k, and the frame after it is remade+ # half way. A single stray frame breaks the step into it and the step out of it: when+ # the step before k is also a jump and larger than the step after k+1, frame k is the+ # stray one, and remaking the frame after it would leave it standing.+ before, after = float(scores["score"][(k - 1) % n]), float(scores["score"][(k + 1) % n])+ j = k if before >= ratio and before > after else (k + 1) % n+ if j in replaced or (j - 1) % n in replaced or (j + 1) % n in replaced:+ stopped = f"the worst jump (frame {j}) sits next to a frame already made"+ break+ if interpolate is None:+ raise ValueError(f"frame {j} follows a jump ({score:.2f}x the median step) and no interpolator is available")+ out[j] = interpolate(out[(j - 1) % n], out[(j + 1) % n], 0.5)+ replaced.append(j)+ record["rounds"].append({"step": [k, (k + 1) % n], "score": round(score, 4), "whole": round(float(scores["whole"][k]), 4),+ "hair": round(float(scores["hair"][k]), 4), "replaced": j})+ scores = jump_scores(out, facing=facing, box=box)+ record["replaced"] = replaced+ record["stopped"] = stopped+ record["score_max_after"] = round(float(scores["score"].max()), 4)+ return out, recorddiff --git a/tests/video/test_auto_motion.py b/tests/video/test_auto_motion.pyindex 56f3a1d..f62da3f 100644--- a/tests/video/test_auto_motion.py+++ b/tests/video/test_auto_motion.py@@ -107,7 +107,7 @@ def test_actual_cli_auto_selects_corrects_and_verifies_animation(tmp_path):for k, image in enumerate(source):image.save(keyed/f'{k:03}.png')output = tmp_path/'out'- args = ['--frames-dir', str(keyed), '--out-dir', str(output), '--state', 'walk', '--anchor', 'motion-auto']+ args = ['--frames-dir', str(keyed), '--out-dir', str(output), '--state', 'walk', '--anchor', 'motion-auto', '--repair', 'off']assert loop.main(args) == 0report = json.loads((output/'loop.loop.report.json').read_text())start, length = report['cycle']['start'], report['cycle']['length']diff --git a/tests/video/test_auto_motion_uncorrected.py b/tests/video/test_auto_motion_uncorrected.pyindex 5a61e79..20296f4 100644--- a/tests/video/test_auto_motion_uncorrected.py+++ b/tests/video/test_auto_motion_uncorrected.py@@ -33,7 +33,7 @@ def write_source(path, **kwargs):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"]+ args = ["--frames-dir", str(keyed), "--out-dir", str(out), "--state", "walk", "--repair", "off"]assert loop.main(args + ["--anchor", "motion-auto"]) == 0summary = json.loads(capsys.readouterr().out)report = json.loads((out / "loop.loop.report.json").read_text())@@ -64,7 +64,7 @@ def test_uncertain_match_does_not_accept_bad_uncorrected_seam(tmp_path, monkeypamonkeypatch.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",+ loop.main(["--frames-dir", str(keyed), "--out-dir", str(out), "--state", "walk", "--repair", "off","--anchor", "motion-auto"])report = json.loads((out / "loop.loop.report.json").read_text())assert report["status"] == "failed" and report["resampled_seam_ratio"] > 2diff --git a/tests/video/test_body_anchor.py b/tests/video/test_body_anchor.pyindex 63e5b40..fabce1b 100644--- a/tests/video/test_body_anchor.py+++ b/tests/video/test_body_anchor.py@@ -63,11 +63,11 @@ def test_run_loop_defaults_to_body_for_gaits_and_none_otherwise(tmp_path: Path):keyed.mkdir()for k, im in enumerate(_cycle(drift=6, n=24) * 3):im.save(keyed / f"frame-{k + 1:04d}.png")- walk = loop.run_loop(keyed, tmp_path / "walk", fps=24.0, state="walk", min_len=None, max_len=None, n_out=None, seam_max=1000.0, name="w", report_path=tmp_path / "w.json", cycle_mode="fixed", start=0, length=24)+ walk = loop.run_loop(keyed, tmp_path / "walk", fps=24.0, state="walk", min_len=None, max_len=None, n_out=None, seam_max=1000.0, name="w", report_path=tmp_path / "w.json", cycle_mode="fixed", start=0, length=24, repair="off")assert walk["strip"]["foot_anchor"] == "body" and walk["strip"]["wrap_dx_px"] in (-6, -5)- idle = loop.run_loop(keyed, tmp_path / "idle", fps=24.0, state="idle", min_len=None, max_len=None, n_out=None, seam_max=1000.0, name="i", report_path=tmp_path / "i.json", cycle_mode="fixed", start=0, length=24)+ idle = loop.run_loop(keyed, tmp_path / "idle", fps=24.0, state="idle", min_len=None, max_len=None, n_out=None, seam_max=1000.0, name="i", report_path=tmp_path / "i.json", cycle_mode="fixed", start=0, length=24, repair="off")assert idle["strip"]["foot_anchor"] == "none" and "wrap_dx_px" not in idle["strip"]- feet = loop.run_loop(keyed, tmp_path / "feet", fps=24.0, state="walk", min_len=None, max_len=None, n_out=None, seam_max=1000.0, name="f", report_path=tmp_path / "f.json", cycle_mode="fixed", start=0, length=24, anchor="feet")+ feet = loop.run_loop(keyed, tmp_path / "feet", fps=24.0, state="walk", min_len=None, max_len=None, n_out=None, seam_max=1000.0, name="f", report_path=tmp_path / "f.json", cycle_mode="fixed", start=0, length=24, anchor="feet", repair="off")assert feet["strip"]["foot_anchor"] == "feet" and "wrap_dx_px" not in feet["strip"]diff --git a/tests/video/test_gait_fallback.py b/tests/video/test_gait_fallback.pyindex c8fd51f..7f52974 100644--- a/tests/video/test_gait_fallback.py+++ b/tests/video/test_gait_fallback.py@@ -51,7 +51,7 @@ def run(tmp_path, frames, *extra):for k, image in enumerate(frames):image.save(keyed/f'{k:03}.png')output = tmp_path/'out'- args = ['--frames-dir', str(keyed), '--out-dir', str(output), '--state', 'walk', '--anchor', 'motion-auto',+ args = ['--frames-dir', str(keyed), '--out-dir', str(output), '--state', 'walk', '--anchor', 'motion-auto', '--repair', 'off','--report', str(tmp_path/'loop.json'), *extra]try:code = loop.main(args)diff --git a/tests/video/test_loop_repair.py b/tests/video/test_loop_repair.pynew file mode 100644index 0000000..45d64c1--- /dev/null+++ b/tests/video/test_loop_repair.py@@ -0,0 +1,160 @@+# SPDX-License-Identifier: Apache-2.0+"""Jump-frame repair (docs/loop-repair.md section 2): only the frame after a jump is replaced,+by the interpolator's frame between its two neighbours; at most three, never two side by side;+the hair watched is behind the body whichever way it faces; and `video-loop` records what it+replaced, gates the cells as they now play, and refuses — naming `--repair off` — when a frame+needs making and no RIFE is installed.++The interpolator is a stand-in that returns the true in-between of the synthetic loop, so the+tests need no binary and can say exactly which frame should come back."""++from __future__ import annotations++import json+import math+from pathlib import Path++import numpy as np+import pytest+from PIL import Image++from sprite_gen.video import loop as loop_mod+from sprite_gen.video import repair++W, H, N = 120, 140, 24+++def _frame(phase: float, *, tail_dx: int = 0, tail_side: str = "left", tail_jump: int = 0) -> Image.Image:+ """A body (static block), a foot going round with the phase, and a 'ponytail' behind it."""+ a = np.zeros((H, W, 4), dtype=np.uint8)+ a[30:100, 50:70] = (90, 90, 200, 255) # torso+ a[10:30, 48:72] = (230, 190, 160, 255) # head+ # a foot going round at an even speed, so every ordinary step changes about as much+ fx, fy = 60 + round(22 * math.cos(phase)), 121 + round(10 * math.sin(phase))+ a[fy - 6:fy + 6, fx - 6:fx + 6] = (60, 60, 60, 255)+ tx = (14 if tail_side == "left" else W - 30) + tail_dx + tail_jump+ a[45:95, tx:tx + 16] = (200, 40, 40, 255) # ponytail, in the hair box behind a right-facing body+ return Image.fromarray(a, "RGBA")+++def _sway(k: int) -> int:+ """The true ponytail sway: one pixel a frame, there and back over the cycle."""+ return min(k % N, N - k % N)+++def _loop(jumps: dict[int, int] | None = None, *, side: str = "left") -> tuple[list[Image.Image], list[Image.Image]]:+ """(frames as filmed, the true loop). The true ponytail sways a little; a jump+ frame puts it `jumps[k]` px off its true place."""+ jumps = jumps or {}+ truth = [_frame(2 * math.pi * k / N, tail_dx=_sway(k), tail_side=side) for k in range(N)]+ filmed = [_frame(2 * math.pi * k / N, tail_dx=_sway(k), tail_side=side,+ tail_jump=jumps.get(k, 0)) for k in range(N)]+ return filmed, truth+++class TrueMiddle:+ """Stand-in interpolator: the true frame between two frames of the synthetic loop."""++ def __init__(self, filmed: list[Image.Image], truth: list[Image.Image]):+ self.index = {id(f): k for k, f in enumerate(filmed)}+ self.truth = truth+ self.calls: list[tuple[int, int, float]] = []++ def __call__(self, a: Image.Image, b: Image.Image, t: float) -> Image.Image:+ ka, kb = self.index[id(a)], self.index[id(b)]+ self.calls.append((ka, kb, t))+ assert (kb - ka) % N == 2 and t == 0.5 # always the two neighbours, half way+ return self.truth[(ka + 1) % N]+++def test_only_the_frame_after_a_jump_is_replaced_by_its_neighbours_middle():+ filmed, truth = _loop({10: 12})+ fake = TrueMiddle(filmed, truth)+ out, record = repair.repair_jumps(filmed, fake)+ assert record["replaced"] == [10]+ assert fake.calls == [(9, 11, 0.5)]+ assert out[10] is truth[10]+ assert all(out[k] is filmed[k] for k in range(N) if k != 10) # every other frame stays the video's own+ assert record["score_max_before"] >= repair.JUMP_RATIO > record["score_max_after"]+ assert record["stopped"].startswith("no step at or above")+++def test_a_smooth_loop_is_left_alone_and_needs_no_interpolator():+ filmed, _ = _loop()+ out, record = repair.repair_jumps(filmed, None)+ assert record["replaced"] == [] and all(a is b for a, b in zip(out, filmed))+++def test_at_most_three_and_never_next_to_a_made_frame():+ filmed, truth = _loop({3: 14, 9: 13, 15: 12, 20: 11})+ out, record = repair.repair_jumps(filmed, TrueMiddle(filmed, truth))+ assert len(record["replaced"]) == 3 and record["stopped"] == "3 frames replaced"+ assert record["replaced"][0] == 3 and set(record["replaced"]) < {3, 9, 15, 20} # worst first, only stray frames++ filmed, truth = _loop({8: 14, 9: 14}) # two jump frames side by side+ out, record = repair.repair_jumps(filmed, TrueMiddle(filmed, truth))+ assert len(record["replaced"]) == 1+ assert "next to a frame already made" in record["stopped"]+++def test_the_hair_watched_is_behind_the_body_whichever_way_it_faces():+ # A small ponytail jump: the whole frame barely notices, the hair box does.+ right_filmed, right_truth = _loop({12: 6}, side="left") # tail on the left = behind a right-facing body+ assert repair.jump_scores(right_filmed, facing="right")["hair"].max() >= repair.JUMP_RATIO+ assert repair.jump_scores(right_filmed, facing="left")["hair"].max() < repair.JUMP_RATIO+ left_filmed, _ = _loop({12: 6}, side="right") # tail on the right = behind a left-facing body+ assert repair.jump_scores(left_filmed, facing="left")["hair"].max() >= repair.JUMP_RATIO+ assert repair.hair_box("left") == (0.55, 0.30, 1.0, 0.80)+++def _keyed(tmp_path: Path, frames: list[Image.Image]) -> Path:+ d = tmp_path / "keyed"+ d.mkdir()+ for k, f in enumerate(frames + frames[:6]): # a little more than one cycle, as a clip is+ f.save(d / f"{k:04d}.png")+ return d+++def _run(tmp_path: Path, keyed: Path, **kw):+ return loop_mod.run_loop(keyed, tmp_path / "out", fps=24.0, state="walk", min_len=None, max_len=None, n_out=None,+ seam_max=1000.0, name="w", report_path=tmp_path / "w.json", cycle_mode="fixed",+ start=0, length=N, anchor="none", **kw)+++def test_video_loop_records_the_repair_and_plays_the_made_frame(tmp_path):+ filmed, truth = _loop({10: 12})+ keyed = _keyed(tmp_path, filmed)+ reopened = [Image.open(p).convert("RGBA") for p in sorted(keyed.glob("*.png"))][:N]+ made = []++ def middle(a, b, t):+ made.append(t)+ return truth[10]++ rep = _run(tmp_path, keyed, interpolate=middle)+ assert rep["jump_repair"]["replaced"] == [10] and rep["jump_repair"]["applied"] is True+ assert rep["jump_repair"]["interpolator"] == {"kind": "injected"}+ assert rep["seam_measurement"] == "rendered-cells"+ on_disk = np.asarray(Image.open(tmp_path / "out" / "cycle" / "frame-010.png"))+ assert np.array_equal(on_disk, np.asarray(truth[10]))+ assert np.array_equal(np.asarray(Image.open(tmp_path / "out" / "cycle" / "frame-009.png")), np.asarray(reopened[9]))+ assert json.loads((tmp_path / "w.json").read_text())["jump_repair"]["replaced"] == [10]+ assert made == [0.5]+++def test_a_jump_without_rife_is_refused_naming_repair_off(tmp_path, monkeypatch):+ monkeypatch.delenv("SPRITE_GEN_RIFE", raising=False)+ monkeypatch.setenv("PATH", str(tmp_path / "empty"))+ filmed, _ = _loop({10: 12})+ keyed = _keyed(tmp_path, filmed)+ with pytest.raises(SystemExit, match=r"--repair off"):+ _run(tmp_path, keyed)+ report = json.loads((tmp_path / "w.json").read_text())+ assert report["status"] == "failed" and "rife-ncnn-vulkan not found" in report["error"]+++def test_repair_off_cuts_as_filmed_and_says_so(tmp_path):+ filmed, _ = _loop({10: 12})+ rep = _run(tmp_path, _keyed(tmp_path, filmed), repair="off")+ assert rep["jump_repair"] == {"applied": False, "why": "--repair off"}+ assert rep["seam_measurement"] == "source-frames"diff --git a/tests/video/test_motion_anchor.py b/tests/video/test_motion_anchor.pyindex a05eeab..fea4370 100644--- a/tests/video/test_motion_anchor.py+++ b/tests/video/test_motion_anchor.py@@ -97,7 +97,7 @@ def test_cli_writes_corrected_cycle_and_gates_rendered_cells(tmp_path, correctedfor k, im in enumerate(source):im.save(keyed / f"{k:03}.png")out = tmp_path / "output"- args = ["--frames-dir", str(keyed), "--out-dir", str(out), "--state", "walk",+ args = ["--frames-dir", str(keyed), "--out-dir", str(out), "--state", "walk", "--repair", "off","--cycle", "fixed", "--start", "0", "--length", "24", "--anchor", "motion","--anchor-region", "55,27,86,60", "--anchor-region", "48,61,94,110"]assert loop.main(args) == 0diff --git a/tests/video/test_video_pipeline.py b/tests/video/test_video_pipeline.pyindex dafecf1..4d839d5 100644--- a/tests/video/test_video_pipeline.py+++ b/tests/video/test_video_pipeline.py@@ -236,7 +236,7 @@ def test_profiles_scale_windows_with_clip_length() -> None:@pytest.mark.skipif(not HAS_IMG2WEBP, reason="img2webp not installed")def test_run_loop_emits_strip_gif_webp_and_verifies(tmp_path: Path) -> None:files = _gait_frames(tmp_path, period=12, n=96)- rep = loop_mod.run_loop(tmp_path / "keyed", tmp_path / "out", fps=24.0, state="walk", min_len=None, max_len=None, n_out=8, seam_max=2.0, name="walker", report_path=None)+ rep = loop_mod.run_loop(tmp_path / "keyed", tmp_path / "out", fps=24.0, state="walk", min_len=None, max_len=None, n_out=8, seam_max=2.0, name="walker", report_path=None, repair="off")# 12 frames at 24 fps is half a second — below the walk gait floor (0.6 s), so the# half-period guard doubles it to the two-step 24 and records that it didassert rep["cycle"]["period_global"] == 24@@ -262,7 +262,7 @@ def test_run_loop_seam_gate_fails_loud_on_noise(tmp_path: Path, monkeypatch) ->arr[..., 3][mask] = 255Image.fromarray(arr, "RGBA").save(d / f"frame-{t:04d}.png")with pytest.raises(SystemExit, match="seam ratio|no periodic cycle"):- loop_mod.run_loop(d, tmp_path / "out", fps=24.0, state="walk", min_len=None, max_len=None, n_out=6, seam_max=2.0, name="noise", report_path=None)+ loop_mod.run_loop(d, tmp_path / "out", fps=24.0, state="walk", min_len=None, max_len=None, n_out=6, seam_max=2.0, name="noise", report_path=None, repair="off")assert not (tmp_path / "out" / "noise.gif").exists()@@ -313,7 +313,7 @@ def test_run_loop_auto_fails_over_to_one_shot_only_for_action_states(tmp_path: P_one_shot_frames(tmp_path)# walk must not repeat once: the gate stays a hard failurewith pytest.raises(SystemExit, match="no periodic cycle"):- loop_mod.run_loop(tmp_path / "keyed", tmp_path / "walk", fps=24.0, state="walk", min_len=None, max_len=None, n_out=8, seam_max=2.0, name="w", report_path=None)+ loop_mod.run_loop(tmp_path / "keyed", tmp_path / "walk", fps=24.0, state="walk", min_len=None, max_len=None, n_out=8, seam_max=2.0, name="w", report_path=None, repair="off")# jump may happen once: recorded failover, periodic attempt kept in the reportrep = loop_mod.run_loop(tmp_path / "keyed", tmp_path / "jump", fps=24.0, state="jump", min_len=None, max_len=None, n_out=8, seam_max=2.0, name="j", report_path=None)assert rep["cycle"]["kind"] == "one-shot" and rep["cycle_mode"] == "auto"@@ -349,9 +349,9 @@ def test_gif_frame_count_follows_cycle_length_at_a_fixed_playback_rate(tmp_path:assert rep["n_out"] == 30 and 80 <= rep["delay_ms"] <= 90(tmp_path / "short").mkdir()_gait_frames(tmp_path / "short", period=26, n=100, stamp=True) # 1.08 s- rep2 = loop_mod.run_loop(tmp_path / "short" / "keyed", tmp_path / "short-out", fps=24.0, state="walk", min_len=None, max_len=None, n_out=None, seam_max=2.0, name="w", report_path=None, gif_fps=12.0)+ rep2 = loop_mod.run_loop(tmp_path / "short" / "keyed", tmp_path / "short-out", fps=24.0, state="walk", min_len=None, max_len=None, n_out=None, seam_max=2.0, name="w", report_path=None, gif_fps=12.0, repair="off")assert 12 <= rep2["n_out"] <= 14 and abs(rep2["delay_ms"] - rep["delay_ms"]) <= 15 # ~1.1 s at 12 fps; the period may resolve to 24-26- explicit = loop_mod.run_loop(tmp_path / "short" / "keyed", tmp_path / "short-out2", fps=24.0, state="walk", min_len=None, max_len=None, n_out=8, seam_max=2.0, name="w8", report_path=None)+ explicit = loop_mod.run_loop(tmp_path / "short" / "keyed", tmp_path / "short-out2", fps=24.0, state="walk", min_len=None, max_len=None, n_out=8, seam_max=2.0, name="w8", report_path=None, repair="off")assert explicit["n_out"] == 8assert rep["n_out"] <= rep["cycle"]["length"] and rep2["n_out"] <= rep2["cycle"]["length"]@@ -382,7 +382,7 @@ def test_fixed_cycle_cuts_exactly_and_skips_detection(tmp_path: Path) -> None:@pytest.mark.skipif(not HAS_IMG2WEBP, reason="img2webp not installed")def test_strip_height_caps_the_output_size(tmp_path: Path) -> None:files = _gait_frames(tmp_path, period=12, n=60, size=(160, 400))- rep = loop_mod.run_loop(tmp_path / "keyed", tmp_path / "h", fps=24.0, state="walk", min_len=None, max_len=None, n_out=None, seam_max=2.0, name="h", report_path=None, strip_height=100)+ rep = loop_mod.run_loop(tmp_path / "keyed", tmp_path / "h", fps=24.0, state="walk", min_len=None, max_len=None, n_out=None, seam_max=2.0, name="h", report_path=None, strip_height=100, repair="off")assert rep["strip"]["h"] <= 100assert Image.open(rep["gif"]["file"] if Path(rep["gif"]["file"]).is_absolute() else tmp_path / "h" / rep["gif"]["file"]).height <= 100@@ -421,14 +421,14 @@ def test_body_height_measures_the_clips_first_frame_not_a_raised_weapon(tmp_pathim.putpixel((36, y), (120, 120, 120, 255))im.save(path)rep = loop_mod.run_loop(tmp_path / "keyed", tmp_path / "out", fps=24.0, state="walk", min_len=None, max_len=None,- n_out=8, seam_max=9.0, name="w", report_path=None, body_height=48)+ n_out=8, seam_max=9.0, name="w", report_path=None, body_height=48, repair="off")meta = json.loads((tmp_path / "out" / "w.strip.json").read_text())assert meta["body_ref"] == "first-frame"assert (meta["body_src_h"], meta["scale"], meta["body_h"]) == (48, 1.0, 48) # the raised frames are 56 tallassert rep["strip"]["body_h"] == 48# without a target nothing changes: the tallest grounded frame, never scaled uploop_mod.run_loop(tmp_path / "keyed", tmp_path / "plain", fps=24.0, state="walk", min_len=None, max_len=None,- n_out=8, seam_max=9.0, name="w", report_path=None)+ n_out=8, seam_max=9.0, name="w", report_path=None, repair="off")plain = json.loads((tmp_path / "plain" / "w.strip.json").read_text())assert plain["body_ref"] == "tallest-grounded" and plain["body_src_h"] == 56