Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
feat(video): automate local cycle selection and XY motion correction
Soohong Kim87f1d387771b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 17cfa03..6e8b851 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,8 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the- 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.+## v2.5.6 - Walk and run loops close their wrap with one ramp- Walk and run loops close their wrap with one ramp. `video-loop --anchor body` (now the default for `walk` and `run`) measures how far the last frame's head and torso sit from the first's, once, by whole-pixel registration over the top of the first frame's box, and shifts frame k by that offset times k/L. It never fits frame by frame: per-frame fitting turns a head bob into a full-body shiver, and the feet anchor pins the planted foot, which a quadruped moves every step. A cycle whose wrap already lands (most bipeds) is left byte-identical; the strip sidecar records `wrap_dx_px` and `seam_ratio_after_anchor`. `--anchor feet` and `--anchor none` are unchanged, and other states keep `none`.diff --git a/docs/loop-review.md b/docs/loop-review.mdindex 7f50f4f..2144617 100644--- a/docs/loop-review.md+++ b/docs/loop-review.md@@ -53,6 +53,46 @@ uncertainty. Keep that decision separate from the unmodified automatic report. Awithout the required visual input must not claim it reviewed the gait. Ambiguous orcontradictory visual evidence should remain unresolved rather than inventing a precise cut.+## Automatic XY correction and local cycle selection++For a fully automatic walk/run candidate, opt into `motion-auto`:++```bash+sprite-gen video-frames --clip clip.mp4 --out-dir frames/ --key auto \+ --spill auto --reference canvas.png --report frames.report.json+sprite-gen video-loop --frames-dir frames/keyed/ --out-dir loop/ \+ --state walk --fps <measured-source-fps> --anchor motion-auto+```++`video-set --states walk,run --anchor motion-auto` uses the same path. Other+states and fixed/manual cuts are rejected before generation. The defaults above+remain unchanged. This mode accepts no supplied regions or frame indices.++The script searches a grid in the upper part of the foreground for two separated,+textured regions. It ranks their normalized cross-correlation across time and+requires both to track throughout the sequence. These are stable image regions,+not semantic detections of a face, torso, species or limb. Untrackable patches are+counted as rejected candidates; absence of a usable pair is an explicit failure.++For selection only, the measured horizontal trajectory is locally fitted and the+vertical linear trend is removed. Local lag minima can then identify a repeat in+a clip with changing drift or cadence. Selection requires repeat depth, active+motion around both boundaries, and a supported doubled recurrence when a short+step falls below the gait floor. Candidate ranking also penalizes drift that a+single 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 selected original frames receive the same integer XY correction described+below, using regions discovered again in the selected interval. Analysis resampling+never enters the emitted cycle. Reports include `automatic_motion_analysis`,+`automatic_motion_regions`, local candidates, the duration guard and every final+translation. The unchanged seam limit measures the actual rendered cells.++Automatic results carry `review_recommended=true`: these measurements cannot+establish limb identity or fix changing drawings. Validate unfamiliar body shapes+and motions visually; no animal-wide quality claim follows from humanoid examples.+## 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.pynew file mode 100644index 0000000..52eb988--- /dev/null+++ b/sprite_gen/video/auto_motion.py@@ -0,0 +1,181 @@+# SPDX-License-Identifier: Apache-2.0+"""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.+"""+from __future__ import annotations++from PIL import Image+from sprite_gen._deps import np+from sprite_gen.video import motion_anchor++ANALYSIS_EDGE = 184+SAMPLE_COUNT = 9+++def _center(a):+ y, x = np.nonzero(a[:, :, 3] > .1)+ if not len(x):+ raise ValueError("automatic motion anchor needs visible foreground in every frame")+ return np.array([x.mean(), y.mean()])+++def _reference(a, box):+ x, y, right, bottom = box+ patch = a[y:bottom, x:right]+ mask = patch[:, :, 3] > .05+ if mask.mean() < .45:+ return None+ z = np.pad(mask, 1)+ mask = np.logical_or.reduce([z[dy:dy+mask.shape[0], dx:dx+mask.shape[1]]+ for dx, dy in ((1, 1), (0, 1), (2, 1), (1, 0), (1, 2))])+ flat = patch[mask]+ centered = flat - flat.mean(axis=0)+ norm = float(np.sqrt((centered * centered).sum()))+ if norm < .5:+ return None+ return box, mask, centered, norm+++def _match(reference, moving, center, radius):+ """Bounded masked NCC; vectorized across translations, never wrap pixels."""+ (x, y, right, bottom), mask, feature, norm = reference+ cx, cy = center+ height, width = mask.shape+ xs, xe = max(0, x-cx-radius), min(moving.shape[1]-width, x-cx+radius)+ ys, ye = max(0, y-cy-radius), min(moving.shape[0]-height, y-cy+radius)+ if xs > xe or ys > ye:+ raise ValueError("automatic motion anchor has no search overlap")+ windows = np.lib.stride_tricks.sliding_window_view(+ moving[ys:ye+height, xs:xe+width], (height, width), axis=(0, 1))+ patches = windows.transpose(0, 1, 3, 4, 2)[:, :, mask, :]+ centered = patches - patches.mean(axis=2, keepdims=True)+ denominator = np.sqrt((centered * centered).sum(axis=(2, 3))) * norm+ costs = 1 - (centered * feature).sum(axis=(2, 3)) / np.maximum(1e-10, denominator)+ iy, ix = np.unravel_index(costs.argmin(), costs.shape)+ dx, dy = x-(xs+int(ix)), y-(ys+int(iy))+ if abs(dx-cx) == radius or abs(dy-cy) == radius:+ raise ValueError("automatic motion anchor match reached search boundary")+ return np.array([dx, dy]), float(costs[iy, ix])+++def discover(frames: list[Image.Image], *, reference_index: int) -> tuple[list, dict]:+ if len(frames) < 6 or any(im.mode != 'RGBA' or im.size != frames[0].size for im in frames):+ raise ValueError("automatic motion anchor needs at least six equally sized RGBA frames")+ width, height = frames[0].size+ # Keep small sprites measurable and bound memory for high resolution input.+ divisor = max(1, int(np.ceil(max(width, height) / ANALYSIS_EDGE)))+ size = (max(1, width // divisor), max(1, height // divisor))+ scale = np.array([width/size[0], height/size[1]])+ arrays = [motion_anchor._features(im.resize(size, Image.Resampling.BOX)) for im in frames]+ centers = [_center(a) for a in arrays]+ a = arrays[reference_index]+ yy, xx = np.nonzero(a[:, :, 3] > .1)+ x0, x1, y0, y1 = int(xx.min()), int(xx.max()+1), int(yy.min()), int(yy.max()+1)+ body_h, body_w = y1-y0, x1-x0+ pw, ph = max(5, round(min(body_w*.5, body_h*.25))), max(5, round(body_h*.20))+ radius = max(8, round(body_h*.16))+ samples = np.unique(np.linspace(0, len(frames)-1, SAMPLE_COUNT).astype(int))+ candidates = []+ rejected = 0+ for fraction in np.linspace(.08, .5, 6):+ y = int(y0+fraction*body_h)+ for x in range(x0, max(x0+1, x1-pw+1), max(2, pw//3)):+ box = (x, y, x+pw, y+ph)+ if box[2] > size[0] or box[3] > size[1]:+ continue+ reference = _reference(a, box)+ if reference is None:+ continue+ positions, errors = [], []+ try:+ for k in samples:+ center = np.rint(centers[reference_index]-centers[k]).astype(int)+ position, error = _match(reference, arrays[k], center, radius)+ positions.append(position)+ errors.append(error)+ except ValueError:+ rejected += 1+ continue # A rejected patch is not used as an alternative motion result.+ smoothness = float(np.abs(np.diff(positions, n=2, axis=0)).mean()/body_h)+ quality = float(np.mean(errors)+.25*np.quantile(errors, .9)+.05*smoothness)+ candidates.append({'box': box, 'quality': quality, 'sample_costs': errors})+ candidates.sort(key=lambda row: (row['quality'], row['box']))+ if not candidates or candidates[0]['quality'] > .8:+ raise ValueError("automatic motion anchor found no stable textured region")+ chosen = []+ validated = []+ for row in candidates:+ if row['quality'] > .8:+ break+ if chosen and abs(row['box'][1]-chosen[0]['box'][1]) < ph*.75:+ continue+ reference = _reference(a, row['box'])+ tracking = []+ try:+ for k, moving in enumerate(arrays):+ center = np.rint(centers[reference_index]-centers[k]).astype(int)+ tracking.append(_match(reference, moving, center, radius))+ except ValueError:+ rejected += 1+ continue+ chosen.append(row)+ validated.append(tracking)+ if len(chosen) == 2:+ break+ if len(chosen) != 2:+ raise ValueError("automatic motion anchor needs two separated regions trackable throughout the clip")+ ordered = sorted(zip(chosen, validated), key=lambda pair: pair[0]['box'][1])+ chosen = [pair[0] for pair in ordered]+ validated = [pair[1] for pair in ordered]+ positions, costs = [], []+ for k in range(len(frames)):+ matches = [tracking[k] for tracking in validated]+ positions.append(sum(w * match[0] for w, match in zip(motion_anchor.REGION_WEIGHTS, matches)))+ costs.append([match[1] for match in matches])+ regions = [tuple(int(round(v * scale[j % 2])) for j, v in enumerate(row['box'])) for row in chosen]+ report = {+ 'method': 'stable-texture-grid-v1', 'reference_index': reference_index,+ 'analysis_size': list(size), 'scale_xy': scale.tolist(), 'regions': [list(b) for b in regions],+ 'region_quality': [r['quality'] for r in chosen], 'candidate_count': len(candidates),+ 'rejected_search_candidates': rejected, 'sample_indices': samples.tolist(),+ 'tracking_xy': (np.asarray(positions)*scale).tolist(), 'tracking_costs': costs,+ 'semantic_labels': False,+ }+ return regions, report+++def analyse(frames: list[Image.Image], *, fps: float) -> tuple[np.ndarray, np.ndarray, dict]:+ _, report = discover(frames, reference_index=len(frames)//2)+ size = tuple(report['analysis_size'])+ scale = np.asarray(report['scale_xy'])+ positions = np.asarray(report['tracking_xy']) / scale+ n = len(frames)+ # Local linear X trend follows slow drift changes; vertical trend is global+ # so the periodic hop/bob remains evidence. These images are NEVER emitted.+ radius = max(3, round(fps/2))+ trajectory = []+ for k in range(n):+ js = np.arange(max(0, k-radius), min(n, k+radius+1))+ trajectory.append(float(np.polyfit(js-k, positions[js, 0], 1)[1]))+ trajectory = np.asarray(trajectory)+ trajectory -= trajectory[n//2]+ dy_slope = float(np.polyfit(np.arange(n), positions[:, 1], 1)[0])+ shifts = np.column_stack((trajectory, dy_slope*(np.arange(n)-n//2)))+ pad = int(np.ceil(np.abs(shifts).max()))+4+ normalized = []+ for im, (dx, dy) in zip(frames, shifts):+ small = im.resize(size, Image.Resampling.BOX)+ canvas = Image.new('RGBA', (size[0]+2*pad, size[1]+2*pad))+ canvas.paste(small, (pad, pad))+ canvas = canvas.transform(canvas.size, Image.Transform.AFFINE,+ (1, 0, -float(dx), 0, 1, -float(dy)), Image.Resampling.BILINEAR)+ normalized.append(motion_anchor._features(canvas).reshape(-1))+ flat = np.stack(normalized)+ distances = np.empty((n, n), dtype=np.float32)+ for k in range(n):+ distances[k] = np.abs(flat-flat[k]).mean(axis=1)+ report['analysis_only_translation_xy'] = (shifts*scale).tolist()+ report['analysis_only'] = True+ return distances, trajectory, reportdiff --git a/sprite_gen/video/batch.py b/sprite_gen/video/batch.pyindex 8402d1f..998def4 100644--- a/sprite_gen/video/batch.py+++ b/sprite_gen/video/batch.py@@ -105,6 +105,8 @@ def run_item(facing_fix: str = "none",prepare_side: Callable[[Path], tuple[Path, dict]] | None = None,) -> dict[str, Any]:+ if anchor == "motion-auto" and not loop_mod.profile_for(state).gait:+ raise SystemExit("video-set: --anchor motion-auto requires walk/run states")if anchor == "motion":raise SystemExit("video-set: motion anchor requires reviewed regions; use video-loop --cycle fixed")validate_facing(facing, facing_fix)@@ -226,6 +228,8 @@ def run_set(facing: str = "right",facing_fix: str = "none",) -> dict[str, Any]:+ 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":raise SystemExit("video-set: motion anchor requires reviewed regions; use video-loop --cycle fixed")validate_facing(facing, facing_fix)@@ -293,7 +297,7 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:parser.add_argument("--concurrency", type=int, default=3, help="parallel clip generations (starts are staggered regardless)")parser.add_argument("--start-gap", type=float, default=START_GAP_SECONDS, help="seconds between clip request starts")parser.add_argument("--shape", choices=canvas_mod.SHAPES, help="force one canvas shape for every state (e.g. wide for a costume or arms that leave a 1:1 frame)")- parser.add_argument("--anchor", choices=tuple(a for a in loop_mod.ANCHOR_MODES if a != "motion"), default="none", help="feet: remove in-canvas drift so every cell stands on the mean foot line")+ parser.add_argument("--anchor", choices=tuple(a for a in loop_mod.ANCHOR_MODES if a != "motion"), default="none", help="motion-auto: automatic regions, local period and XY correction (walk/run only); feet: remove in-canvas drift")parser.add_argument("--spill", choices=frames_mod.SPILL_MODES, default="auto", help="auto: judge key reflections from each item's canvas still (default); small / full: force")parser.add_argument("--force", action="store_true", help="regenerate clips that already exist")diff --git a/sprite_gen/video/local_cycle.py b/sprite_gen/video/local_cycle.pynew file mode 100644index 0000000..505e757--- /dev/null+++ b/sprite_gen/video/local_cycle.py@@ -0,0 +1,85 @@+# SPDX-License-Identifier: Apache-2.0+"""Select an observed local repeat after camera/subject drift analysis.++A changing cadence can contain a good cycle without one period fitting the+whole clip. Require a local lag minimum, repeat depth, motion context, and the+same two-step duration prior; an isolated matching endpoint is insufficient.+"""+from __future__ import annotations+import math+from sprite_gen._deps import np+++def detect(distances, trajectory, *, min_len, max_len, gait_floor,+ periodicity_min, double_tolerance, double_search):+ n = len(distances)+ lo, hi = max(6, min_len), min(max_len, n//2)+ if hi < lo:+ raise ValueError(f"automatic motion cycle window [{lo}, {hi}] has no repeated cycle")+ candidates = []+ for length in range(max(lo, gait_floor), hi+1):+ radius = max(2, length//4)+ for start in range(n-length-radius-1):+ js = np.arange(max(0, start-radius), start+radius+1)+ profile = {}+ for lag in range(max(2, lo//2), hi+2):+ observed = js[js+lag < n]+ if len(observed) >= radius+1:+ profile[lag] = float(distances[observed, observed+lag].mean())+ minima = [lag for lag in profile if lag-1 in profile and lag+1 in profile+ and profile[lag] <= min(profile[lag-1], profile[lag+1]) and lag <= hi]+ if not minima:+ continue+ deepest = min(profile[lag] for lag in minima)+ period = min(lag for lag in minima if profile[lag] <= deepest*1.15+1e-4)+ guard = {'applied': False}+ if period < gait_floor:+ doubles = [lag for lag in minima if abs(lag-2*period) <= double_search and lag >= gait_floor]+ if not doubles:+ continue+ doubled = min(doubles, key=profile.get)+ if profile[doubled] > profile[period]*(1+double_tolerance)+1e-4:+ continue+ guard = {'applied': True, 'from': period, 'to': doubled,+ 'gait_floor': gait_floor, 'reason': 'local-two-step-repeat'}+ period = doubled+ # Allow one frame of cut quantization around the measured local lag.+ if abs(length-period) > 1 or profile.get(length, math.inf) > profile[period]*1.15+1e-4:+ continue+ baseline = float(np.mean(list(profile.values())))+ error = profile[length]+ depth = 1-error/baseline if baseline > 0 else 0+ step = float(np.diag(distances[start:start+length, start:start+length], 1).mean())+ if depth < periodicity_min or step <= 1e-10 or error/step > 2:+ continue+ # A still/rest segment matching another still is not a repeated gait.+ first_motion = float(distances[js[:-1], js[1:]].mean())+ second_motion = float(distances[js[:-1]+length, js[1:]+length].mean())+ if min(first_motion, second_motion) < .25*step:+ continue+ ratio = float(distances[start+length-1, start])/step+ x = np.arange(length)+ segment = trajectory[start:start+length]+ residual = float(np.abs(segment-np.polyval(np.polyfit(x, segment, 1), x)).mean())+ score = error/step + .3*abs(math.log(max(.01, ratio))) + residual+ candidates.append({+ 'start': start, 'length': length, 'period_local': period, 'score': score,+ 'ratio': ratio, 'periodicity': depth, 'context_repeat_over_step': error/step,+ 'context_pair_range': [int(js[0]), int(js[-1])+1],+ 'context_motion_over_step': [first_motion/step, second_motion/step],+ 'drift_line_residual_analysis_px': residual, 'half_period_guard': guard,+ })+ if not candidates:+ raise ValueError("no periodic cycle found — no supported local two-step repeat after drift analysis")+ candidates.sort(key=lambda row: (row['score'], row['start'], row['length']))+ # Equivalent-quality candidates: prefer the earliest demonstrated repeat.+ cutoff = candidates[0]['score']*1.15+1e-8+ chosen = min((r for r in candidates if r['score'] <= cutoff),+ key=lambda row: (row['start'], row['score'], row['length']))+ return {+ **chosen, 'kind': 'periodic', 'method': 'local-repeat-drift-v1',+ 'period_global': None, 'periodicity_min': periodicity_min,+ 'review_recommended': True, 'candidate_count': len(candidates),+ 'best_score': candidates[0]['score'], 'equivalent_score_tolerance': .15,+ 'candidates': candidates[:12],+ }diff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.pyindex 02a82c7..c601914 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+from sprite_gen.video import motion_anchor, auto_motion, local_cycleANALYSIS_SIZE = 96 # thumbnail edge for the distance matrixSTRIP_MAX_CELLS = 64 # upper bound on cells even when they are narrow@@ -70,7 +70,7 @@ ONE_SHOT_MIN_LEN = 4 # a one-shot's length is the clip's own fact; only a degenGAIT_DOUBLE_TOL = 0.25GAIT_DOUBLE_SEARCH = 3 # frames either side of 2x the step where the full gait's own minimum may sitGAIT_NEAR_EXACT_STEP_FRACTION = 0.10 # no ambiguity extension when repeat error is tiny compared with a playback step-ANCHOR_MODES = ("none", "feet", "body", "motion")+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@@ -751,6 +751,9 @@ def run_loop(motion_anchor.validate_request(anchor, cycle_mode, length, anchor_regions)except ValueError as exc:raise SystemExit(f"video-loop: {exc}") from exc+ if anchor == "motion-auto" and (cycle_mode not in ("auto", "periodic") or not profile_for(state).gait+ or start is not None or length is not None):+ raise SystemExit("video-loop: --anchor motion-auto requires walk/run with automatic or periodic selection; no fixed cut")if cycle_mode not in CYCLE_MODES:raise SystemExit(f"video-loop: unknown --cycle {cycle_mode!r}; expected one of {', '.join(CYCLE_MODES)}")frames_dir = frames_dir.expanduser().resolve()@@ -772,11 +775,20 @@ def run_loop("window": [lo, hi], "profile": prof.why, "cycle_mode": cycle_mode,"seam_max": seam_max,"anchor": anchor,- "seam_measurement": "rendered-cells" if anchor == "motion" else "source-frames",+ "seam_measurement": "rendered-cells" if anchor in ("motion", "motion-auto") else "source-frames",}cycle = Nonetry:- if cycle_mode == "fixed":+ if anchor == "motion-auto":+ 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,+ )+ elif cycle_mode == "fixed":if start is None or length is None:raise SystemExit("video-loop: --cycle fixed needs --start and --length")cycle = fixed_cycle(D, start=start, length=length)@@ -802,10 +814,12 @@ def run_loop(f"video-loop: no periodic cycle found — {flat}; the motion does not repeat, widen the window, ""regenerate the clip, or pass --cycle one-shot for a single performed action")- except SystemExit as exc:+ except (SystemExit, ValueError) as exc:write_loop_report(target, {**report_base, "status": "failed", "error": str(exc),"cycle": getattr(exc, "diagnostics", cycle),"periodic_attempt": periodic_attempt})+ if isinstance(exc, ValueError):+ raise SystemExit(f"video-loop: {exc}") from excraisei, L = cycle["start"], cycle["length"]# playback density, not a fixed count: a long cycle gets more frames so every state plays at@@ -821,7 +835,7 @@ def run_loop(for k, f in enumerate(files[i : i + L]):im = Image.open(f).convert("RGBA")# Motion review is pixel preserving: cleanup belongs to the keyed input.- if anchor != "motion":+ if anchor not in ("motion", "motion-auto"):scrubbed += _scrub(im)im, d = _drop_specks(im, SPECK_MIN_FRACTION)specks += d@@ -833,8 +847,11 @@ def run_loop(wrap_dx = body_wrap_offset(frames)frames = ramp_frames(frames, wrap_dx)motion = None- if anchor == "motion":+ if anchor in ("motion", "motion-auto"):try:+ if anchor == "motion-auto":+ anchor_regions, region_report = auto_motion.discover(frames, reference_index=0)+ report_base["automatic_motion_regions"] = region_reportframes, motion = motion_anchor.correct_motion(frames, anchor_regions, coarse_dx=body_wrap_offset(frames, search=motion_anchor.COARSE_SEARCH),)@@ -850,7 +867,7 @@ 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"))if motion is not None:- strip_meta["foot_anchor"] = "motion"+ strip_meta["foot_anchor"] = anchorstrip_meta["motion_anchor"] = motionif anchor == "body":strip_meta["foot_anchor"] = "body"@@ -876,7 +893,7 @@ 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 == "motion":+ if anchor in ("motion", "motion-auto"):# Gate the actual corrected/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())@@ -951,7 +968,7 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:parser.add_argument("--length", type=int, help="fixed cut: cycle length in frames (with --cycle fixed)")parser.add_argument("--strip-height", type=int, default=STRIP_MAX_HEIGHT, help=f"cell/strip/GIF height cap in px (default {STRIP_MAX_HEIGHT}); the cycle is scaled down to fit, and never up unless --body-height asks for it")parser.add_argument("--body-height", type=int, help="scale so the STANDING height (tallest floor-contact frame) 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="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", 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("--name", default="loop", help="basename for strip/gif/webp outputs")parser.add_argument("--report", type=Path)diff --git a/tests/video/test_auto_motion.py b/tests/video/test_auto_motion.pynew file mode 100644index 0000000..471e653--- /dev/null+++ b/tests/video/test_auto_motion.py@@ -0,0 +1,99 @@+"""Automatic postprocessing exercised with known synthetic movement, no private assets."""+import json+import math++import numpy as np+import pytest+from PIL import Image, ImageDraw+from sprite_gen.video import auto_motion, batch, local_cycle, loop+++def walker(k, *, repeat=True):+ im = Image.new('RGBA', (280, 180))+ d = ImageDraw.Draw(im)+ x = 45+k+ y = 18+round(k*.2)+round(3*math.sin(k*2*math.pi/24))+ 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)) if repeat else 0+ 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))+ d.point((x+leg+2, y+85+k%12), fill=(240, 240, 240, 255))+ return im+++def detect(D, trajectory=None, **kwargs):+ return local_cycle.detect(D, np.zeros(len(D)) if trajectory is None else trajectory,+ min_len=12, max_len=36, gait_floor=14,+ periodicity_min=.15, double_tolerance=.25, double_search=3, **kwargs)+++def test_local_repeat_refuses_static_and_single_excursion():+ for values in [np.zeros(80), np.array([10 if 40 <= k <= 44 else 0 for k in range(80)])]:+ D = np.abs(values[:, None]-values[None, :]).astype(np.float32)+ with pytest.raises(ValueError, match='no periodic cycle'):+ detect(D)+++def test_symmetric_steps_keep_two_phase_occurrences_and_respect_window():+ values = np.array([[math.sin(k*2*math.pi/12), math.cos(k*2*math.pi/12)] for k in range(80)])+ D = np.abs(values[:, None]-values[None, :]).mean(axis=2)+ result = detect(D)+ assert result['length'] == 24+ assert result['half_period_guard']['from'] == 12+ assert result['half_period_guard']['to'] == 24+ # A hard ceiling below the doubled recurrence must not be silently widened.+ with pytest.raises(ValueError, match='no periodic cycle'):+ local_cycle.detect(D, np.zeros(80), min_len=12, max_len=18, gait_floor=14,+ periodicity_min=.15, double_tolerance=.25, double_search=3)+++def test_region_discovery_refuses_blank_input():+ with pytest.raises(ValueError, match='visible foreground'):+ auto_motion.discover([Image.new('RGBA', (100, 100)) for _ in range(6)], reference_index=0)+++def test_actual_cli_auto_selects_corrects_and_verifies_animation(tmp_path):+ source = [walker(k) for k in range(73)]+ keyed = tmp_path/'keyed'+ keyed.mkdir()+ 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']+ assert loop.main(args) == 0+ report = json.loads((output/'loop.loop.report.json').read_text())+ start, length = report['cycle']['start'], report['cycle']['length']+ assert length == 24+ assert report['anchor'] == 'motion-auto' and report['seam_measurement'] == 'rendered-cells'+ assert report['automatic_motion_analysis']['analysis_only'] is True+ assert report['automatic_motion_regions']['reference_index'] == 0+ assert report['gif']['n_frames'] == report['webp']['n_frames'] == length+ motion = report['motion_anchor']+ assert abs(motion['endpoint_xy'][0]+23) <= 1+ assert abs(motion['endpoint_xy'][1]+5) <= 1+ left, top, _, _ = motion['padding_ltrb']+ for k, path in enumerate(sorted((output/'cycle').glob('*.png'))):+ image = Image.open(path)+ dx, dy = motion['shifts_xy'][k]+ restored = image.crop((left+dx, top+dy, left+dx+280, top+dy+180))+ np.testing.assert_array_equal(np.asarray(restored), np.asarray(source[start+k]))+ with pytest.raises(SystemExit, match='loop seam ratio'):+ loop.main(args+['--seam-max', '.001'])+ assert json.loads((output/'loop.loop.report.json').read_text())['status'] == 'failed'+++def test_automatic_contract_refuses_manual_inputs_and_non_gaits_before_io(tmp_path):+ args = ['--frames-dir', '/missing', '--out-dir', str(tmp_path), '--anchor', 'motion-auto']+ for extra in [[], ['--state', 'idle'], ['--state', 'walk', '--cycle', 'fixed', '--start', '0', '--length', '24']]:+ with pytest.raises(SystemExit, match='requires walk/run'):+ loop.main(args+extra)+ with pytest.raises(SystemExit, match='requires --anchor motion'):+ loop.main(args+['--state', 'walk', '--anchor-region', '1,2,3,4'])+ with pytest.raises(SystemExit, match='requires walk/run'):+ batch.run_set(bases={}, states=['walk', 'idle'], root=tmp_path/'batch', character=None,+ duration=3, resolution='720p', key='auto', concurrency=1,+ force=False, gap=0, anchor='motion-auto')+ assert not (tmp_path/'batch').exists()diff --git a/tests/video/test_gait_guard_anchor_wide.py b/tests/video/test_gait_guard_anchor_wide.pyindex bdd1e79..0fa0196 100644--- a/tests/video/test_gait_guard_anchor_wide.py+++ b/tests/video/test_gait_guard_anchor_wide.py@@ -195,7 +195,8 @@ def test_raised_limb_states_get_a_wide_canvas() -> None:assert canvas_mod.profile_for("idle").shape == canvas_mod.SHAPE_SQUARE-def test_video_set_passes_shape_and_anchor_through(tmp_path: Path, monkeypatch) -> None:[email protected]("state,anchor", [("cheer", "feet"), ("walk", "motion-auto")])+def test_video_set_passes_shape_and_anchor_through(tmp_path: Path, monkeypatch, state, anchor) -> None:seen: dict[str, object] = {}def fake_canvas(base, out, *, state, shape, facing, headroom, lead, report_path):@@ -227,10 +228,10 @@ def test_video_set_passes_shape_and_anchor_through(tmp_path: Path, monkeypatch)monkeypatch.setattr(batch_mod.loop_mod, "run_loop", fake_loop)base = tmp_path / "base.png"Image.new("RGB", (32, 32), (0, 255, 0)).save(base)- payload = batch_mod.run_set(bases={"side": base}, states=["cheer"], root=tmp_path / "set", character=None, duration=6, resolution="720p", key="green", concurrency=1, force=False, gap=0.0, video_runner=fake_video, shape="wide", anchor="feet")+ payload = batch_mod.run_set(bases={"side": base}, states=[state], root=tmp_path / "set", character=None, duration=6, resolution="720p", key="green", concurrency=1, force=False, gap=0.0, video_runner=fake_video, shape="wide", anchor=anchor)assert payload["ok"] == 1# the frames step is told to judge spill from the item's own canvas still- assert seen == {"shape": "wide", "anchor": "feet", "spill": ("auto", "canvas.png")}+ assert seen == {"shape": "wide", "anchor": anchor, "spill": ("auto", "canvas.png")}def test_cheer_motion_template_names_no_limbs() -> None: