Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
feat(video): one cycle length for a direction set, RIFE only between source frames, starting on a foot strike
Soohong Kim53b1f8f8a362
diff --git a/docs/README.md b/docs/README.mdindex 9c4532e..ee21f5b 100644--- a/docs/README.md+++ b/docs/README.md@@ -16,6 +16,7 @@ flowchart LRdirection LRb1[video-canvas] --> b2[video] --> b3[video-frames] --> b4[video-loop]b5[video-set] -.runs all four.-> b1+ b4 --> b6[video-cycle-align]endsubgraph C["C · utilities"]direction LR@@ -37,7 +38,7 @@ flowchart LR| Pipeline / tool group / workflow | Entry doc | Verbs ||---|---|---|| **A · atlas rows** — one still becomes a runtime sprite sheet | [run-contract.md](run-contract.md) | `prepare` → `gen` / `gen-set` → `extract` → `compose-atlas`; optional `curation` and recompose |-| **B · video → loop** — one still becomes transparent motion loops | [video-pipeline.md](video-pipeline.md) | `video-canvas` → `video` → `video-frames` → `video-loop`, `video-set` |+| **B · video → loop** — one still becomes transparent motion loops | [video-pipeline.md](video-pipeline.md) | `video-canvas` → `video` → `video-frames` → `video-loop`, `video-set`, `video-cycle-align` || **C · utilities** — imported images in, clean cuts out | [sheet-slicing.md](sheet-slicing.md) | `cutout`, `slice-sheet`, `unpack-atlas` || **D · post-processing** — finished sheets, refined | [recolor.md](recolor.md) | `recolor`, `recolor-palette`, `compose-layers`, breathing (compose), `export-pngs`, `export-aseprite` || **E · asset tools** — independent background, shadow and motion tools | [asset-tools.md](asset-tools.md) | `background-tile`, `shadow`, `inspect-motion` |diff --git a/docs/loop-repair.md b/docs/loop-repair.mdindex ecce0b9..01882e8 100644--- a/docs/loop-repair.md+++ b/docs/loop-repair.md@@ -191,6 +191,51 @@ Read:so as a default gate it would refilm about every other Lite walk: the opposite of the aim, onthe strength of two refusals. The bounds stay a reference until more takes are judged.+## 4. One cycle for a direction set — `video-cycle-align`, `video-set --align-cycles auto`++Each direction of a walk is filmed on its own and comes out its own length (one Lite set:+16, 19, 21, 25 and 27 frames). A game that turns a character mid-stride wants every direction the+same number of frames, starting on the same step.++```bash+sprite-gen video-cycle-align --loop-dir set/front-walk/loop --loop-dir set/side-walk/loop \+ --loop-dir set/back-walk/loop [--length N] [--report set/walk.cycle-align.json]+```++- **Length**: the median of the set's own lengths (`--length` overrides). The median is the+ length that needs the fewest made frames across the set; a loop already that long is not+ touched.+- **Resample, offset 0**: frame k of a loop of L frames resampled to L* is the source at time+ k·L/L*, cyclic. A time within 0.03 of a source frame takes that frame as filmed; only a time+ between two frames is made, by RIFE at that fraction (section 1). An offset of half a frame,+ which would remake every frame, is not offered (section 2).+- **Foot strike**: each loop is then turned to start where the body is lowest (its solid top+ line lowest, smoothed 1-2-1) — both feet down just after a heel lands. A walk has two such+ moments; the first is taken.+- **Rebuilt in place**: `cycle/`, `<name>.strip.png` / `.strip.json`, `.gif`, `.webp` are+ rewritten at the loop's own cell rules (`cell_height_cap`, body-height target, anchor), at the+ loop's frame rate, so the aligned cycle lasts L*/fps seconds. `strip.json` gains+ `cycle_align` (`from`, `to`, `taken`, `made_by_rife`, `made_at`, `turned_by`, the seam ratio of+ the rebuilt cells, and the re-verified GIF/WebP).+- **The cut as filmed is kept** in `cycle.source/` on the first alignment, and every later+ alignment reads from there: running it again, or at another length, never resamples a+ resampled loop. Every loop of the set is resampled before any is rewritten, so a loop that+ cannot be made leaves the set as it was.+- Loops at different frame rates are refused (one length in frames would mean different+ durations), and so is a loop cut before `cell_height_cap` was recorded (cut it again).++`video-set` runs this after its loops are cut, once per walk or run state filmed in two or more+directions (`--align-cycles auto`, default; `off` keeps each loop's own length). Its report+carries `cycle_align` per state and `<state>.cycle-align.json`; a failed alignment is listed as+`cycle-align:<state>` and the loops stay as cut.++How much RIFE that is, on the 2026-10-03 sets (the experiment's `finalize.py`): resampling to+the median made 18 of 21 frames for a Lite side loop of 27, 20 of 21 for a back-diagonal loop of+19, and none for the loop already 21 long; Pro, 22 of 24 for a front-diagonal loop of 34. The+final set showed a Lite back-diagonal walk that jumped; seen at three stages (as filmed, jumps+repaired, aligned), it jumped at all three, so the take — not the resampling — was the cause+(maintainer's judgement, 2026-10-03).+## Related- [video-pipeline.md](video-pipeline.md) — the pipeline these repairs run insidediff --git a/docs/video-pipeline.md b/docs/video-pipeline.mdindex 14003b0..26b0220 100644--- a/docs/video-pipeline.md+++ b/docs/video-pipeline.md@@ -495,6 +495,14 @@ are idempotent (an existing clip is reused unless `--force`); one failure stopsits item and is listed in `table.md` with its stage and error. Exit code is non-zerowhen any item failed.+After the loops are cut, every walk or run filmed in two or more directions is given one cycle+length: each loop is resampled to the set's median length (only the frames that fall between two+source frames are made, by RIFE) and turned to start on a foot strike (`--align-cycles auto`, the+default; `off` keeps each loop's own length). The same step stands alone as+`sprite-gen video-cycle-align --loop-dir … --loop-dir …`. `set.report.json` carries `cycle_align`+per state, and a failed alignment is listed as `cycle-align:<state>`. See+[loop repair](loop-repair.md) section 4.+## What the rules were measured onEvery threshold above (the 15 % period tolerance, the 2.0 seam gate, the 0.15diff --git a/sprite_gen/_modules.py b/sprite_gen/_modules.pyindex 2250f0f..b72b23b 100644--- a/sprite_gen/_modules.py+++ b/sprite_gen/_modules.py@@ -25,6 +25,7 @@ MODULE_DOMAIN = {'frames': 'video','loop': 'video','batch': 'video',+ 'align': 'video','prepare': 'gen','extract': 'frames','cutout': 'frames',@@ -85,8 +86,8 @@ DOMAIN_TITLE = dict(DOMAINS)PIPELINES: list[dict[str, object]] = [{"key": "A", "name": "atlas rows", "verbs": ["prepare", "gen", "gen-set", "extract", "compose-atlas", "curation"],"chain": "prepare → gen (or gen-set) → extract → compose-atlas; optional curation and recompose", "doc": "docs/run-contract.md"},- {"key": "B", "name": "video → loop", "verbs": ["video-canvas", "video", "video-frames", "video-loop", "video-set"],- "chain": "video-canvas → video → video-frames → video-loop, or video-set", "doc": "docs/video-pipeline.md"},+ {"key": "B", "name": "video → loop", "verbs": ["video-canvas", "video", "video-frames", "video-loop", "video-set", "video-cycle-align"],+ "chain": "video-canvas → video → video-frames → video-loop, or video-set; video-cycle-align across a set", "doc": "docs/video-pipeline.md"},]TOOL_GROUPS: list[dict[str, object]] = [diff --git a/sprite_gen/cli.py b/sprite_gen/cli.pyindex 9a4367b..31c44b1 100644--- a/sprite_gen/cli.py+++ b/sprite_gen/cli.py@@ -18,6 +18,7 @@ from sprite_gen.video import batch as video_batchfrom sprite_gen.video import canvas as video_canvasfrom sprite_gen.video import frames as video_framesfrom sprite_gen.video import loop as video_loop+from sprite_gen.video import align as video_alignfrom sprite_gen.effects import recolor, shadowfrom sprite_gen.scene import render, inspect_scenefrom sprite_gen.serve import serve_compose, serve_curation@@ -347,6 +348,11 @@ COMMANDS: dict[str, tuple[str, Callable[[argparse.ArgumentParser], None], Callabvideo_batch.add_arguments,video_batch.run,),+ "video-cycle-align": (+ "One cycle length for every direction of a set: resample each loop to the median length (RIFE between source frames only), start on a foot strike.",+ video_align.add_arguments,+ video_align.run,+ ),# The argument surface is `serve_curation.add_arguments` itself, not a copy of it: the# webview's own `--help` and this subcommand are the same declaration, so `sprite-gen# curation` cannot drift from the launch form the READMEs still document.diff --git a/sprite_gen/video/align.py b/sprite_gen/video/align.pynew file mode 100644index 0000000..8190913--- /dev/null+++ b/sprite_gen/video/align.py@@ -0,0 +1,230 @@+# SPDX-License-Identifier: Apache-2.0+"""`sprite-gen video-cycle-align` — one cycle length for every direction of a set.++Each direction of a walk is filmed on its own, so its cycle comes out its own length (a Lite+set measured 16 to 27 frames). A game that turns a character mid-stride wants every direction+to be the same number of frames and to start on the same step. So every loop of the set is+resampled to the set's median length L*: frame k of the new loop is the source loop at time+k·L/L* (cyclic, offset 0), so a time that lands on a source frame takes that frame as filmed+and only the times between two frames are made by RIFE. Then each loop is turned to start where+the body is lowest — a foot just landed. docs/loop-repair.md section 4.++Every frame between two source frames softens a little, so the length is the median (the one+that needs the fewest made frames across the set), and a loop already that long is not touched.++The loop directories are `video-loop` output directories. Their first alignment keeps the cut+as filmed in `cycle.source/`; every later alignment reads from there, so running it again — or+with another length — never resamples a resampled loop.+"""++from __future__ import annotations++import argparse+import json+import shutil+import statistics+from pathlib import Path+from typing import Any++from PIL import Image++from sprite_gen._deps import np+from sprite_gen.spec.runio import atomic_write_text+from sprite_gen.util.gif_utils import save_clean_gif+from sprite_gen.video import loop as loop_mod+from sprite_gen.video import rife as rife_mod++SNAP = 0.03 # a sample time within this of a source frame takes that frame+SOURCE_DIR = "cycle.source"+RATE_TOLERANCE = 0.002 # frame rates read back from the strip metadata agree within this+LOW_ALPHA = 128 # the body's top line for the foot-strike turn: solid pixels only+++def resample(frames: list[Image.Image], length: int, interpolate: rife_mod.Interpolate | None) -> tuple[list[Image.Image], dict[str, Any]]:+ """`frames` as one cycle, resampled to `length` frames at times k·L/length (offset 0)."""+ count = len(frames)+ if length < 2:+ raise ValueError(f"cycle length {length} is too short")+ out: list[Image.Image] = []+ made_at: list[int] = []+ for k in range(length):+ t = k * count / length+ i = int(np.floor(t))+ frac = t - i+ if frac < SNAP:+ out.append(frames[i % count])+ elif frac > 1 - SNAP:+ out.append(frames[(i + 1) % count])+ else:+ if interpolate is None:+ raise ValueError(f"frame {k} of {length} falls between source frames and no interpolator is available")+ out.append(interpolate(frames[i % count], frames[(i + 1) % count], frac))+ made_at.append(k)+ return out, {"from": count, "to": length, "taken": length - len(made_at), "made_by_rife": len(made_at), "made_at": made_at}+++def foot_strike_start(frames: list[Image.Image]) -> int:+ """The frame where the body is lowest — its top line lowest, both feet down just after a heel+ lands — smoothed over its neighbours (1-2-1). A walk has two such moments a cycle; the first+ is taken."""+ tops = []+ for f in frames:+ box = f.getchannel("A").point(lambda v: 255 if v >= LOW_ALPHA else 0).getbbox()+ if box is None:+ raise ValueError("a loop frame has no solid body")+ tops.append(box[1])+ n = len(tops)+ smooth = [(tops[(k - 1) % n] + 2 * tops[k] + tops[(k + 1) % n]) / 4 for k in range(n)]+ return max(range(n), key=lambda k: smooth[k])+++def _loop_files(loop_dir: Path) -> tuple[Path, dict[str, Any]]:+ metas = sorted(loop_dir.glob("*.strip.json"))+ if len(metas) != 1:+ raise ValueError(f"{loop_dir}: expected one <name>.strip.json from video-loop, found {len(metas)}")+ meta = json.loads(metas[0].read_text(encoding="utf-8"))+ for key in ("cycle_frames", "cycle_seconds", "cell_height_cap", "kind"):+ if key not in meta:+ raise ValueError(f"{metas[0]}: no `{key}` — cut the loop again with this sprite-gen (video-loop) before aligning it")+ return metas[0], meta+++def _source_frames(loop_dir: Path) -> list[Image.Image]:+ """The cut as filmed: `cycle.source/` once an alignment has run, `cycle/` before (kept there first)."""+ source = loop_dir / SOURCE_DIR+ if not source.is_dir():+ cycle = loop_dir / "cycle"+ if not any(cycle.glob("frame-*.png")):+ raise ValueError(f"{loop_dir}: no cycle/frame-*.png")+ staging = loop_dir / f".{SOURCE_DIR}.tmp"+ shutil.rmtree(staging, ignore_errors=True)+ shutil.copytree(cycle, staging)+ staging.rename(source)+ files = sorted(source.glob("frame-*.png"))+ if not files:+ raise ValueError(f"{source}: no frame-*.png")+ return [Image.open(f).convert("RGBA") for f in files]+++def _rebuild(loop_dir: Path, meta_path: Path, meta: dict[str, Any], frames: list[Image.Image], fps: float,+ record: dict[str, Any]) -> dict[str, Any]:+ """Write the aligned cycle, strip, GIF and WebP over the loop's own, at the loop's own cell size rules."""+ name = meta_path.name[: -len(".strip.json")]+ cycle_dir = loop_dir / "cycle"+ cycle_dir.mkdir(exist_ok=True)+ for old in cycle_dir.glob("frame-*.png"):+ old.unlink()+ for k, im in enumerate(frames):+ im.save(cycle_dir / f"frame-{k:03d}.png")+ cycle_seconds = len(frames) / fps+ standing = meta.get("body_src_h") if meta.get("body_ref") == "first-frame" else None+ strip, strip_meta = loop_mod.build_strip(+ frames, max_height=int(meta["cell_height_cap"]), cycle_seconds=cycle_seconds, body_height=meta.get("body_height_target"),+ anchor="feet" if meta.get("foot_anchor") == "feet" else "none", kind=str(meta["kind"]), standing_src=standing)+ # what build_strip does not own (how the cut was anchored) is carried over as it was+ merged = {**{k: v for k, v in meta.items() if k not in strip_meta and k != "cycle_align"}, **strip_meta}+ if meta.get("foot_anchor") and meta.get("foot_anchor") != "feet":+ merged["foot_anchor"] = meta["foot_anchor"]+ cells = [strip.crop((k * strip_meta["w"], 0, (k + 1) * strip_meta["w"], strip_meta["h"])) for k in range(strip_meta["frames"])]+ flat = np.stack([loop_mod._small_features(c) for c in cells])+ adjacent = float(np.abs(flat[1:] - flat[:-1]).mean())+ seam = float(np.abs(flat[-1] - flat[0]).mean())+ record["seam_ratio"] = round(seam / adjacent, 4) if adjacent > 0 else None+ merged["cycle_align"] = record+ strip.save(loop_dir / f"{name}.strip.png")+ atomic_write_text(meta_path, json.dumps(merged, indent=2) + "\n")+ delay_ms = max(20, round(1000 * cycle_seconds / len(cells)))+ gif_path, webp_path = loop_dir / f"{name}.gif", loop_dir / f"{name}.webp"+ save_clean_gif(cells, gif_path, duration_ms=delay_ms, loop=0, alpha_threshold=128)+ loop_mod.write_webp(cells, webp_path, delay_ms=delay_ms, workdir=loop_dir / ".webp-frames")+ shutil.rmtree(loop_dir / ".webp-frames", ignore_errors=True)+ record["gif"] = loop_mod.verify_animation(gif_path, expect_frames=len(cells), check_stale=False)+ record["webp"] = loop_mod.verify_animation(webp_path, expect_frames=len(cells), check_stale=True)+ return merged+++def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate: rife_mod.Interpolate | None = None,+ report_path: Path | None = None) -> dict[str, Any]:+ """Resample every loop of a set to one length (default: the median), turned to a foot strike."""+ if len(loop_dirs) < 1:+ raise SystemExit("video-cycle-align: at least one --loop-dir")+ loops = []+ for d in loop_dirs:+ d = d.expanduser().resolve()+ try:+ meta_path, meta = _loop_files(d)+ except ValueError as exc:+ raise SystemExit(f"video-cycle-align: {exc}") from exc+ loops.append((d, meta_path, meta, meta["cycle_frames"] / meta["cycle_seconds"]))+ # cycle_seconds is written to four decimals, so a rate read back from it carries that rounding+ rates = [fps for *_, fps in loops]+ if max(rates) / min(rates) - 1 > RATE_TOLERANCE:+ raise SystemExit(f"video-cycle-align: the loops play at different frame rates ({sorted(round(r, 3) for r in rates)}); "+ "one length in frames means nothing across them")+ fps = round(statistics.median(rates), 3)+ sources = []+ for d, *_ in loops:+ try:+ sources.append(_source_frames(d))+ except ValueError as exc:+ raise SystemExit(f"video-cycle-align: {exc}") from exc+ lengths = [len(f) for f in sources]+ target = length if length is not None else round(statistics.median(lengths))+ located: list[dict[str, str]] = []++ def lazy(a: Image.Image, b: Image.Image, t: float) -> Image.Image:+ nonlocal interpolate+ if interpolate is None:+ found = rife_mod.Rife()+ located.append(found.describe())+ interpolate = found+ return interpolate(a, b, t)++ # Every loop is resampled before any is rewritten: a loop that cannot be made leaves the set as it was.+ aligned = []+ for (d, *_), frames in zip(loops, sources):+ try:+ out, facts = resample(frames, target, lazy)+ start = foot_strike_start(out)+ except (ValueError, rife_mod.RifeUnavailable) as exc:+ raise SystemExit(f"video-cycle-align: {d}: {exc}; frames between source frames are made by RIFE (docs/loop-repair.md)") from exc+ record = {**facts, "turned_by": start, "fps": round(fps, 4), "source": SOURCE_DIR,+ "made_at": [(k - start) % target for k in facts["made_at"]]}+ aligned.append((out[start:] + out[:start], record))+ rows = []+ for (d, meta_path, meta, _), (out, record) in zip(loops, aligned):+ merged = _rebuild(d, meta_path, meta, out, fps, record)+ rows.append({"dir": str(d), "name": meta_path.name[: -len(".strip.json")], **{k: v for k, v in record.items() if k not in ("gif", "webp")},+ "strip": {k: merged[k] for k in ("frames", "w", "h", "body_h", "delay_ms")}})+ report = {"kind": "sprite-gen-video-cycle-align-report", "length": target, "length_rule": "requested" if length is not None else "median",+ "lengths": lengths, "fps": round(fps, 4), "cycle_seconds": round(target / fps, 4),+ "interpolator": ({"kind": "rife-ncnn-vulkan", **located[0]} if located else+ {"kind": "injected"} if any(r["made_by_rife"] for r in rows) else None),+ "made_by_rife": sum(r["made_by_rife"] for r in rows), "loops": rows}+ if report_path is not None:+ loop_mod.write_loop_report(report_path.expanduser().resolve(), report)+ return report+++def add_arguments(parser: argparse.ArgumentParser) -> None:+ parser.add_argument("--loop-dir", action="append", type=Path, required=True, help="a video-loop output directory (repeat once per direction of the set)")+ parser.add_argument("--length", type=int, help="cycle length in frames for every loop (default: the median of the set's own lengths)")+ parser.add_argument("--report", type=Path, help="where to write the set's alignment report (JSON)")+++def run(**kwargs: object) -> int:+ report = align_set(list(kwargs["loop_dir"]), length=kwargs.get("length"), report_path=kwargs.get("report")) # type: ignore[arg-type]+ print(json.dumps({k: report[k] for k in ("length", "lengths", "made_by_rife", "cycle_seconds")}+ | {"loops": [{k: r[k] for k in ("name", "from", "to", "made_by_rife", "turned_by", "seam_ratio")} for r in report["loops"]]},+ ensure_ascii=False, indent=2))+ return 0+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(prog="sprite-gen video-cycle-align", description=__doc__)+ add_arguments(parser)+ return run(**vars(parser.parse_args(argv)))+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/sprite_gen/video/batch.py b/sprite_gen/video/batch.pyindex aeddec3..13d64e2 100644--- a/sprite_gen/video/batch.py+++ b/sprite_gen/video/batch.py@@ -28,6 +28,7 @@ from sprite_gen.video import facing as facing_modfrom sprite_gen.video import canvas as canvas_modfrom sprite_gen.video import frames as frames_modfrom sprite_gen.video import loop as loop_mod+from sprite_gen.video import align as align_modSTART_GAP_SECONDS = 2.0# Clip length the batch asks the video model for. 3 s holds two or more cycles of every@@ -406,6 +407,37 @@ def run_item(return result+ALIGN_MODES = ("auto", "off")+++def align_gaits(results: list[dict[str, Any]], root: Path, mode: str, *, interpolate: Any = None) -> dict[str, Any]:+ """One cycle length per gait state across the set's directions (`video-cycle-align`,+ docs/loop-repair.md section 4). A state filmed in fewer than two directions has nothing to+ match. A failure is recorded under its state and the batch reports it; the loops stay as cut."""+ out: dict[str, Any] = {}+ if mode == "off":+ return out+ by_state: dict[str, list[dict[str, Any]]] = {}+ for r in results:+ if r.get("ok") and loop_mod.profile_for(r["state"]).gait:+ by_state.setdefault(r["state"], []).append(r)+ for state, rows in by_state.items():+ if len(rows) < 2:+ continue+ try:+ report = align_mod.align_set([Path(r["dir"]) / "loop" for r in rows], interpolate=interpolate,+ report_path=root / f"{state}.cycle-align.json")+ except SystemExit as exc:+ out[state] = {"ok": False, "error": str(exc)}+ continue+ out[state] = {"ok": True, "length": report["length"], "lengths": report["lengths"], "made_by_rife": report["made_by_rife"],+ "report": str(root / f"{state}.cycle-align.json")}+ for r, row in zip(rows, report["loops"]):+ r["loop"]["cycle_align"] = {k: row[k] for k in ("from", "to", "made_by_rife", "turned_by", "seam_ratio")}+ r["loop"]["n_out"] = row["strip"]["frames"]+ return out++def write_table(results: list[dict[str, Any]], path: Path) -> str:lines = ["| direction | state | kind | cycle | period | seam | frames | status |", "|---|---|---|---|---|---|---|---|"]for r in results:@@ -443,7 +475,11 @@ def run_set(body_height: int | None = None,fit: str = "state",decontam: str = "off",+ align_cycles: str = "auto",+ interpolate: Any = None,) -> dict[str, Any]:+ if align_cycles not in ALIGN_MODES:+ raise SystemExit(f"video-set: --align-cycles must be one of {', '.join(ALIGN_MODES)}")if anchor == "motion-auto" and any(not loop_mod.profile_for(state).gait for state in states):raise SystemExit("video-set: --anchor motion-auto requires walk/run states")if anchor == "motion":@@ -480,8 +516,10 @@ def run_set(results.append(r)print(json.dumps({k: r[k] for k in ("item", "ok") if k in r} | ({"error": r["error"]} if not r.get("ok") else {"seam": r["loop"]["seam_ratio"]}), ensure_ascii=False), flush=True)results.sort(key=lambda r: [i for i, _, _ in items].index(r["item"]))+ aligned = align_gaits(results, root, align_cycles, interpolate=interpolate)table = write_table(results, root / "table.md")- payload = {"kind": "sprite-gen-video-set-report", "root": str(root), "states": states, "facing": facing, "facing_fix": facing_fix, "directions": list(bases), "body_height": body_height, "ok": sum(1 for r in results if r.get("ok")), "failed": [r["item"] for r in results if not r.get("ok")], "items": results}+ failed = [r["item"] for r in results if not r.get("ok")] + [f"cycle-align:{st}" for st, a in aligned.items() if not a.get("ok")]+ payload = {"kind": "sprite-gen-video-set-report", "root": str(root), "states": states, "facing": facing, "facing_fix": facing_fix, "directions": list(bases), "body_height": body_height, "ok": sum(1 for r in results if r.get("ok")), "failed": failed, "items": results, "cycle_align": aligned}atomic_write_text(root / "set.report.json", json.dumps(payload, ensure_ascii=False, indent=2) + "\n")print(table)return payload@@ -520,6 +558,7 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:parser.add_argument("--fit", choices=canvas_mod.FITS, default="state", help="state: each state's room for the motion (default); tight: no room, the subject fills the frame and a motion that leaves it is clipped (use with --body-height at a low --resolution)")parser.add_argument("--body-height", type=int, default=None, help="scale every state's loop so the standing height is this many px (video-loop --body-height): one value for the whole set keeps the character the same size across states")parser.add_argument("--decontam", choices=frames_mod.DECONTAM_MODES, default="off", help="passed to video-frames: palette re-explains key-tinted edges with the subject's own colours (default off)")+ parser.add_argument("--align-cycles", choices=ALIGN_MODES, default="auto", help="auto (default): after the loops are cut, every walk/run filmed in two or more directions is resampled to the set's median cycle length and turned to start on a foot strike (video-cycle-align; RIFE makes only the frames between source frames); off: each loop keeps its own length")parser.add_argument("--force", action="store_true", help="regenerate clips that already exist")@@ -533,7 +572,7 @@ def run(**kwargs: object) -> int:facing=str(kwargs.get("facing") or "right"), facing_fix=str(kwargs.get("facing_fix") or "none"),shape=(str(kwargs["shape"]) if kwargs.get("shape") else None), anchor=str(kwargs.get("anchor") or "none"), spill=str(kwargs.get("spill") or "auto"),body_height=(int(kwargs["body_height"]) if kwargs.get("body_height") else None), fit=str(kwargs.get("fit") or "state"),- decontam=str(kwargs.get("decontam") or "off"),+ decontam=str(kwargs.get("decontam") or "off"), align_cycles=str(kwargs.get("align_cycles") or "auto"),)return 0 if not payload["failed"] else 1diff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.pyindex 88aebcb..3a5b98f 100644--- a/sprite_gen/video/loop.py+++ b/sprite_gen/video/loop.py@@ -684,6 +684,7 @@ def build_strip(frames: list[Image.Image], *, max_cells: int = STRIP_MAX_CELLS,"subsampled": L > cap,"cell_cap": cap,"top_margin_px": top,+ "cell_height_cap": max_height, # --strip-height: what a rebuild of these cells (video-cycle-align) scales against"body_height_target": body_height,"foot_anchor": anchor, # "none" | "feet" — how the cells were aligned"drift_px": drift_px, # source px of slow in-canvas drift removed across the cycle (0 when not measured)diff --git a/tests/video/test_cycle_align.py b/tests/video/test_cycle_align.pynew file mode 100644index 0000000..5023f79--- /dev/null+++ b/tests/video/test_cycle_align.py@@ -0,0 +1,138 @@+# SPDX-License-Identifier: Apache-2.0+"""One cycle length per set (docs/loop-repair.md section 4): every loop resampled to the median+length at times k·L/L*, a time on a source frame keeping that frame as filmed and only the times+between frames made by the interpolator; each loop turned to start where the body is lowest; the+cut as filmed kept in `cycle.source/`, so a second alignment reads the source, not its own output.++The interpolator is a stand-in that records what it was asked for and cross-fades."""++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 align+from sprite_gen.video import loop as loop_mod++W, H = 100, 120+++def _walker(phase: float) -> Image.Image:+ """A body that bobs with the phase (lowest at phase 0) and a foot going round."""+ a = np.zeros((H, W, 4), dtype=np.uint8)+ bob = round(4 * (1 + math.cos(2 * phase)) / 2) # two lows a cycle, as a walk has+ a[20 + bob:90, 40:60] = (90, 90, 200, 255)+ fx, fy = 50 + round(20 * math.cos(phase)), 104 + round(8 * math.sin(phase))+ a[fy - 5:fy + 5, fx - 5:fx + 5] = (60, 60, 60, 255)+ return Image.fromarray(a, "RGBA")+++class Recorder:+ def __init__(self):+ self.calls: list[float] = []++ def __call__(self, a: Image.Image, b: Image.Image, t: float) -> Image.Image:+ self.calls.append(round(t, 4))+ return Image.blend(a, b, t) # a frame of its own, never a copy of a neighbour+++def test_resample_keeps_every_frame_that_lands_on_a_source_frame():+ frames = [_walker(2 * math.pi * k / 6) for k in range(6)]+ rec = Recorder()+ out, facts = align.resample(frames, 12, rec)+ assert facts == {"from": 6, "to": 12, "taken": 6, "made_by_rife": 6, "made_at": [1, 3, 5, 7, 9, 11]}+ assert all(out[2 * k] is frames[k] for k in range(6)) and rec.calls == [0.5] * 6+ same, facts = align.resample(frames, 6, None) # already that long: untouched, nothing made+ assert facts["made_by_rife"] == 0 and all(a is b for a, b in zip(same, frames))+ with pytest.raises(ValueError, match="no interpolator"):+ align.resample(frames, 9, None)+++def test_the_loop_starts_where_the_body_is_lowest():+ frames = [_walker(2 * math.pi * k / 12) for k in range(12)]+ turned = frames[5:] + frames[:5]+ start = align.foot_strike_start(turned)+ assert turned[start] is frames[0] or turned[start] is frames[6] # the two lows of the bob+++def _cut(tmp_path: Path, name: str, length: int) -> Path:+ keyed = tmp_path / f"{name}-keyed"+ keyed.mkdir()+ for k in range(length + 6):+ _walker(2 * math.pi * k / length).save(keyed / f"{k:04d}.png")+ out = tmp_path / name+ loop_mod.run_loop(keyed, out, fps=24.0, state="walk", min_len=None, max_len=None, n_out=None, seam_max=1000.0,+ name="walk", report_path=None, cycle_mode="fixed", start=0, length=length, anchor="none", repair="off")+ return out+++def test_a_set_is_aligned_to_its_median_length_and_a_second_run_reads_the_source(tmp_path):+ dirs = [_cut(tmp_path, n, L) for n, L in (("S", 20), ("E", 24), ("N", 28))]+ rec = Recorder()+ report = align.align_set(dirs, interpolate=rec, report_path=tmp_path / "align.json")+ assert report["length"] == 24 and report["lengths"] == [20, 24, 28] and report["length_rule"] == "median"+ by = {Path(r["dir"]).name: r for r in report["loops"]}+ assert by["E"]["made_by_rife"] == 0 and by["E"]["taken"] == 24+ assert by["S"]["made_by_rife"] > 0 and by["N"]["made_by_rife"] > 0+ assert report["made_by_rife"] == len(rec.calls) == by["S"]["made_by_rife"] + by["N"]["made_by_rife"]+ for d in dirs:+ meta = json.loads((d / "walk.strip.json").read_text())+ assert meta["frames"] == 24 and meta["cycle_frames"] == 24 and meta["cycle_align"]["to"] == 24+ assert meta["cycle_seconds"] == pytest.approx(1.0)+ assert len(list((d / "cycle").glob("frame-*.png"))) == 24+ assert Image.open(d / "walk.gif").n_frames == 24+ assert (d / align.SOURCE_DIR).is_dir()+ lowest = align.foot_strike_start([Image.open(p).convert("RGBA") for p in sorted((d / "cycle").glob("frame-*.png"))])+ assert lowest == 0+ assert len(list((dirs[0] / align.SOURCE_DIR).glob("frame-*.png"))) == 20+ first = (dirs[0] / "walk.strip.png").read_bytes()+ again = align.align_set(dirs, interpolate=Recorder())+ assert again["lengths"] == [20, 24, 28] # read from cycle.source, not the aligned cycle+ assert (dirs[0] / "walk.strip.png").read_bytes() == first+ assert json.loads((tmp_path / "align.json").read_text())["kind"] == "sprite-gen-video-cycle-align-report"+++def test_loops_at_different_frame_rates_are_refused(tmp_path):+ a, b = _cut(tmp_path, "A", 20), _cut(tmp_path, "B", 24)+ meta = json.loads((b / "walk.strip.json").read_text())+ meta["cycle_seconds"] = 24 / 30+ (b / "walk.strip.json").write_text(json.dumps(meta))+ with pytest.raises(SystemExit, match="different frame rates"):+ align.align_set([a, b], interpolate=Recorder())+++def test_a_loop_cut_before_the_cell_cap_was_recorded_is_refused_by_name(tmp_path):+ d = _cut(tmp_path, "A", 20)+ meta = json.loads((d / "walk.strip.json").read_text())+ del meta["cell_height_cap"]+ (d / "walk.strip.json").write_text(json.dumps(meta))+ with pytest.raises(SystemExit, match="cell_height_cap"):+ align.align_set([d], interpolate=Recorder())+++def test_video_set_aligns_each_gait_filmed_in_two_or_more_directions(tmp_path):+ from sprite_gen.video import batch++ rows = []+ for direction, length in (("front", 20), ("side", 24), ("back", 28)):+ item = tmp_path / f"{direction}-walk"+ item.mkdir()+ _cut(item, "loop", length)+ rows.append({"item": f"{direction}-walk", "direction": direction, "state": "walk", "dir": str(item), "ok": True,+ "loop": {"n_out": length}})+ lone = tmp_path / "side-run"+ lone.mkdir()+ _cut(lone, "loop", 18)+ rows.append({"item": "side-run", "direction": "side", "state": "run", "dir": str(lone), "ok": True, "loop": {"n_out": 18}})+ out = batch.align_gaits(rows, tmp_path, "auto", interpolate=Recorder())+ assert set(out) == {"walk"} # a run in one direction has nothing to match+ assert out["walk"]["ok"] and out["walk"]["length"] == 24 and out["walk"]["lengths"] == [20, 24, 28]+ assert [r["loop"]["n_out"] for r in rows[:3]] == [24, 24, 24] and rows[3]["loop"]["n_out"] == 18+ assert rows[0]["loop"]["cycle_align"]["from"] == 20+ assert (tmp_path / "walk.cycle-align.json").is_file()+ assert batch.align_gaits(rows, tmp_path, "off") == {}