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 with no cycle found is searched again, scaled back and with a longer window
Soohong Kimcc3bacce3ba3
diff --git a/docs/loop-review.md b/docs/loop-review.mdindex fd44f37..cd224d6 100644--- a/docs/loop-review.md+++ b/docs/loop-review.md@@ -88,7 +88,39 @@ motion around both boundaries, and a supported doubled recurrence when a shortstep falls below the gait floor. Candidate ranking also penalizes drift that asingle linear correction could not remove. Among scores within 15% of the best,the earliest repeat is used; exact cut quantization may differ by one frame from-the lag minimum. The requested length window is never widened.+the lag minimum. An explicit `--max-len` is never widened; without one, only the gait+fallback below looks past the state's window, and only after this search found nothing.++### The gait fallback: a slow walk, or a walk toward the camera++When the local search finds no cycle, `motion-auto` looks once more, for two things a+front or back gait does that the first search cannot see past:++- **It walked toward the camera, or away from it.** Asked to walk in place, a front walk+ sometimes comes closer, and the body grows through the clip, so the same pose never matches+ itself in size. A straight-line fit of the subject's opaque height measures it; at 3 % or+ more over the clip (`SCALE_DRIFT_MIN`) every frame is scaled back to the first frame's fitted+ height about its fitted foot point, premultiplied so the soft edge keeps its colour. The+ search, the cells and the seam gate then all read the scaled-back frames. On the walk clips+ we have kept, the median change is 0.5 % and nine in ten stay under 2.7 %.+- **It walked slowly.** A calm walk in long clothing can take longer than half the clip per+ cycle, the most the first search confirms (a 3 s clip at 24 fps: 36 frames). The second+ search allows up to 60 % of the clip and at most 2 s (`LONG_CYCLE_FRACTION`,+ `LONG_CYCLE_SECONDS`; 43 frames for that clip), so a cycle is still seen once whole and+ repeating for the rest.++Every other gate is the same, the seam limit included. A clip the first search cuts is cut+exactly as before. The report records the first search's reason, the measured drift, whether+it was undone and the window (`gait_fallback`); if the second search fails too, the error+keeps its `no periodic cycle found` start and says what was tried. The scaled-back frames are+written to `<out-dir>/.gait-fallback-frames` and removed once the strip is built or the run+fails.++Measured on six stored 3 s front walks that had failed with `no periodic cycle found`: four+loop now. A long kimono, which hides the legs, walked a 38 to 39 frame cycle (one clip also+grew 3.9 %, two grew 11 % and 16 %), and a front horse walk grew 6.4 % with a 42 frame cycle.+Of the other two, one still shows no repeat and one finds a 38 frame candidate that the seam+gate refuses (2.81).The selected original frames receive the same integer XY correction describedbelow, using regions discovered again in the selected interval. Analysis resamplingdiff --git a/sprite_gen/video/gait_fallback.py b/sprite_gen/video/gait_fallback.pynew file mode 100644index 0000000..f49b9d3--- /dev/null+++ b/sprite_gen/video/gait_fallback.py@@ -0,0 +1,99 @@+# SPDX-License-Identifier: Apache-2.0+"""A second look for a walk or run cycle when the automatic search finds none.++Two things a front or back gait does that the first search cannot see past:++* It walks toward the camera (or away from it) although it was asked to stay in place, so the+ body grows or shrinks through the clip and the same pose never matches itself in size. A+ linear trend in the subject's height measures that; the frames are scaled back to the first+ frame's size about the subject's foot point, which stays where it was filmed. Horizontal and+ vertical drift are left to the motion analysis, which already measures them.+* It walks slowly. A calm walk in long clothing can take longer than half the clip per cycle,+ the most the first search confirms. The second search allows a cycle up to+ `LONG_CYCLE_FRACTION` of the clip: it is still seen once whole and repeating for the rest.++Only a failed search reaches this, so a clip that loops today is cut exactly as before. What+was done is recorded in the report (`gait_fallback`).+"""+from __future__ import annotations++from pathlib import Path++from PIL import Image++from sprite_gen._deps import np++# Height change over the clip, from the fitted trend, at which the frames are scaled back.+# Nine in ten walk clips stay under it (median 0.5 %): their change is a head bob and hair.+SCALE_DRIFT_MIN = 0.03+# The longest cycle the second search accepts, as a share of the clip and in seconds.+LONG_CYCLE_FRACTION = 0.6+LONG_CYCLE_SECONDS = 2.0+# Opaque enough to be the subject (the keyed frames' soft edge is below it).+ALPHA_SUBJECT = 128+++def subject_boxes(frames: list[Image.Image]) -> np.ndarray:+ """Per frame: left, top, right, bottom of the opaque subject. A frame with none is NaN."""+ boxes = []+ for frame in frames:+ alpha = np.asarray(frame.getchannel("A")) >= ALPHA_SUBJECT+ ys, xs = np.nonzero(alpha)+ boxes.append((xs.min(), ys.min(), xs.max() + 1, ys.max() + 1) if len(xs) else (np.nan,) * 4)+ return np.asarray(boxes, dtype=np.float64)+++def _trend(values: np.ndarray) -> np.ndarray:+ t = np.arange(len(values), dtype=np.float64)+ known = ~np.isnan(values)+ if known.sum() < 2:+ return np.full(len(values), np.nanmean(values) if known.any() else np.nan)+ return np.polyval(np.polyfit(t[known], values[known], 1), t)+++def scale_drift(frames: list[Image.Image]) -> dict:+ """The fitted height of the subject over the clip and where its feet stand."""+ boxes = subject_boxes(frames)+ height = _trend(boxes[:, 3] - boxes[:, 1])+ foot_x = _trend((boxes[:, 0] + boxes[:, 2]) / 2)+ foot_y = _trend(boxes[:, 3])+ first, last = float(height[0]), float(height[-1])+ drift = last / first - 1 if first > 0 else 0.0+ return {"height_first_px": round(first, 2), "height_last_px": round(last, 2), "drift": round(drift, 4),+ "height": height, "foot_x": foot_x, "foot_y": foot_y}+++def undo_scale(frames: list[Image.Image], measured: dict) -> list[Image.Image]:+ """Each frame scaled to the first frame's fitted height about its fitted foot point.++ Premultiplied while it is resampled, so the soft edge does not pick up the colour that+ sits under fully transparent pixels.+ """+ height, foot_x, foot_y = measured["height"], measured["foot_x"], measured["foot_y"]+ out = []+ for k, frame in enumerate(frames):+ s = float(height[0] / height[k])+ ax, ay = float(foot_x[k]), float(foot_y[k])+ # Output (x, y) reads input anchor + (x - anchor) / s.+ inverse = (1 / s, 0.0, ax * (1 - 1 / s), 0.0, 1 / s, ay * (1 - 1 / s))+ resampled = frame.convert("RGBa").transform(frame.size, Image.Transform.AFFINE, inverse,+ resample=Image.Resampling.BICUBIC)+ out.append(resampled.convert("RGBA"))+ return out+++def long_window(lo: int, n: int, fps: float) -> int:+ """The second search's ceiling in frames."""+ return max(lo + 2, min(round(LONG_CYCLE_SECONDS * fps), int(n * LONG_CYCLE_FRACTION)))+++def write_frames(frames: list[Image.Image], names: list[str], work_dir: Path) -> list[Path]:+ work_dir.mkdir(parents=True, exist_ok=True)+ for old in work_dir.glob("*.png"):+ old.unlink()+ paths = []+ for name, frame in zip(names, frames):+ path = work_dir / name+ frame.save(path)+ paths.append(path)+ return pathsdiff --git a/sprite_gen/video/local_cycle.py b/sprite_gen/video/local_cycle.pyindex 505e757..9656572 100644--- a/sprite_gen/video/local_cycle.py+++ b/sprite_gen/video/local_cycle.py@@ -11,9 +11,10 @@ from sprite_gen._deps import npdef detect(distances, trajectory, *, min_len, max_len, gait_floor,- periodicity_min, double_tolerance, double_search):+ periodicity_min, double_tolerance, double_search, max_fraction=.5):n = len(distances)- lo, hi = max(6, min_len), min(max_len, n//2)+ # A cycle has to be seen repeating: half the clip by default, more for the gait fallback.+ lo, hi = max(6, min_len), min(max_len, int(n*max_fraction))if hi < lo:raise ValueError(f"automatic motion cycle window [{lo}, {hi}] has no repeated cycle")candidates = []diff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.pyindex f98d84e..1a508eb 100644--- a/sprite_gen/video/loop.py+++ b/sprite_gen/video/loop.py@@ -39,7 +39,7 @@ from PIL import Imagefrom sprite_gen._deps import npfrom sprite_gen.spec.runio import atomic_write_textfrom sprite_gen.util.gif_utils import save_clean_gif-from sprite_gen.video import motion_anchor, auto_motion, local_cycle+from sprite_gen.video import motion_anchor, auto_motion, local_cycle, gait_fallbackANALYSIS_SIZE = 96 # thumbnail edge for the distance matrixSTRIP_MAX_CELLS = 64 # upper bound on cells even when they are narrow@@ -48,6 +48,8 @@ STRIP_MAX_HEIGHT = 520SEAM_RATIO_MAX = 2.0 # loop seam / mean adjacent distance inside the cycleSPECK_MIN_FRACTION = 0.01 # detached components smaller than this fraction of the body are keying specksPERIODICITY_MIN = 0.15 # the period must dip at least 15% below the profile mean (flat profile = no repeat)+# Where the gait fallback writes the frames it scaled back (removed once the strip is built).+FALLBACK_FRAMES_DIR = ".gait-fallback-frames"GIF_FPS_DEFAULT = 24.0 # GIF/WebP playback density = the source rate: every cycle frame is kept, a fast action never looks slow (12 made a jump read sluggish, 2026-09-09)GIF_FRAMES_MIN = 4ONE_SHOT_MIN_CONTRAST = 3.0 # one-shot: the excursion peak must stand this far above the rest-pose noise (in MADs)@@ -830,11 +832,33 @@ def run_loop(source_frames = [Image.open(f).convert("RGBA") for f in files]D, trajectory, analysis = auto_motion.analyse(source_frames, fps=fps)report_base["automatic_motion_analysis"] = analysis- cycle = local_cycle.detect(- D, trajectory, min_len=lo, max_len=hi, gait_floor=round(prof.min_seconds*fps),- periodicity_min=PERIODICITY_MIN, double_tolerance=GAIT_DOUBLE_TOL,- double_search=GAIT_DOUBLE_SEARCH,- )+ detect = dict(gait_floor=round(prof.min_seconds*fps), periodicity_min=PERIODICITY_MIN,+ double_tolerance=GAIT_DOUBLE_TOL, double_search=GAIT_DOUBLE_SEARCH)+ try:+ cycle = local_cycle.detect(D, trajectory, min_len=lo, max_len=hi, **detect)+ except ValueError as first:+ # A front or back gait that walked toward the camera, or a slow one: one more+ # search, recorded (`gait_fallback`), and only after the first found nothing.+ drift = gait_fallback.scale_drift(source_frames)+ fallback = {"reason": str(first), "scale_drift": {k: drift[k] for k in ("height_first_px", "height_last_px", "drift")},+ "scale_drift_min": gait_fallback.SCALE_DRIFT_MIN, "scale_undone": False}+ if abs(drift["drift"]) >= gait_fallback.SCALE_DRIFT_MIN:+ source_frames = gait_fallback.undo_scale(source_frames, drift)+ files = gait_fallback.write_frames(source_frames, [f.name for f in files], out_dir.expanduser().resolve() / FALLBACK_FRAMES_DIR)+ D, trajectory, analysis = auto_motion.analyse(source_frames, fps=fps)+ report_base["automatic_motion_analysis"] = analysis+ fallback["scale_undone"] = True+ # An explicit --max-len is the caller's ceiling and stays one.+ hi_long = gait_fallback.long_window(lo, n, fps) if max_len is None else hi+ fallback["window"] = [lo, hi_long]+ report_base["gait_fallback"] = fallback+ try:+ cycle = local_cycle.detect(D, trajectory, min_len=lo, max_len=hi_long,+ max_fraction=gait_fallback.LONG_CYCLE_FRACTION if max_len is None else .5,+ **detect)+ except ValueError as second:+ raise ValueError(f"{second} (also with the gait fallback: window [{lo}, {hi_long}], "+ f"scale drift {drift['drift']:+.1%}{', undone' if fallback['scale_undone'] else ''})") from firstelif cycle_mode == "fixed":if start is None or length is None:raise SystemExit("video-loop: --cycle fixed needs --start and --length")@@ -864,6 +888,7 @@ def run_loop("regenerate the clip, or pass --cycle one-shot for a single performed action")except (SystemExit, ValueError) as exc:+ shutil.rmtree(out_dir.expanduser().resolve() / FALLBACK_FRAMES_DIR, ignore_errors=True)write_loop_report(target, {**report_base, "status": "failed", "error": str(exc),"cycle": getattr(exc, "diagnostics", cycle),"periodic_attempt": periodic_attempt})@@ -907,6 +932,7 @@ def run_loop()except ValueError as exc:error = f"video-loop: {exc}"+ 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 excreport_base["motion_anchor"] = motion@@ -917,6 +943,8 @@ def run_loop(im.save(cycle_dir / f"frame-{k:03d}.png")strip, strip_meta = build_strip(frames, max_height=strip_height, cycle_seconds=cycle_seconds, body_height=body_height, anchor="feet" if anchor == "feet" else "none", kind=str(cycle.get("kind") or "periodic"),standing_src=first_frame_height(files[0]) if body_height is not None else None)+ # The scaled-back frames are read for the last time above; the cycle cells keep them.+ shutil.rmtree(out_dir / FALLBACK_FRAMES_DIR, ignore_errors=True)if motion is not None:strip_meta["foot_anchor"] = anchorstrip_meta["motion_anchor"] = motiondiff --git a/tests/video/test_gait_fallback.py b/tests/video/test_gait_fallback.pynew file mode 100644index 0000000..c8fd51f--- /dev/null+++ b/tests/video/test_gait_fallback.py@@ -0,0 +1,132 @@+"""The gait fallback: a slow walk and a walk toward the camera, on synthetic frames."""+import json+import math++import numpy as np+import pytest+from PIL import Image, ImageDraw+from sprite_gen.video import gait_fallback, loop++FOOT = (140, 170)+++SS = 4 # drawn this many times larger and scaled down, so a slow swing moves by sub-pixels+++def walker(k, *, period=24, grow=0.0, frames=73):+ """A front walker standing on FOOT, legs swinging with `period` frames, `grow` bigger by the end."""+ big = Image.new('RGBA', (280*SS, 180*SS))+ d = ImageDraw.Draw(big)+ phase = k*2*math.pi/period++ def box(x0, y0, x1, y1, fill):+ d.rectangle(tuple(round(v*SS) for v in (x0, y0, x1, y1)), fill=fill)++ # No head bob: the analysis fits one vertical slope over the clip, and a bob that does not+ # complete whole cycles in it tilts that slope.+ x, y = FOOT[0]-15, FOOT[1]-120+ box(x, y, x+28, y+30, (210, 150, 60, 255))+ box(x+20, y+8, x+24, y+12, (10, 30, 50, 255))+ box(x-3, y+32, x+30, y+78, (20, 90, 180, 255))+ box(x+10, y+35, x+15, y+73, (210, 190, 40, 255))+ lift = 10*math.sin(phase)+ # Two legs that do not look alike, so half a cycle is not a cycle.+ box(x-2, y+79+max(0, lift), x+10, FOOT[1]-1-max(0, lift)/2, (240, 200, 40, 255))+ box(x+24, y+79+max(0, -lift), x+29, FOOT[1]-1-max(0, -lift)/2, (30, 60, 90, 255))+ # A mark that moves every frame and comes back each cycle: no two neighbours are identical,+ # which the GIF writer would merge.+ box(x+3, y+38+12*(k % period)/period, x+5, y+40+12*(k % period)/period, (240, 240, 240, 255))+ im = big.convert('RGBa').resize((280, 180), Image.Resampling.BOX).convert('RGBA')+ if not grow:+ return im+ s = 1+grow*k/(frames-1)+ ax, ay = FOOT+ return im.convert('RGBa').transform(im.size, Image.Transform.AFFINE, (1/s, 0, ax*(1-1/s), 0, 1/s, ay*(1-1/s)),+ resample=Image.Resampling.BICUBIC).convert('RGBA')+++def run(tmp_path, frames, *extra):+ keyed = tmp_path/'keyed'+ keyed.mkdir()+ 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',+ '--report', str(tmp_path/'loop.json'), *extra]+ try:+ code = loop.main(args)+ except SystemExit as exc:+ code = exc+ return code, json.loads((tmp_path/'loop.json').read_text()), output+++def test_drift_is_measured_on_the_fitted_height_and_undone_about_the_feet():+ frames = [walker(k, grow=0.2) for k in range(73)]+ measured = gait_fallback.scale_drift(frames)+ assert 0.17 < measured['drift'] < 0.23+ undone = gait_fallback.undo_scale(frames, measured)+ boxes = gait_fallback.subject_boxes(undone)+ # Back to the walker's own height in every frame, its bob included.+ still = gait_fallback.subject_boxes([walker(k) for k in range(73)])+ assert np.all(np.abs((boxes[:, 3]-boxes[:, 1])-(still[:, 3]-still[:, 1])) <= 2)+ # The feet stay where they were filmed.+ assert np.all(np.abs(boxes[:, 3]-FOOT[1]) <= 2)+ # Nothing to undo on a walker that stays its size.+ assert abs(gait_fallback.scale_drift([walker(k) for k in range(73)])['drift']) < 0.02+++def test_a_clip_the_first_search_cuts_is_cut_without_the_fallback(tmp_path):+ code, report, output = run(tmp_path, [walker(k) for k in range(73)])+ assert code == 0+ assert report['cycle']['length'] == 24+ assert 'gait_fallback' not in report+ assert not (output/loop.FALLBACK_FRAMES_DIR).exists()+++def test_a_cycle_longer_than_half_the_clip_is_found_by_the_fallback(tmp_path):+ frames = [walker(k, period=40) for k in range(73)]+ code, report, output = run(tmp_path, frames)+ assert code == 0+ assert abs(report['cycle']['length']-40) <= 1+ fallback = report['gait_fallback']+ assert 'no periodic cycle found' in fallback['reason']+ assert fallback['scale_undone'] is False+ assert fallback['window'] == [12, gait_fallback.long_window(12, 73, 24.0)]+ assert not (output/loop.FALLBACK_FRAMES_DIR).exists()+++def test_an_explicit_max_len_stays_the_ceiling(tmp_path):+ code, report, _ = run(tmp_path, [walker(k, period=40) for k in range(73)], '--max-len', '36')+ assert str(code).startswith('video-loop: no periodic cycle found')+ assert report['gait_fallback']['window'] == [12, 36]+++def test_a_walk_toward_the_camera_is_scaled_back_before_the_second_search(tmp_path):+ frames = [walker(k, grow=0.2) for k in range(73)]+ code, report, output = run(tmp_path, frames)+ assert code == 0+ assert abs(report['cycle']['length']-24) <= 1+ fallback = report['gait_fallback']+ assert fallback['scale_undone'] is True+ assert fallback['scale_drift']['drift'] > gait_fallback.SCALE_DRIFT_MIN+ # The cells are the scaled-back frames: the strip's standing height does not grow.+ cells = sorted((output/'cycle').glob('frame-*.png'))+ heights = gait_fallback.subject_boxes([Image.open(p).convert('RGBA') for p in cells])+ heights = heights[:, 3]-heights[:, 1]+ # Filmed, the cycle grows by about 6 %; scaled back, it keeps the walker's own bob only.+ assert np.ptp(heights) <= 6+ assert not (output/loop.FALLBACK_FRAMES_DIR).exists()+++def test_no_cycle_in_either_search_says_so_and_keeps_the_gate_line(tmp_path):+ frames = [walker(0) for _ in range(73)]+ code, report, output = run(tmp_path, frames)+ assert str(code).startswith('video-loop: no periodic cycle found')+ assert 'also with the gait fallback' in str(code)+ assert report['status'] == 'failed' and report['gait_fallback']['scale_undone'] is False+ assert not (output/loop.FALLBACK_FRAMES_DIR).exists()++[email protected]('n, fps, expected', [(73, 24.0, 43), (145, 24.0, 48), (37, 24.0, 22)])+def test_the_long_window_is_bounded_by_the_clip_and_by_seconds(n, fps, expected):+ assert gait_fallback.long_window(12, n, fps) == expected