Skip to content

Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.

video-loop: generalize beyond the biped measurement set

Soohong Kim2781435b4afc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6a58a26..70737de 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,9 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the
- Added the `sprite_gen/video` domain: `sprite-gen video-canvas` (state canvas — tall for jumps, wide for attacks, square otherwise; the still's corner key fills the padding), `sprite-gen video-frames` (ffmpeg extraction + cutout keying with an edge-contact gate), `sprite-gen video-loop` (global-period cycle detection, strip with `body_h` metadata, 1-bit-alpha GIF, `img2webp -exact` WebP, seam and periodicity gates, output re-verification) and `sprite-gen video-set` (directions × states with staggered starts and a bounded HTTP 429 retry, per-item reports and a table).
- Declared `ffmpeg` and `img2webp` as required binaries for the video pipeline; `docs/video-pipeline.md` records the contract and the rules behind it. A new domain plus new required binaries is why this is a major version.
+- `video-loop --cycle auto|periodic|one-shot`: action states (`jump`, `attack`, unknown) whose clip performs the action once now get a recorded one-shot cut (rest → excursion → rest, medoid rest pose, 3-MAD excursion) instead of a hard failure; the report keeps the rejected periodic attempt and `table.md` gains a `kind` column. `walk`, `run`, `idle` still fail loud without a period.
+- Walk detection window floor 10 % → 6 % of the clip so a legless body's fast bounce resolves; the 15 % depth rule keeps rejecting the one-step half period (verified on a biped and a quadruped).
+- `video-set` motion templates no longer assume a biped ("this body type" instead of knees/arms).
- Slimmed `SKILL.md` into a route-first hub (still / atlas / video-to-loop / utilities) under the 24 KB skill budget; the interpreter rationale, the rename gate and the breathing contract moved verbatim to `docs/interpreter.md`, `docs/rename-gate.md` and `docs/breathing.md`.
## v1.61.0 - Image to Video
diff --git a/SKILL.md b/SKILL.md
index 1445df2..2fa5729 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -183,7 +183,7 @@ $SPRITE_GEN_ROOT/.venv/bin/sprite-gen video-set \
--character "<subject phrase>"
```
-Per item: `video-canvas` (the still padded into the state's canvas — the API ignores `aspect_ratio`, the input frame decides) → `video` (in-place, evenly paced, returns-to-start prompt) → `video-frames` (ffmpeg + cutout keying; edge contact fails loud) → `video-loop` (global period first, then best seam; strip + `body_h` meta, 1-bit GIF, `img2webp -exact` WebP, seam gate). Starts are staggered for the 2 req/s team quota, a 429 retries once or twice, every item reports and `table.md` lists failures by name. Render strips at 24 fps (one cell per frame). Contract and the measurements behind each rule: [`docs/video-pipeline.md`](docs/video-pipeline.md).
+Per item: `video-canvas` (the still padded into the state's canvas — the API ignores `aspect_ratio`, the input frame decides) → `video` (in-place, evenly paced, returns-to-start prompt) → `video-frames` (ffmpeg + cutout keying; edge contact fails loud) → `video-loop` (global period first, then best seam; for `jump`/`attack` a clip that performs the action once gets a recorded one-shot cut, `cycle.kind` in the report; strip + `body_h` meta, 1-bit GIF, `img2webp -exact` WebP, seam gate). Starts are staggered for the 2 req/s team quota, a 429 retries once or twice, every item reports and `table.md` lists failures by name. Render strips at 24 fps (one cell per frame). Contract and the measurements behind each rule: [`docs/video-pipeline.md`](docs/video-pipeline.md).
## SSoT
diff --git a/docs/video-pipeline.md b/docs/video-pipeline.md
index 42acd75..81121a9 100644
--- a/docs/video-pipeline.md
+++ b/docs/video-pipeline.md
@@ -49,7 +49,9 @@ Unchanged from [video.md](video.md): the user's own credential, fail-loud, `ftyp
mp4. For loops, prompt for **in-place, evenly paced, returns-to-start** motion on a flat
chroma fill ("walks in place on a treadmill", "hop … return to the exact starting
stance … same height every time"). `video-set` carries those templates
-(`MOTION_TEXT` / `VIEW_TEXT`).
+(`MOTION_TEXT` / `VIEW_TEXT`). They describe the gait "for this body type" and never
+name limbs — the first drafts said "bipedal … knees … arms pumping", which prompted a
+quadruped and a legless blob into a contradiction (2026-09-09).
## 3. Frames — extract, key, check the edges
@@ -76,13 +78,32 @@ was 17). `video-loop` therefore:
Windows come from the state profile (`STATE_PROFILES`, fractions of the clip length):
idle 60–95 % (breathing is slow and not periodic — the lowest seam is a long window,
-and idle is exempt from the periodicity gate), walk 10–31 %, run 7–23 %, jump/attack
-11–45 %. `--min-len/--max-len` override.
+and idle is exempt from the periodicity gate), walk 6–31 %, run 7–23 %, jump/attack
+11–45 %. `--min-len/--max-len` override. The walk floor is low on purpose: a legless
+body "walks" as a fast bounce (about 13 frames at 24 fps) while a gait is 24–28, and it
+is the 15 % depth rule — not the window — that rejects the one-step half period (on a
+biped and a quadruped the half period dipped only 55–70 % as deep as the full one).
Gates, all fail-loud: no period (profile flat, `periodicity < 0.15`), loop seam ratio
above `--seam-max` (2.0), GIF/WebP re-opened and checked (frame count, `loop=0`,
transparent corners, no RGB under alpha 0 in the WebP).
+### One-shot actions — `--cycle auto|periodic|one-shot`
+
+A video model asked to jump "over and over" sometimes jumps once and stands for the
+rest of the clip. That is not a period, and the periodicity gate says so. For states
+that *are* single actions by nature (`jump`, `attack`, unknown states; never `walk`,
+`run`, `idle`) `auto` then runs a second, different detector instead of failing: the
+**rest pose** is the medoid frame (smallest mean distance to all others), frames whose
+distance to it rises more than 3 MADs above the rest noise are the excursion, and the
+longest such run padded by 2 rest frames on each side is the cycle — so the seam is
+rest → rest by construction. The failover is explicit and recorded, not silent: the
+report carries `cycle.kind = "one-shot"` plus `periodic_attempt` (the periodicity that
+failed and the window), `table.md` has a `kind` column, and the same seam and
+animation gates still apply. `--cycle periodic` keeps the old hard failure; `--cycle
+one-shot` forces the excursion cut. A clip that never leaves its rest pose fails loud
+in both detectors.
+
Outputs:
- `cycle/frame-NNN.png` — the cycle frames, RGB under alpha 0 scrubbed, detached specks
@@ -113,6 +134,12 @@ when any item failed.
Every threshold above (the 15 % period tolerance, the 2.0 seam gate, the 0.15
periodicity floor, the state windows, the tall/wide canvas rooms, the 2 s stagger) was
-set on one hand-run set of 15 loops (3 directions × 5 states) on 2026-09-08 and every
-loop of that set passed the gates as written. The set itself is operator data and is
-not in this repository; the synthetic fixtures under `tests/video/` pin the same rules.
+set on one hand-run set of 15 loops (3 directions × 5 states, one SD biped) on
+2026-09-08 and every loop of that set passed the gates as written. On 2026-09-09 the
+same rules were run against two deliberately different bodies — a quadruped and a
+legless blob, generated for the test — with idle, walk and jump each. Two rules turned
+out to be *that biped's* rules and were generalized: the walk window floor (the blob's
+bounce was faster than any gait) and the assumption that an action state repeats (the
+quadruped jumped once). Everything else held unchanged, and the original biped set
+still resolves to the same periods afterwards. The subjects are not in this repository;
+the synthetic fixtures under `tests/video/` pin every rule named here.
diff --git a/sprite_gen/video/batch.py b/sprite_gen/video/batch.py
index b24c087..224ade6 100644
--- a/sprite_gen/video/batch.py
+++ b/sprite_gen/video/batch.py
@@ -35,10 +35,10 @@ VIEW_TEXT = {
"back": "seen from directly behind, facing away from the viewer",
}
MOTION_TEXT = {
- "idle": "stands in place in a relaxed idle: slow gentle breathing, a subtle weight sway, one natural eye blink. Feet never move.",
- "walk": "walks in place on a treadmill: a steady, natural walk cycle for this body type, limbs alternating with clear ground contacts, the rest of the body following naturally.",
- "run": "runs in place on a treadmill: a fast, energetic run cycle for this body type, clear alternating strides with a bounding rhythm.",
- "jump": "performs a modest vertical hop in place over and over: crouch, spring up about half the body height, land softly, return to the exact starting stance, repeat at an even rhythm. Same height every time.",
+ "idle": "holds a relaxed idle in place: slow gentle breathing, a subtle weight sway, one natural blink if the face has eyes. The ground contact never slides.",
+ "walk": "moves in place on a treadmill: a steady locomotion cycle for this body type with clear repeating ground contacts and an even left-right or front-back rhythm the body already has.",
+ "run": "moves in place on a treadmill: a fast locomotion cycle for this body type with a bounding rhythm and clear repeating ground contacts.",
+ "jump": "performs a modest vertical hop in place over and over: compress, spring up about half the body height, land softly, return to the exact starting stance, repeat at an even rhythm. Same height every time.",
"attack": "performs the same melee attack over and over: one clean strike in front, then returns to the exact ready stance, repeating at an even rhythm.",
}
COMMON_TEXT = (
@@ -122,7 +122,7 @@ def run_item(
fr = frames_mod.run_frames(clip, item_dir / "frames", key=key, allow_edge_contact=False, report_path=item_dir / "frames.report.json")
result["frames"] = {k: fr[k] for k in ("fps", "frames", "alpha_zero_pct_min", "alpha_zero_pct_max")}
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")
- result["loop"] = {"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"], "gif": lp["gif"]["file"], "webp": lp["webp"]["file"], "strip": lp["strip"]["path"]}
+ 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"], "gif": lp["gif"]["file"], "webp": lp["webp"]["file"], "strip": lp["strip"]["path"]}
result["ok"] = True
except SystemExit as exc:
result["ok"] = False
@@ -131,13 +131,13 @@ def run_item(
def write_table(results: list[dict[str, Any]], path: Path) -> str:
- lines = ["| direction | state | cycle | period | seam | frames | status |", "|---|---|---|---|---|---|---|"]
+ lines = ["| direction | state | kind | cycle | period | seam | frames | status |", "|---|---|---|---|---|---|---|---|"]
for r in results:
if r.get("ok"):
lp = r["loop"]
- lines.append(f"| {r['direction']} | {r['state']} | {lp['cycle']} | {lp['period']} | {lp['seam_ratio']:.2f} | {lp['n_out']} | OK |")
+ lines.append(f"| {r['direction']} | {r['state']} | {lp.get('kind', 'periodic')} | {lp['cycle']} | {lp['period'] if lp['period'] is not None else '-'} | {lp['seam_ratio']:.2f} | {lp['n_out']} | OK |")
else:
- lines.append(f"| {r['direction']} | {r['state']} | - | - | - | - | FAIL: {r.get('error', '')[:80]} |")
+ lines.append(f"| {r['direction']} | {r['state']} | - | - | - | - | - | FAIL: {r.get('error', '')[:80]} |")
text = "\n".join(lines) + "\n"
atomic_write_text(path, text)
return text
diff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.py
index ce8b17c..78be7df 100644
--- a/sprite_gen/video/loop.py
+++ b/sprite_gen/video/loop.py
@@ -44,6 +44,9 @@ STRIP_MAX_HEIGHT = 520
SEAM_RATIO_MAX = 2.0 # loop seam / mean adjacent distance inside the cycle
SPECK_MIN_FRACTION = 0.01 # detached components smaller than this fraction of the body are keying specks
PERIODICITY_MIN = 0.15 # the period must dip at least 15% below the profile mean (flat profile = no repeat)
+ONE_SHOT_MIN_CONTRAST = 3.0 # one-shot: the excursion peak must stand this far above the rest-pose noise (in MADs)
+ONE_SHOT_PAD = 2 # one-shot: rest frames kept on each side of the excursion so the seam is rest -> rest
+CYCLE_MODES = ("auto", "periodic", "one-shot")
@dataclass(frozen=True)
@@ -53,16 +56,17 @@ class LoopProfile:
n_out: int # frames in the resampled GIF/WebP
why: str
periodic: bool = True # gate: the profile must show a real period (idle is exempt)
+ one_shot_ok: bool = False # the state is an action that may legitimately happen once (jump, attack) -> one-shot detector may take over
# State -> detection window. Fractions of the clip length so 6 s and 10 s clips both work.
STATE_PROFILES: dict[str, LoopProfile] = {
"idle": LoopProfile(0.60, 0.95, 16, "breathing is slow and not strictly periodic; the lowest seam is a long window", periodic=False),
- "walk": LoopProfile(0.10, 0.31, 12, "full gait = two steps; window excludes the one-step half period"),
+ "walk": LoopProfile(0.06, 0.31, 12, "full gait = two steps; the floor admits a legless body's fast bounce (~13 frames at 24 fps) — the 15% depth rule, not the window, rejects the one-step half period"),
"run": LoopProfile(0.07, 0.23, 10, "faster gait"),
- "jump": LoopProfile(0.11, 0.45, 12, "crouch-spring-land-return"),
- "attack": LoopProfile(0.11, 0.45, 12, "swing and return to ready"),
- "default": LoopProfile(0.10, 0.45, 12, "generic in-place action"),
+ "jump": LoopProfile(0.11, 0.45, 12, "crouch-spring-land-return", one_shot_ok=True),
+ "attack": LoopProfile(0.11, 0.45, 12, "swing and return to ready", one_shot_ok=True),
+ "default": LoopProfile(0.10, 0.45, 12, "generic in-place action", one_shot_ok=True),
}
@@ -124,6 +128,68 @@ def detect_cycle(D: np.ndarray, *, min_len: int, max_len: int) -> dict[str, Any]
return best
+def detect_one_shot(D: np.ndarray, *, min_len: int, max_len: int) -> dict[str, Any]:
+ """A cycle for an action the model performed ONCE: rest -> excursion -> rest.
+
+ The rest pose is the medoid frame (smallest mean distance to every other frame — in a
+ clip that mostly stands still that is a standing frame). Frames whose distance to it
+ rises above the rest noise (median + ONE_SHOT_MIN_CONTRAST MADs) are the excursion; the
+ longest contiguous run of them, padded by ONE_SHOT_PAD rest frames on each side, is the
+ cycle, so the loop seam is rest -> rest by construction. Fails loud when nothing stands
+ out or the excursion does not fit the window — never returns a guess.
+ """
+ n = D.shape[0]
+ rest = int(np.argmin(D.mean(axis=1)))
+ e = D[rest]
+ med = float(np.median(e))
+ mad = float(np.median(np.abs(e - med))) or 1e-6
+ contrast = (float(e.max()) - med) / mad
+ if contrast < ONE_SHOT_MIN_CONTRAST:
+ raise SystemExit(
+ f"video-loop: no one-shot excursion either — the clip never leaves its rest pose "
+ f"(peak {contrast:.1f} MADs above rest, need {ONE_SHOT_MIN_CONTRAST}); regenerate the clip"
+ )
+ active = e > med + ONE_SHOT_MIN_CONTRAST * mad
+ best_run: tuple[int, int] | None = None
+ j = 0
+ while j < n:
+ if active[j]:
+ k = j
+ while k + 1 < n and active[k + 1]:
+ k += 1
+ if best_run is None or (k - j) > (best_run[1] - best_run[0]):
+ best_run = (j, k)
+ j = k + 1
+ else:
+ j += 1
+ assert best_run is not None
+ a, b = best_run
+ start = max(0, a - ONE_SHOT_PAD)
+ end = min(n - 1, b + ONE_SHOT_PAD)
+ L = end - start + 1
+ if L < min_len or L > max_len:
+ raise SystemExit(
+ f"video-loop: the one-shot excursion spans {L} frames ({a}..{b} + {ONE_SHOT_PAD} rest each side), "
+ f"outside the window [{min_len},{max_len}]; pass --min-len/--max-len if that length is intended"
+ )
+ adjacent = np.array([D[i, i + 1] for i in range(start, end)])
+ inner = float(adjacent.mean())
+ seam = float(D[start, end])
+ return {
+ "kind": "one-shot",
+ "start": start,
+ "length": L,
+ "seam": seam,
+ "inner_mean_adjacent": inner,
+ "ratio": seam / inner if inner > 0 else math.inf,
+ "period_global": None,
+ "periodicity": None,
+ "rest_frame": rest,
+ "excursion": [a, b],
+ "excursion_contrast": round(contrast, 2),
+ }
+
+
def _drop_specks(image: Image.Image, min_fraction: float) -> tuple[Image.Image, int]:
"""Erase detached alpha components smaller than `min_fraction` of the largest one."""
a = np.asarray(image)[..., 3] > 16
@@ -265,7 +331,10 @@ def run_loop(
seam_max: float,
name: str,
report_path: Path | None,
+ cycle_mode: str = "auto",
) -> dict[str, Any]:
+ 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()
files = sorted(frames_dir.glob("*.png"))
if len(files) < 6:
@@ -276,13 +345,27 @@ def run_loop(
hi = max_len if max_len is not None else max(lo + 2, round(n * prof.max_frac))
n_out = n_out or prof.n_out
D = distance_matrix(files)
- cycle = detect_cycle(D, min_len=lo, max_len=hi)
+ periodic_attempt: dict[str, Any] | None = None
+ if cycle_mode == "one-shot":
+ cycle = detect_one_shot(D, min_len=lo, max_len=hi)
+ else:
+ cycle = detect_cycle(D, min_len=lo, max_len=hi)
+ cycle["kind"] = "periodic"
+ if prof.periodic and cycle["periodicity"] < PERIODICITY_MIN:
+ flat = (
+ f"the period profile is flat (periodicity {cycle['periodicity']:.2f} < {PERIODICITY_MIN}) in window [{lo},{hi}]"
+ )
+ if cycle_mode == "auto" and prof.one_shot_ok:
+ # explicit, recorded failover: the action happened once (allowed for this state),
+ # so cut rest -> excursion -> rest instead. The periodic attempt stays in the report.
+ periodic_attempt = {"periodicity": cycle["periodicity"], "window": [lo, hi], "profile_minima": cycle["profile_minima"], "why_rejected": flat}
+ cycle = detect_one_shot(D, min_len=lo, max_len=max(hi, round(n * 0.9)))
+ else:
+ raise SystemExit(
+ 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"
+ )
i, L = cycle["start"], cycle["length"]
- if prof.periodic and cycle["periodicity"] < PERIODICITY_MIN:
- raise SystemExit(
- f"video-loop: no periodic cycle found — the period profile is flat (periodicity {cycle['periodicity']:.2f} < {PERIODICITY_MIN}) "
- f"in window [{lo},{hi}]; the motion does not repeat, widen the window or regenerate the clip"
- )
n_out = min(n_out, L) # never ask for more distinct frames than the cycle holds
out_dir = out_dir.expanduser().resolve()
@@ -337,7 +420,9 @@ def run_loop(
"frames_total": n,
"window": [lo, hi],
"profile": prof.why,
+ "cycle_mode": cycle_mode,
"cycle": cycle,
+ "periodic_attempt": periodic_attempt,
"cycle_seconds": round(cycle_seconds, 4),
"n_out": n_out,
"delay_ms": delay_ms,
@@ -364,6 +449,7 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--max-len", type=int, help="override: maximum cycle length in frames")
parser.add_argument("--n-out", type=int, help="frames in the GIF/WebP (default from the state profile)")
parser.add_argument("--seam-max", type=float, default=SEAM_RATIO_MAX, help=f"loop seam gate (default {SEAM_RATIO_MAX})")
+ parser.add_argument("--cycle", choices=CYCLE_MODES, default="auto", help="auto: periodic first, one-shot failover for action states (recorded in the report); periodic / one-shot force one detector")
parser.add_argument("--name", default="loop", help="basename for strip/gif/webp outputs")
parser.add_argument("--report", type=Path)
@@ -374,9 +460,12 @@ def run(**kwargs: object) -> int:
fps=float(kwargs.get("fps") or 24.0), state=kwargs.get("state"), # type: ignore[arg-type]
min_len=kwargs.get("min_len"), max_len=kwargs.get("max_len"), n_out=kwargs.get("n_out"), # type: ignore[arg-type]
seam_max=float(kwargs.get("seam_max") or SEAM_RATIO_MAX), name=str(kwargs.get("name") or "loop"), report_path=kwargs.get("report"), # type: ignore[arg-type]
+ cycle_mode=str(kwargs.get("cycle") or "auto"),
)
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"][k] for k in ("start", "length", "period_global", "ratio")}
+ summary["cycle"] = {k: payload["cycle"].get(k) for k in ("kind", "start", "length", "period_global", "ratio")}
+ if payload["periodic_attempt"]:
+ summary["periodic_attempt"] = payload["periodic_attempt"]["why_rejected"]
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 0
diff --git a/tests/video/test_video_pipeline.py b/tests/video/test_video_pipeline.py
index 96d3399..5e60805 100644
--- a/tests/video/test_video_pipeline.py
+++ b/tests/video/test_video_pipeline.py
@@ -179,6 +179,10 @@ def test_detect_cycle_refuses_empty_window() -> None:
def test_profiles_scale_windows_with_clip_length() -> None:
p = loop_mod.profile_for("idle")
assert p.min_frac > loop_mod.profile_for("walk").min_frac
+ # a 6 s / 24 fps clip: the walk floor must admit a 13-frame bounce (legless body) and the
+ # ceiling a 28-frame gait (2026-09-09: slime 13, wolf 24, biped 25 all resolved by the depth rule)
+ lo, hi = round(144 * loop_mod.profile_for("walk").min_frac), round(144 * loop_mod.profile_for("walk").max_frac)
+ assert lo <= 13 and hi >= 28
assert loop_mod.profile_for("unknown-state") is loop_mod.STATE_PROFILES["default"]
@@ -212,6 +216,64 @@ def test_run_loop_seam_gate_fails_loud_on_noise(tmp_path: Path, monkeypatch) ->
assert not (tmp_path / "out" / "noise.gif").exists()
+def _one_shot_frames(tmp_path: Path, n: int = 144, hop: tuple[int, int] = (60, 76), size=(64, 64), jitter: int = 2) -> list[Path]:
+ """A body that stands (with a little rest jitter, like a real keyed clip) except for ONE
+ hop between the given frames — what a video model does when it ignores 'over and over'
+ (2026-09-09 quadruped run)."""
+ d = tmp_path / "keyed"
+ d.mkdir()
+ files = []
+ rng = np.random.default_rng(3)
+ for t in range(n):
+ im = Image.new("RGBA", size, (0, 0, 0, 0))
+ lift = 0
+ if hop[0] <= t < hop[1]:
+ lift = round(14 * math.sin(math.pi * (t - hop[0]) / (hop[1] - hop[0])))
+ dx = int(rng.integers(-jitter, jitter + 1))
+ dy = int(rng.integers(-jitter, jitter + 1))
+ for y in range(20 - lift + dy, 58 - lift + dy):
+ for x in range(24 + dx, 40 + dx):
+ im.putpixel((x, y), (200, 60, 60, 255))
+ p = d / f"frame-{t:04d}.png"
+ im.save(p)
+ files.append(p)
+ return files
+
+
+def test_one_shot_detector_cuts_rest_excursion_rest(tmp_path: Path) -> None:
+ files = _one_shot_frames(tmp_path)
+ D = loop_mod.distance_matrix(files)
+ periodic = loop_mod.detect_cycle(D, min_len=16, max_len=65)
+ assert periodic["periodicity"] < loop_mod.PERIODICITY_MIN # one hop is not a period
+ cycle = loop_mod.detect_one_shot(D, min_len=9, max_len=65)
+ assert cycle["kind"] == "one-shot"
+ assert cycle["start"] <= 60 and cycle["start"] + cycle["length"] >= 75 # covers the hop, rest on both sides
+ assert cycle["ratio"] < 2.0 # rest -> rest seam within the gate
+
+
+def test_one_shot_detector_fails_loud_when_nothing_moves(tmp_path: Path) -> None:
+ files = _one_shot_frames(tmp_path, n=60, hop=(0, 0), jitter=0)
+ D = loop_mod.distance_matrix(files)
+ with pytest.raises(SystemExit, match="never leaves its rest pose"):
+ loop_mod.detect_one_shot(D, min_len=4, max_len=60)
+
+
[email protected](not HAS_IMG2WEBP, reason="img2webp not installed")
+def test_run_loop_auto_fails_over_to_one_shot_only_for_action_states(tmp_path: Path) -> None:
+ _one_shot_frames(tmp_path)
+ # walk must not repeat once: the gate stays a hard failure
+ with 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)
+ # jump may happen once: recorded failover, periodic attempt kept in the report
+ rep = 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"
+ assert rep["periodic_attempt"]["periodicity"] < loop_mod.PERIODICITY_MIN
+ assert rep["gif"]["loop"] == 0 and rep["webp"]["stale_rgb_under_alpha0"] == 0
+ # forcing periodic keeps the old behaviour
+ with pytest.raises(SystemExit, match="no periodic cycle"):
+ loop_mod.run_loop(tmp_path / "keyed", tmp_path / "jump2", fps=24.0, state="jump", min_len=None, max_len=None, n_out=8, seam_max=2.0, name="j2", report_path=None, cycle_mode="periodic")
+
+
def test_drop_specks_erases_detached_slivers_only() -> None:
im = Image.new("RGBA", (40, 40), (0, 0, 0, 0))
for y in range(5, 35):
@@ -228,7 +290,7 @@ def test_drop_specks_erases_detached_slivers_only() -> None:
def test_prompt_uses_state_and_view_and_optional_character() -> None:
p = batch_mod.build_prompt("side", "walk", "The armored knight")
- assert p.startswith("2D game sprite animation. The armored knight walks")
+ assert p.startswith("2D game sprite animation. The armored knight moves in place on a treadmill")
assert "seen from the exact side" in p
assert "The character" in batch_mod.build_prompt("back", "jump", None)
@@ -237,7 +299,16 @@ def test_motion_templates_do_not_assume_a_body_plan() -> None:
# the templates were first written for a biped; a quadruped or a legless blob must not
# be prompted into a contradiction (2026-09-09 generalization run)
for state, text in batch_mod.MOTION_TEXT.items():
- for word in ("bipedal", "knees", "arms pumping", "arms swinging"):
+ for word in (
+ "bipedal",
+ "knees",
+ "arms pumping",
+ "arms swinging",
+ "limbs alternating",
+ "Feet never",
+ "alternating strides",
+ "crouch,", # biped verb; jump uses "compress" instead
+ ):
assert word not in text, (state, word)
@@ -273,6 +344,6 @@ def test_run_set_staggers_retries_429_and_tables_failures(tmp_path: Path, monkey
assert not by["side-jump"]["ok"] and "clip generation failed" in by["side-jump"]["error"]
assert payload["failed"] == ["side-jump"]
table = (tmp_path / "set" / "table.md").read_text()
- assert "| side | jump | - | - | - | - | FAIL" in table and "| side | walk | 12 | 12 | 0.50 | 12 | OK |" in table
+ assert "| side | jump | - | - | - | - | - | FAIL" in table and "| side | walk | periodic | 12 | 12 | 0.50 | 12 | OK |" in table
assert (tmp_path / "set" / "set.report.json").is_file()
assert (tmp_path / "set" / "side-walk" / "canvas.png").is_file() # canvas ran for real