Skip to content

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

feat(cycle-align): an alignment aligns its loops as filmed and fills what it delivers at the end; a loop whose cells video-loop made again is cut again with the fill off from its report's arguments (no provider call) or refused by name, `--fill-held` and `--out-fps` once aligned, and video-set cuts the walks and runs it aligns as filmed and cuts again, filled, the ones no alignment took

Soohong Kim82e9dcd86a7f
diff --git a/sprite_gen/video/align.py b/sprite_gen/video/align.py
index fc3095d..8a4959f 100644
--- a/sprite_gen/video/align.py
+++ b/sprite_gen/video/align.py
@@ -97,9 +97,11 @@ from __future__ import annotations
import argparse
import json
+import math
import shutil
import statistics
import sys
+from functools import partial
from pathlib import Path
from typing import Any
@@ -112,6 +114,7 @@ from sprite_gen.util.gif_utils import save_clean_gif
from sprite_gen.video import sway as sway_mod
from sprite_gen.video import cadence as cadence_mod
from sprite_gen.video import held as held_mod
+from sprite_gen.video import held_fill as held_fill_mod
from sprite_gen.video import legs as legs_mod
from sprite_gen.video import local_cycle
from sprite_gen.video import loop as loop_mod
@@ -984,10 +987,10 @@ def _loop_files(loop_dir: Path) -> tuple[Path, dict[str, Any]]:
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")
- if "out_fps" in meta:
+ if "out_fps" in meta and "cycle_align" not in meta:
raise ValueError(f"{metas[0]}: cut at --out-fps {meta['out_fps']:g}, its cells each made at a time of their own — the "
"alignment makes its own frames between: align the loop cut at its clip's rate (video-loop without "
- "--out-fps)")
+ "--out-fps), and ask the alignment for the rate (video-cycle-align --out-fps)")
strip = cut_strip(loop_dir, metas[0], meta)
if strip is not None and not strip.is_file():
raise ValueError(f"{loop_dir}: no {strip.name} — a first alignment reads the strip as cut to record where its cells are from "
@@ -996,6 +999,126 @@ def _loop_files(loop_dir: Path) -> tuple[Path, dict[str, Any]]:
return metas[0], meta
+CUT_AGAIN_DIR = ".cycle.source.cut" # where a filled loop is cut again with the fill off, removed once staged
+
+
+def filled(meta: dict[str, Any]) -> bool:
+ """Whether a cut's held cells were made again (`held_fill.made`, or `made` of the read after its repair)."""
+ held = meta.get("held_fill") or {}
+ return bool(held.get("made") or (held.get("again") or {}).get("made"))
+
+
+def unfilled_source(loop_dir: Path, meta_path: Path, meta: dict[str, Any]) -> dict[str, Any] | None:
+ """The frames an alignment reads are the cut as filmed: a loop never aligned whose held cells `video-loop` made again
+ (`filled`) is cut again from its frames as its report records it was asked (`loop.cut_again`), with the fill off, and
+ that cut is kept as `cycle.source/` (its strip and strip record beside its frames) — the alignment makes its frames
+ between from filmed frames, never from frames made between, and fills what it delivers at the end. What was done
+ (`cut_again`), or None where nothing was to do: a loop aligned before, one not filled, one whose `cycle.source/`
+ already holds its cut with the fill off. ValueError naming why it cannot be cut again (a report from before cuts
+ recorded what they were asked, frames moved away, another cut taken): cut it again with `--fill-held off`."""
+ if "cycle_align" in meta or not filled(meta):
+ return None
+ source = loop_dir / SOURCE_DIR
+ staged = source / meta_path.name
+ if staged.is_file():
+ try:
+ if not filled(json.loads(staged.read_text(encoding="utf-8"))):
+ return None
+ except (OSError, ValueError):
+ pass
+ found = cut_report(loop_dir, meta_path, meta)
+ if found is None:
+ raise ValueError("its held cells were made again (held_fill), and no report of its cut is beside it to cut it again "
+ "with the fill off")
+ report_path, report = found
+ work = loop_dir / CUT_AGAIN_DIR
+ shutil.rmtree(work, ignore_errors=True)
+ try:
+ try:
+ cut = loop_mod.cut_again(report, work, report_path=work / "cut.loop.report.json", fill_held="off")
+ except SystemExit as exc:
+ raise ValueError(f"cutting it again with the fill off failed: {exc}") from None
+ cut_meta = json.loads((work / meta_path.name).read_text(encoding="utf-8"))
+ was = meta.get("cycle_drawings") or {}
+ now = cut_meta.get("cycle_drawings") or {}
+ if (now.get("start"), now.get("length")) != (was.get("start"), was.get("length")):
+ raise ValueError(f"cut again with the fill off it took frames {now.get('start')}+{now.get('length')}, not "
+ f"{was.get('start')}+{was.get('length')}")
+ shutil.rmtree(source, ignore_errors=True)
+ (work / "cycle").rename(source)
+ shutil.copyfile(work / meta_path.name, staged)
+ strip = meta_path.name[: -len(".strip.json")] + ".strip.png"
+ shutil.copyfile(work / strip, source / strip)
+ finally:
+ shutil.rmtree(work, ignore_errors=True)
+ return {"report": str(report_path), "fill_held": "off", "cells": cut["strip"]["cycle_frames"],
+ "made_before": (meta.get("held_fill") or {}).get("made", [])}
+
+
+def _material_filled(loop_dir: Path, meta_path: Path, meta: dict[str, Any]) -> bool:
+ """Whether the frames an alignment of this loop reads (`cycle.source/`, or its cut) hold cells made between: their
+ own record says so where it is kept beside them, else the cut's (a loop never aligned)."""
+ staged = loop_dir / SOURCE_DIR / meta_path.name
+ if staged.is_file():
+ try:
+ return filled(json.loads(staged.read_text(encoding="utf-8")))
+ except (OSError, ValueError):
+ return False
+ return "cycle_align" not in meta and filled(meta)
+
+
+def _indexed(cell: dict[str, Any], index: list[int]) -> dict[str, Any]:
+ """Where a cell is from (`resample`'s `cells_from`, or a cell the fill made) as frames of `cycle.source/`."""
+ if "source" in cell:
+ return {"source": index[cell["source"]]}
+ return {"between": [index[j] for j in cell["between"]], "t": cell["t"],
+ **({"held_fill": cell["held_fill"]} if "held_fill" in cell else {})}
+
+
+def _place_between(cells: list[dict[str, Any]], between: list[int], t: float, count: int, cell: int) -> dict[str, Any]:
+ """Where a cell made between two cells of the aligned loop (`between`, at `t`) stands on its `count` source frames,
+ as `cells_from` records a frame made between two: the place `t` of the way from the one's to the other's, round the
+ cycle; `held_fill` names the cells it was made between."""
+ def place(c: dict[str, Any]) -> float:
+ return float(c["source"]) if "source" in c else c["between"][0] + c["t"]
+
+ pa, pb = place(cells[between[0]]), place(cells[between[1]])
+ x = pa + t * ((pb - pa) % count)
+ i = math.floor(x)
+ return {"between": [i % count, (i + 1) % count], "t": round(x - i, 4),
+ "held_fill": {"between": list(between), "t": round(t, 4), "cell": cell}}
+
+
+def _fill_aligned(frames: list[Image.Image], interpolate: Any, *, mode: str, hold: int | None
+ ) -> tuple[list[Image.Image], dict[str, Any]]:
+ """`held_fill.fill` on an aligned loop (a ring: its first cell kept; `hold` the hold of frames drawn on twos or
+ threes, every run kept). No RIFE installed: its held cells are delivered as resampled, the record says which and how
+ to install it (`unmade`), never a failure."""
+ asked = partial(held_fill_mod.fill, ring=True, mode=mode, drawn_on=hold)
+ try:
+ return asked(frames, interpolate)
+ except rife_mod.RifeNotInstalled as exc:
+ out, record = asked(frames, None)
+ if "unmade" in record:
+ record["unmade"].update(why="RIFE is not installed", rife=str(exc), install=rife_mod.install_command())
+ return out, record
+
+
+def _rate_aligned(frames: list[Image.Image], interpolate: Any, cells: list[dict[str, Any]], *, fps: float, out_fps: float,
+ count: int) -> tuple[list[Image.Image], dict[str, Any], list[dict[str, Any]]]:
+ """An aligned loop given at `out_fps` (`held_fill.upsample`), and where each of its cells is from. No RIFE
+ installed: the loop at its own rate, the record saying so."""
+ try:
+ out, record = held_fill_mod.upsample(frames, interpolate, ring=True, fps=fps, out_fps=out_fps)
+ except rife_mod.RifeNotInstalled as exc:
+ return frames, {"asked": out_fps, "fps": fps, "applied": False, "cells": len(frames), "why": "RIFE is not installed",
+ "rife": str(exc), "install": rife_mod.install_command()}, cells
+ made = {row["cell"]: row for row in record["frames"]}
+ placed = [cells[k] if k is not None else _place_between(cells, made[j]["between"], made[j]["t"], count, j)
+ for j, k in enumerate(record["source_frames"])]
+ return out, record, placed
+
+
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
@@ -1018,6 +1141,9 @@ def cut_strip(loop_dir: Path, meta_path: Path, meta: dict[str, Any]) -> Path | N
follow-through moved it); None on a loop aligned before, whose origin its first alignment recorded."""
if "cycle_align" in meta:
return None
+ staged = loop_dir / SOURCE_DIR / f"{meta_path.name[: -len('.strip.json')]}.strip.png"
+ if staged.is_file():
+ return staged # the cut again with the fill off (`unfilled_source`): what is aligned
source = loop_dir / loop_mod.FOLLOW_SOURCE
return source if source.exists() else loop_dir / f"{meta_path.name[: -len('.strip.json')]}.strip.png"
@@ -1029,17 +1155,25 @@ def origin_of(loop_dir: Path, meta_path: Path, meta: dict[str, Any]) -> dict[str
strip = cut_strip(loop_dir, meta_path, meta)
if strip is None:
return meta["cycle_align"].get("origin")
+ if strip.parent.name == SOURCE_DIR:
+ meta = json.loads((strip.parent / meta_path.name).read_text(encoding="utf-8"))
return sway_mod.cut_origin(strip.read_bytes(), meta)
def _rebuild(loop_dir: Path, meta_path: Path, meta: dict[str, Any], frames: list[Image.Image], fps: float,
record: dict[str, Any], *, cells_from: list[dict[str, Any]] | None = None,
- origin: dict[str, Any] | None = None) -> dict[str, Any]:
+ origin: dict[str, Any] | None = None, held: dict[str, Any] | None = None,
+ holds: list[dict[str, Any]] | None = None, times: list[float] | None = None,
+ source_fps: float | None = None) -> dict[str, Any]:
"""Write the aligned cycle, strip, GIF and WebP over the loop's own, at the loop's own cell size rules. `cells_from`
says where each of `frames` is from; the record keeps it per cell of the strip, with the cut's `origin`. On a loop
- never aligned, the cut's own strip record is kept beside its frames as filmed first (`cycle.source/`), as it was."""
+ never aligned, the cut's own strip record is kept beside its frames as filmed first (`cycle.source/`), as it was
+ (unless it is there already: a filled loop cut again with the fill off, `unfilled_source`). `held` is what the
+ alignment's fill made of the loop's held cells (`held_fill.public`) and `holds` the holds it kept as the motion's own,
+ as cells of `frames` (both replace the cut's, whose cells these are not); `fps` the rate of `frames`, and
+ `source_fps` the clip's where they are given at a rate of their own (`--out-fps`), each cell at `times`."""
name = meta_path.name[: -len(".strip.json")]
- if "cycle_align" not in meta:
+ if "cycle_align" not in meta and not (loop_dir / SOURCE_DIR / meta_path.name).is_file():
shutil.copyfile(meta_path, loop_dir / SOURCE_DIR / meta_path.name)
cycle_dir = loop_dir / "cycle"
cycle_dir.mkdir(exist_ok=True)
@@ -1065,6 +1199,13 @@ def _rebuild(loop_dir: Path, meta_path: Path, meta: dict[str, Any], frames: list
and not (k == "steps" and "cycle_taken" in record)}, **strip_meta}
if meta.get("foot_anchor") and meta.get("foot_anchor") != "feet":
merged["foot_anchor"] = meta["foot_anchor"]
+ for key in ("out_fps", "source_fps"):
+ merged.pop(key, None)
+ if source_fps is not None:
+ merged.update(out_fps=fps, source_fps=source_fps)
+ if held is not None:
+ merged["held_fill"] = held
+ merged["holds"] = held_fill_mod.strip_holds(holds or [], strip_meta["sample_indices"], times)
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())
@@ -1196,7 +1337,7 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:
report_path: Path | None = None, between: str = DEFAULT_BETWEEN, views: list[str | None] | None = None,
start_foot: str = START_FOOT, multi_cycle: str = "fail", cycles: dict[str, int] | None = None,
state: str | None = None, feet: dict[str, str] | None = None, between_cache: Path | None = None,
- same_foot: str = "warn") -> dict[str, Any]:
+ same_foot: str = "warn", fill_held: str = "auto", out_fps: float | None = None) -> dict[str, Any]:
"""Resample every loop of a set to one length (default: the median), turned to a foot strike —
where `views` (one per loop: `front`, `back`, `side@right`, `front_diagonal@left`, …) lets it,
the strike of the same own foot (`start_foot`) in every loop.
@@ -1224,7 +1365,13 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:
Every loop's beat is recorded (`beat`, `cadence.beat_record`, as frames of the turned loop), and a loop seen from the
back or a back diagonal is read for the same foot stepping twice in a row (`same_foot`, `cadence.same_foot`, with the
clip's every cut as `video-loop` read them, `clip`): `same_foot` warn names such a loop in the warnings, refuse stops
- the set before anything is rewritten (the report written with `applied` false, `refused` same-foot)."""
+ the set before anything is rewritten (the report written with `applied` false, `refused` same-foot).
+
+ The frames aligned are the cut as filmed: a loop whose held cells video-loop made again is cut again with the fill
+ off first (`unfilled_source`), or the set stops naming it. Each loop delivered is read at the end, its held cells made
+ between the poses beside them as video-loop fills a loop (`held_fill.fill`, `fill_held` auto; off delivers them as
+ resampled), its record (`held_fill`) and kept holds (`holds`) replacing the cut's; and given at `out_fps` where one
+ is asked (`held_fill.upsample`, every loop the same number of cells)."""
if len(loop_dirs) < 1:
raise SystemExit("video-cycle-align: at least one --loop-dir")
if between_cache is not None and interpolate is not None and not callable(getattr(interpolate, "identity", None)):
@@ -1238,6 +1385,8 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:
raise SystemExit(f"video-cycle-align: --multi-cycle must be one of {', '.join(MULTI_CYCLE)}, not {multi_cycle!r}")
if same_foot not in SAME_FOOT:
raise SystemExit(f"video-cycle-align: --same-foot must be one of {', '.join(SAME_FOOT)}, not {same_foot!r}")
+ if fill_held not in held_fill_mod.MODES:
+ raise SystemExit(f"video-cycle-align: --fill-held must be one of {', '.join(held_fill_mod.MODES)}, not {fill_held!r}")
for v in views or []:
if v is not None:
name, _, facing = v.partition("@")
@@ -1253,13 +1402,26 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:
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"]))
+ # an aligned loop given at a rate of its own is aligned again from its frames at the clip's rate
+ loops.append((d, meta_path, meta, float(meta["source_fps"]) if "out_fps" in meta else 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)
+ if out_fps is not None and not (math.isfinite(out_fps) and out_fps > fps):
+ raise SystemExit(f"video-cycle-align: --out-fps {out_fps:g} is not above the loops' {fps:g} fps: a set is given at a "
+ "higher rate than it was filmed (its frames between made)")
+ cut_again: dict[int, dict[str, Any]] = {}
+ for i, (d, meta_path, meta, _) in enumerate(loops):
+ try:
+ done = unfilled_source(d, meta_path, meta)
+ except ValueError as exc:
+ raise SystemExit(f"video-cycle-align: {d}: {exc} — cut it again with `video-loop --fill-held off` and align that: "
+ "the alignment makes its frames between from frames as filmed (docs/loop-repair.md section 7)") from None
+ if done is not None:
+ cut_again[i] = done
sources = []
for d, *_ in loops:
try:
@@ -1357,10 +1519,11 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:
raise SystemExit(f"video-cycle-align: {d}: {exc}; frames between source frames are made by RIFE (docs/loop-repair.md)") from exc
start = strike["start"]
# A loop whose held cells video-loop made again (`held_fill`) shows a picture a cell where its clip held them: the
- # clip's readings say how it was filmed, not how it plays, and its own cells are read.
- filled = bool((loops[i][2].get("held_fill") or {}).get("made"))
- drawings = held_drawings(frames, fps=fps, clip=None if filled else loops[i][2].get("drawings"),
- cut=None if filled else loops[i][2].get("cycle_drawings"))
+ # clip's readings say how it was filmed, not how it plays, and its own cells are read. The frames aligned are the
+ # cut's as filmed wherever they can be (`unfilled_source`); only an aligned loop's frames from before may be filled.
+ made = _material_filled(d, loops[i][1], loops[i][2])
+ drawings = held_drawings(frames, fps=fps, clip=None if made else loops[i][2].get("drawings"),
+ cut=None if made else loops[i][2].get("cycle_drawings"))
# the ghosts passed over or kept as frames of cycle.source/, each cell where it now stands
ghost_at = sorted(({**g, "at": (g["at"] - start) % target, "source": index[g["source"]], "taken": index[g["taken"]]}
for g in facts["ghost_at"]), key=lambda g: g["at"])
@@ -1393,14 +1556,31 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:
"at": [[(k - start) % target, (k + 1 - start) % target]
for k in _showing(j["step"][0], provenance, len(frames))]}
for j in screen["jumps"]]}
- provenance = [{"source": index[p["source"]]} if "source" in p else {"between": [index[j] for j in p["between"]], "t": p["t"]}
- for p in provenance]
+ raw = provenance
+ provenance = [_indexed(p, index) for p in provenance]
out = out[start:] + out[:start]
if cadence_mod.view_reads_feet(view):
record["same_foot"] = {**cadence_mod.same_foot(out, view), "clip": loops[i][2].get("clip_feet")}
record["retake"] = retake(drawings, facts, ghost_at, fps=fps, beat=record["beat"], feet=record.get("same_foot"),
screen=record["screen"])
- aligned.append((out, record, provenance[start:] + provenance[:start]))
+ if i in cut_again:
+ record["cut_again"] = cut_again[i]
+ # The loop as delivered, read at the end (docs/loop-repair.md section 7): its held cells made between the poses
+ # beside them, its first cell kept (a loop drawn on twos or threes keeps every run), then given at `out_fps`.
+ hold = held_fill_mod.drawn(held_fill_mod.runs(held_fill_mod.same_steps(frames)), len(frames), drawings.get("hold"))
+ out, held = _fill_aligned(out, lazy, mode=fill_held, hold=hold)
+ turned = raw[start:] + raw[:start]
+ base = list(turned)
+ for row in held.get("frames", []):
+ turned[row["cell"]] = _place_between(base, row["between"], row["t"], len(frames), row["cell"])
+ times = None
+ if out_fps is not None:
+ out, held["out_fps"], turned = _rate_aligned(out, lazy, turned, fps=fps, out_fps=out_fps, count=len(frames))
+ times = held["out_fps"]["times"] if held["out_fps"]["applied"] else None
+ record["held_fill"] = held
+ record["holds"] = held_fill_mod.intended(held)
+ record["times"] = times
+ aligned.append((out, record, [_indexed(p, index) for p in turned]))
twice = [(loops[i][0], loops[i][1], record) for i, (_, record, _) in enumerate(aligned)
if (record.get("same_foot") or {}).get("twice")]
if twice and same_foot == "refuse":
@@ -1416,10 +1596,14 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:
raise SystemExit(message)
rows = []
for (d, meta_path, meta, _), (out, record, provenance), origin in zip(loops, aligned, origins):
- merged = _rebuild(d, meta_path, meta, out, fps, record, cells_from=provenance, origin=origin)
+ held, holds, times = record.pop("held_fill"), record.pop("holds"), record.pop("times")
+ public = held_fill_mod.public(held)
+ rate = held["out_fps"]["asked"] if (held.get("out_fps") or {}).get("applied") else None
+ merged = _rebuild(d, meta_path, meta, out, rate or fps, record, cells_from=provenance, origin=origin, held=public,
+ holds=holds, times=times, source_fps=fps if rate else None)
# The report names where each cell is from; the cut's own record stays in the strip's meta.
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", "origin")},
+ **{k: v for k, v in record.items() if k not in ("gif", "webp", "origin")}, "held_fill": public,
"strip": {k: merged[k] for k in ("frames", "w", "h", "body_h", "delay_ms")}})
warnings = [_fault_line(r["name"], m, next((g for g in r["ghost_at"] if g["at"] == m["at"]), None))
for r in rows for m in r.get("smear", []) if m["faults"]]
@@ -1430,6 +1614,9 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:
# A loop to film again is named by its directory where two loops share a strip name (each `walk`).
shared = len({r["name"] for r in rows}) < len(rows)
warnings += [_ghost_line(r["dir"] if shared else r["name"], g) for r in rows for g in r["ghost_at"]]
+ warnings += [f"{r['dir'] if shared else r['name']}: {line}" for r in rows for line in loop_mod.fill_lines(r["held_fill"])]
+ warnings += [f"{r['dir'] if shared else r['name']}: {line}" for r in rows if "out_fps" in r["held_fill"]
+ for line in loop_mod.out_fps_lines(r["held_fill"]["out_fps"])]
warnings += [f"{r['dir'] if shared else r['name']}: the ghost screen does not read it — {r['ghost_screen']['why']}; no frame of it "
"is named a ghost or given way for one, so look at cycle/ (docs/loop-repair.md section 4)"
for r in rows if not r["ghost_screen"]["reads"]]
@@ -1450,7 +1637,8 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:
"lengths": lengths, "multi_cycle": multi_cycle, "suspects": suspects, "unnamed_feet": unnamed,
"cycles_given": {str(loops[i][0]): k for i, k in given.items()},
"feet_given": {str(loops[i][0]): f for i, f in told.items()},
- "fps": round(fps, 4), "cycle_seconds": round(target / fps, 4),
+ "fps": round(fps, 4), "cycle_seconds": round(target / fps, 4), "fill_held": fill_held,
+ **({"out_fps": out_fps} if out_fps is not None else {}),
"interpolator": (dict(located[0]) if located else
{"kind": "injected"} if any(r.get("smear") for r in rows) else None),
"between_cache": cache.record() if cache is not None else None,
@@ -1501,6 +1689,17 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
"halves of its feet lifting, read round the loop): warn (default) names it in the report (`same_foot`, "
"with its clip's every cut as video-loop read them) and the warnings; refuse stops the set before "
"anything is rewritten, the report naming it")
+ parser.add_argument("--fill-held", choices=held_fill_mod.MODES, default="auto",
+ help="auto (default): each loop as aligned is read for neighbour cells that show the same picture, and "
+ "they are made again as the frames between the poses beside them, as video-loop fills a loop "
+ "(docs/loop-repair.md section 7), its first cell kept; a loop drawn on twos or threes, and a hold "
+ "longer than three cells, are kept; with no RIFE the cells are delivered as resampled with a "
+ "warning. off: delivered as resampled. A loop whose held cells video-loop made again is cut again "
+ "with the fill off from its report before it is aligned (or the set stops naming it)")
+ parser.add_argument("--out-fps", type=float, metavar="F",
+ help="give every loop of the set at F frames a second, above the loops' own rate, once aligned: each "
+ "cell at its own time, made between the cells beside it (never a cell shown again), every loop "
+ "the same number of cells; the strip metadata says `out_fps` and `source_fps`")
parser.add_argument("--between-cache", type=Path, metavar="DIR",
help="a directory every frame RIFE makes between two source frames is kept in, for aligning the same set "
"again: a later alignment given the same DIR (the feet told, a retake in place of one loop) takes a "
@@ -1543,7 +1742,8 @@ def run(**kwargs: object) -> int:
multi_cycle=str(kwargs.get("multi_cycle") or "fail"), cycles=parse_cycles(list(kwargs.get("cycles") or [])), # type: ignore[arg-type]
state=kwargs.get("state"), feet=parse_feet(list(kwargs.get("foot") or [])), # type: ignore[arg-type]
between_cache=kwargs.get("between_cache"), # type: ignore[arg-type]
- same_foot=str(kwargs.get("same_foot") or "warn"))
+ same_foot=str(kwargs.get("same_foot") or "warn"),
+ fill_held=str(kwargs.get("fill_held") or "auto"), out_fps=kwargs.get("out_fps")) # type: ignore[arg-type]
except rife_mod.RifeNotInstalled as exc:
# Asked for by name, so no RIFE is a failure, never a quiet skip (video-set skips with a warning).
raise SystemExit(f"video-cycle-align: {exc}; frames between source frames are made by RIFE — "
diff --git a/sprite_gen/video/batch.py b/sprite_gen/video/batch.py
index 573b122..a3fe108 100644
--- a/sprite_gen/video/batch.py
+++ b/sprite_gen/video/batch.py
@@ -879,50 +879,7 @@ def run_item(
cycle_mode=cut,
facing=facing if direction in handed_mod.LATERAL_VIEWS else "right", view=direction,
fill_held=fill_held, out_fps=out_fps, air_retime=air_retime, meters_per_px=meters_per_px)
- result["loop"] = {"kind": lp["cycle"].get("kind", "periodic"), "cycle": lp["cycle"]["length"], "period": lp["cycle"]["period_global"], "cycle_ratio": round(lp["cycle"]["ratio"], 3), "seam_ratio": lp["resampled_seam_ratio"], "n_out": lp["n_out"], "drift_px": lp["strip"].get("drift_px", 0), "gif": lp["gif"]["file"], "webp": lp["webp"]["file"], "strip": lp["strip"]["path"]}
- result["loop"]["review_recommended"] = lp["cycle"].get("review_recommended", False)
- result["loop"]["half_period_guard"] = lp["cycle"].get("half_period_guard")
- if (lp["cycle"].get("fundamental") or {}).get("suspects"):
- # a half or a third of the cut repeats: it may hold that many cycles (recorded, not cut)
- result["loop"]["fundamental"] = {"period": lp["cycle"]["fundamental"]["period"],
- "suspects": [{k: row.get(k) for k in ("period", "cycles", "pose", "steps")}
- for row in lp["cycle"]["fundamental"]["suspects"]]}
- if "steps" in lp["cycle"]:
- # the cut's steps are known: its frame count is two steps — one cycle — not twice its siblings' one
- result["loop"]["steps"] = lp["cycle"]["steps"]["count"]
- if local_cycle.unwitnessed(lp["cycle"]):
- # its crossings may mark cycles, or its cut be one step, and nothing witnesses whether: it may hold half a
- # cycle or two
- result["loop"][local_cycle.UNWITNESSED] = True
- if local_cycle.four_steps(lp["cycle"]):
- # its cut holds four steps (its body or its feet say so): two cycles where its strip counts two steps — aligned as one
- # cycle, it would play twice as fast
- result["loop"][local_cycle.FOUR_STEPS] = True
- if (lp["cycle"].get("step_screen") or {}).get("suspect"):
- # the cut may be one step of a cycle twice as long (recorded, not cut again)
- result["loop"]["step_screen"] = {k: lp["cycle"]["step_screen"][k] for k in ("lag", "ratio", "depth", "coverage")}
- if lp.get("motion_anchor", {}).get("applied") is False:
- result["loop"]["motion_anchor"] = lp["motion_anchor"]
- if lp.get("retake"):
- # a take to film again (a part that pops at the wrap, a walk that starts or stops in the take), named
- result["loop"]["retake"] = {k: lp["retake"][k] for k in ("reason", "reasons", "remedy")}
- # The cut's poses over its cells, its held runs as delivered, and what became of them (docs/loop-repair.md section 7).
- held = lp["held_fill"]
- result["loop"]["poses"] = held_fill_mod.said(held)
- result["loop"]["held_fill"] = {"before": held_fill_mod.said(held["before"]), "held_runs": held["held_runs"],
- "made": held["made"], **({"unmade": held["unmade"]} if "unmade" in held else {}),
- **({"out_fps": held["out_fps"]} if "out_fps" in held else {})}
- if "root_motion" in lp:
- # A cut played once: each air's seconds and apex (docs/video-pipeline.md, "Root motion").
- result["loop"]["air"] = root_motion_mod.said(lp["root_motion"])
- if "air_retime" in lp:
- result["loop"]["air_retime"] = {k: lp["air_retime"][k] for k in ("applied", "why", "made", "shown_again", "poses", "cells")
- if k in lp["air_retime"]}
- if "rife" in (lp.get("jump_repair") or {}):
- # cut as filmed for want of RIFE: the set report lists it under `warnings` (a wrap the seam bridge read carries
- # its `seam`, not the flow's `off_max_before`)
- result["loop"]["jump_repair"] = {k: lp["jump_repair"][k] for k in ("applied", "why", "off_max_before", "seam", "install")
- if k in lp["jump_repair"]}
+ result["loop"] = loop_summary(lp)
result["ok"] = True
except CodexUnavailableAsk as exc:
result["ok"] = False
@@ -934,6 +891,60 @@ def run_item(
return result
+def held_summary(held: dict[str, Any]) -> dict[str, Any]:
+ """What the set report says of a loop's held cells (its `held_fill` record, the cut's or its alignment's)."""
+ return {"before": held_fill_mod.said(held["before"]), "held_runs": held["held_runs"], "made": held["made"],
+ **({"unmade": held["unmade"]} if "unmade" in held else {}),
+ **({"out_fps": held["out_fps"]} if "out_fps" in held else {})}
+
+
+def loop_summary(lp: dict[str, Any]) -> dict[str, Any]:
+ """What the set report says of an item's loop, from `video-loop`'s report of its cut."""
+ loop: dict[str, Any] = {"kind": lp["cycle"].get("kind", "periodic"), "cycle": lp["cycle"]["length"], "period": lp["cycle"]["period_global"], "cycle_ratio": round(lp["cycle"]["ratio"], 3), "seam_ratio": lp["resampled_seam_ratio"], "n_out": lp["n_out"], "drift_px": lp["strip"].get("drift_px", 0), "gif": lp["gif"]["file"], "webp": lp["webp"]["file"], "strip": lp["strip"]["path"]}
+ loop["review_recommended"] = lp["cycle"].get("review_recommended", False)
+ loop["half_period_guard"] = lp["cycle"].get("half_period_guard")
+ if (lp["cycle"].get("fundamental") or {}).get("suspects"):
+ # a half or a third of the cut repeats: it may hold that many cycles (recorded, not cut)
+ loop["fundamental"] = {"period": lp["cycle"]["fundamental"]["period"],
+ "suspects": [{k: row.get(k) for k in ("period", "cycles", "pose", "steps")}
+ for row in lp["cycle"]["fundamental"]["suspects"]]}
+ if "steps" in lp["cycle"]:
+ # the cut's steps are known: its frame count is two steps — one cycle — not twice its siblings' one
+ loop["steps"] = lp["cycle"]["steps"]["count"]
+ if local_cycle.unwitnessed(lp["cycle"]):
+ # its crossings may mark cycles, or its cut be one step, and nothing witnesses whether: it may hold half a
+ # cycle or two
+ loop[local_cycle.UNWITNESSED] = True
+ if local_cycle.four_steps(lp["cycle"]):
+ # its cut holds four steps (its body or its feet say so): two cycles where its strip counts two steps — aligned as one
+ # cycle, it would play twice as fast
+ loop[local_cycle.FOUR_STEPS] = True
+ if (lp["cycle"].get("step_screen") or {}).get("suspect"):
+ # the cut may be one step of a cycle twice as long (recorded, not cut again)
+ loop["step_screen"] = {k: lp["cycle"]["step_screen"][k] for k in ("lag", "ratio", "depth", "coverage")}
+ if lp.get("motion_anchor", {}).get("applied") is False:
+ loop["motion_anchor"] = lp["motion_anchor"]
+ if lp.get("retake"):
+ # a take to film again (a part that pops at the wrap, a walk that starts or stops in the take), named
+ loop["retake"] = {k: lp["retake"][k] for k in ("reason", "reasons", "remedy")}
+ # The cut's poses over its cells, its held runs as delivered, and what became of them (docs/loop-repair.md section 7).
+ held = lp["held_fill"]
+ loop["poses"] = held_fill_mod.said(held)
+ loop["held_fill"] = held_summary(held)
+ if "root_motion" in lp:
+ # A cut played once: each air's seconds and apex (docs/video-pipeline.md, "Root motion").
+ loop["air"] = root_motion_mod.said(lp["root_motion"])
+ if "air_retime" in lp:
+ loop["air_retime"] = {k: lp["air_retime"][k] for k in ("applied", "why", "made", "shown_again", "poses", "cells")
+ if k in lp["air_retime"]}
+ if "rife" in (lp.get("jump_repair") or {}):
+ # cut as filmed for want of RIFE: the set report lists it under `warnings` (a wrap the seam bridge read carries
+ # its `seam`, not the flow's `off_max_before`)
+ loop["jump_repair"] = {k: lp["jump_repair"][k] for k in ("applied", "why", "off_max_before", "seam", "install")
+ if k in lp["jump_repair"]}
+ return loop
+
+
def _refuse_mirror_with_handed(facing_fix: str, handed: list[Handed] | None) -> None:
if handed and facing_fix == "mirror":
raise SystemExit("video-set: --facing-fix mirror turns the picture over and moves every --handed item to the "
@@ -1011,8 +1022,27 @@ def left_out_why(reasons: list[str], *, stands: bool = False, one_step: bool = F
return why + ("; its step screen says it may be one step (cut it again with video-loop --steps 1 if it is)" if one_step else "")
+def cut_again_unaligned(r: dict[str, Any], *, fill_held: str, out_fps: float | None) -> None:
+ """An item's loop cut for an alignment that did not take it, cut again from its report as a loop delivered as it
+ is (`loop.cut_again`): `fill_held` and `out_fps` as the set was asked. Its result says so (`cut_again`); a cut again
+ that fails is the item's failure."""
+ item_dir = Path(r["dir"])
+ report_path = item_dir / "loop.report.json"
+ try:
+ report = json.loads(report_path.read_text(encoding="utf-8"))
+ lp = loop_mod.cut_again(report, item_dir / "loop", report_path=report_path, fill_held=fill_held, out_fps=out_fps)
+ except (OSError, ValueError) as exc:
+ r["ok"], r["error"] = False, f"the loop cut for the alignment, not aligned, could not be cut again with its held cells filled: {exc}"
+ return
+ except SystemExit as exc:
+ r["ok"], r["error"] = False, str(exc)
+ return
+ r["loop"] = {**loop_summary(lp), "cut_again": {"why": "not aligned", "fill_held": fill_held,
+ **({"out_fps": out_fps} if out_fps is not None else {})}}
+
+
def align_gaits(results: list[dict[str, Any]], root: Path, mode: str, *, interpolate: Any = None, between: str = align_mod.DEFAULT_BETWEEN,
- feet: dict[str, str] | None = None) -> dict[str, Any]:
+ feet: dict[str, str] | None = None, fill_held: str = "auto", out_fps: float | None = 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.
@@ -1062,7 +1092,8 @@ def align_gaits(results: list[dict[str, Any]], root: Path, mode: str, *, interpo
try:
report = align_mod.align_set([Path(r["dir"]) / "loop" for r in rows], interpolate=interpolate,
report_path=root / f"{state}.cycle-align.json", between=between,
- views=[_align_view(r) for r in rows], state=state, feet=told)
+ views=[_align_view(r) for r in rows], state=state, feet=told,
+ fill_held=fill_held, out_fps=out_fps)
except rife_mod.RifeNotInstalled as exc:
out[state] = {"ok": True, "applied": False, "reason": "rife-not-installed", "why": "RIFE not installed — each loop keeps its own length",
"rife": str(exc), "install": rife_mod.install_command()}
@@ -1097,6 +1128,9 @@ def align_gaits(results: list[dict[str, Any]], root: Path, mode: str, *, interpo
r["loop"]["cycle_align"] = {k: row[k] for k in ("from", "to", "made_by_rife", "turned_by", "turned_on", "start_foot", "start_foot_source",
"seam_ratio", "retake")}
r["loop"]["n_out"] = row["strip"]["frames"]
+ # the loop as delivered is the alignment's: its held cells and its poses over its cells are the alignment's
+ r["loop"]["held_fill"] = held_summary(row["held_fill"])
+ r["loop"]["poses"] = held_fill_mod.said(row["held_fill"])
for state, items in left_out.items():
out.setdefault(state, {"ok": True, "applied": False, "why": "fewer than two directions left to align"})["left_out"] = items
for item, reasons in items.items():
@@ -1234,9 +1268,6 @@ def run_set(
raise SystemExit(f"video-set: {exc}") from None
if meters_per_px is None and {"gravity", "speed"} & set(asked_air):
raise SystemExit("video-set: --air-retime gravity= and speed= are metres: give --meters-per-px")
- if out_fps is not None and aligned_items:
- raise SystemExit(f"video-set: --out-fps gives each cut at a higher rate, and the cycle alignment of {', '.join(aligned_items)} "
- "makes its own frames between to one length — pass --align-cycles off with it")
for item, foot in (align_feet or {}).items():
if item not in aligned_items:
raise SystemExit(f"video-set: --align-foot {item}={foot}: {item} is not an item the set aligns (a walk or run filmed in two or "
@@ -1258,13 +1289,20 @@ def run_set(
return prepare_side
with ThreadPoolExecutor(max_workers=max(1, concurrency)) as ex:
- futures = {ex.submit(run_item, item=i, direction=d, state=s, base=b, root=root, character=character, duration=duration, resolution=resolution, key=key, force=force, gap=gap, video_runner=video_runner, shape=shape, anchor=anchor, spill=spill, facing=f, facing_fix=facing_fix, prepare_side=side_preparer(f), body_height=body_height, fit=fit, decontam=decontam, walk_start=walk_start, redraw_runner=redraw_runner, still_provider=still_provider, handed=handed, body_plan=body_plan, **({"end_frame": end_frames[i]} if end_frames and i in end_frames else {}), **({"play": plays[i]} if i in plays else {}), **({"motion": motions[i]} if i in motions else {}), fill_held=fill_held, out_fps=out_fps, air_retime=air_retime, meters_per_px=meters_per_px): i for i, d, s, f, b in items}
+ futures = {ex.submit(run_item, item=i, direction=d, state=s, base=b, root=root, character=character, duration=duration, resolution=resolution, key=key, force=force, gap=gap, video_runner=video_runner, shape=shape, anchor=anchor, spill=spill, facing=f, facing_fix=facing_fix, prepare_side=side_preparer(f), body_height=body_height, fit=fit, decontam=decontam, walk_start=walk_start, redraw_runner=redraw_runner, still_provider=still_provider, handed=handed, body_plan=body_plan, **({"end_frame": end_frames[i]} if end_frames and i in end_frames else {}), **({"play": plays[i]} if i in plays else {}), **({"motion": motions[i]} if i in motions else {}), fill_held="off" if i in aligned_items else fill_held, out_fps=None if i in aligned_items else out_fps, air_retime=air_retime, meters_per_px=meters_per_px): i for i, d, s, f, b in items}
for fut in as_completed(futures):
r = fut.result()
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, between=align_between, feet=align_feet)
+ aligned = align_gaits(results, root, align_cycles, interpolate=interpolate, between=align_between, feet=align_feet,
+ fill_held=fill_held, out_fps=out_fps)
+ # An item cut for the alignment (its held cells as filmed, at its clip's rate) that no alignment took — left out, or
+ # its state not aligned — is a loop delivered as it is: cut again as asked, its held cells filled (docs/loop-repair.md
+ # section 7).
+ for r in results:
+ if r.get("ok") and r["item"] in aligned_items and "cycle_align" not in r["loop"] and (fill_held != "off" or out_fps is not None):
+ cut_again_unaligned(r, fill_held=fill_held, out_fps=out_fps)
table = write_table(results, root / "table.md", both=both)
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")]
# What the set left undone for want of RIFE — never a failure, never silent.
@@ -1399,11 +1437,12 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
"the set's start foot lands, recorded start_foot_source given")
parser.add_argument("--fill-held", choices=held_fill_mod.MODES, default="auto",
help="each cut's neighbour cells showing the same picture (video-loop --fill-held): auto (default) makes "
- "them again with RIFE's frames between, off cuts them as filmed; each item's `loop.poses` says its poses "
- "over its cells")
+ "them again with RIFE's frames between (a walk or run the set aligns is cut as filmed and filled once "
+ "aligned, video-cycle-align --fill-held), off cuts them as filmed; each item's `loop.poses` says its "
+ "poses over its cells")
parser.add_argument("--out-fps", type=float, default=None,
- help="give each cut at this rate, above its clip's, made of frames between (video-loop --out-fps); with "
- "a walk or run filmed in two or more directions, pass --align-cycles off")
+ help="give each cut at this rate, above its clip's, made of frames between (video-loop --out-fps); a "
+ "walk or run filmed in two or more directions is given it once aligned (video-cycle-align --out-fps)")
parser.add_argument("--air-retime", default=None, metavar="gravity=G,air=T,speed=V",
help="each cut played once with an air in it: that air given a length, a gravity and a speed of its own "
"(video-loop --air-retime); each item's `loop.air` says each air's seconds and apex")
diff --git a/tests/video/test_loop_prop_seam_held.py b/tests/video/test_loop_prop_seam_held.py
index 01d22f8..bde8e61 100644
--- a/tests/video/test_loop_prop_seam_held.py
+++ b/tests/video/test_loop_prop_seam_held.py
@@ -426,6 +426,8 @@ GHOST_KEYS_2430 = {"ghost_screen", "ghost_at"}
CLIP_FEET_KEYS, BEAT_KEYS = {"clip_feet"}, {"beat", "screen"}
# 3.8.0: the cut's held cells, read and made again (docs/loop-repair.md section 7)
HELD_FILL_KEYS_3800 = {"held_fill"}
+# 4.0.0: the strip's exact rate, and the cells it shows again on purpose (docs/loop-repair.md section 7)
+NO_REPEAT_KEYS_400 = {"fps", "holds"}
def test_cycle_align_writes_a_loop_without_a_held_part_as_before(tmp_path, staffless):
@@ -448,8 +450,11 @@ def test_cycle_align_writes_a_loop_without_a_held_part_as_before(tmp_path, staff
assert all("cycles_kept" not in row and "steps" not in row for row in out["loops"])
for d in dirs:
meta = json.loads((d / "loop.strip.json").read_text())
- assert set(meta) == STRIP_KEYS_2350 | SOURCE_KEYS_2390 | CLIP_FEET_KEYS | HELD_FILL_KEYS_3800
- assert set(meta["cycle_align"]) == CYCLE_ALIGN_KEYS_2350 | CORRESPONDENCE_KEYS_2410 | GHOST_KEYS_2430 | BEAT_KEYS
+ assert set(meta) == STRIP_KEYS_2350 | SOURCE_KEYS_2390 | CLIP_FEET_KEYS | HELD_FILL_KEYS_3800 | NO_REPEAT_KEYS_400
+ # 4.0.0: a cut whose cells were made again after its repair (its read again) is cut again with the fill off
+ # before it is aligned, and the alignment says so (docs/loop-repair.md section 7).
+ again = {"cut_again"} if align.filled(cut) else set()
+ assert set(meta["cycle_align"]) == CYCLE_ALIGN_KEYS_2350 | CORRESPONDENCE_KEYS_2410 | GHOST_KEYS_2430 | BEAT_KEYS | again
# The cut's source stays as the cut wrote it: `cycle_align` says the cells were turned after it, so it
# no longer names each cell's frame (docs/loop-comparison.md). The rebuilt strip names its own cells —
# the same frames, turned, under the same crop.
diff --git a/tests/video/test_no_repeat_default.py b/tests/video/test_no_repeat_default.py
new file mode 100644
index 0000000..689ee14
--- /dev/null
+++ b/tests/video/test_no_repeat_default.py
@@ -0,0 +1,286 @@
+# SPDX-License-Identifier: Apache-2.0
+"""No picture shown again by default, on every way the engine delivers a loop (docs/loop-repair.md section 7): a loop's
+last cells and the step across its wrap are read and filled like any held run; the cut is read again once its repairs
+have run; an alignment aligns the cut as filmed (a filled loop is cut again with the fill off, or the set stops naming
+it) and fills what it delivers at the end, at a rate of its own where one is asked; a set cuts the directions it aligns
+as filmed and cuts again, filled, the ones no alignment took. A hold the motion means stays and is listed in the strip
+(`holds`); a loop with no held cell is delivered as before.
+
+The interpolator is `Between`, a stand-in that draws the synthetic clip again at the time asked for."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+from sprite_gen.video import align, held_fill
+from sprite_gen.video import loop as loop_mod
+from tests.picture_digest import picture_digest
+from tests.video.held_fill_inputs import N, Between, save, shown_again, walk, walk_at
+
+
+def _cut(tmp_path: Path, name: str, frames: list[Image.Image], *, length: int, fill_held: str = "auto", **kw) -> Path:
+ keyed = save(frames, tmp_path / f"{name}-keyed")
+ 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", fill_held=fill_held, **kw)
+ return out
+
+
+def _cells(d: Path) -> list[Image.Image]:
+ return [Image.open(p).convert("RGBA") for p in sorted((d / "cycle").glob("frame-*.png"))]
+
+
+def _meta(d: Path) -> dict:
+ return json.loads((d / "walk.strip.json").read_text())
+
+
+def _shown_again(frames: list[Image.Image]) -> list[int]:
+ """The cells that show the picture of the cell before them, round a loop."""
+ same = held_fill.same_steps(frames + frames[:1])
+ return [(k + 1) % len(frames) for k, s in enumerate(same) if s]
+
+
+HELD = {5: 2} # the walk's sixth frame shown twice: a clip that stalls once a cycle
+
+
+def _held_clip() -> list[Image.Image]:
+ return shown_again(walk(N + 6), HELD)
+
+
+def _between() -> Between:
+ return Between(walk_at, [k / 4 for k in range(4 * (N + 6))], period=N)
+
+
+# --- video-loop: the loop's last cells and its wrap ---------------------------------------------------------------
+
+
+def test_a_loop_cut_whose_last_cells_show_one_picture_is_delivered_with_none_shown_again(tmp_path):
+ # The cut's last two cells show one picture (frame 22 shown twice): before, kept as filmed, "the loop's last cells".
+ frames = shown_again(walk(N + 6), {N - 2: 2})
+ d = _cut(tmp_path, "end", frames, length=N, interpolate=_between())
+ cells = _cells(d)
+ assert _shown_again(cells) == []
+ held = _meta(d)["held_fill"]
+ assert held["made"] == [N - 1] and held["before"]["held_runs"] == [{"start": N - 2, "length": 2, "filled": True, "made": [N - 1]}]
+ assert cells[0].tobytes() == frames[0].tobytes()
+
+
+def test_a_loop_cut_a_cell_too_long_has_its_last_cell_made_between_and_its_first_kept(tmp_path):
+ # The cut runs one frame past the cycle: its last cell shows its first cell's picture again, across the wrap.
+ frames = walk(N + 6)
+ d = _cut(tmp_path, "long", frames, length=N + 1, interpolate=_between())
+ cells = _cells(d)
+ assert _shown_again(cells) == [] and len(cells) == N + 1
+ held = _meta(d)["held_fill"]
+ assert held["before"]["wrap_held"] is True and held["before"]["wrap"]["made"] == [N]
+ assert cells[0].tobytes() == frames[0].tobytes()
+
+
+def test_the_cut_is_read_again_after_its_repairs_and_a_run_they_left_is_made():
+ # A repair that gives a cell way to the frame beside it leaves that frame shown twice; read again, it is made.
+ frames = [walk_at(t) for t in range(N)]
+ _, record = held_fill.fill(frames, _between(), ring=True)
+ assert record["made"] == []
+ repaired = list(frames)
+ repaired[9] = repaired[8]
+ out, again = held_fill.again(repaired, _between(), record, ring=True)
+ assert again is not None and again["made"] == [9] and out[9].tobytes() == walk_at(9).tobytes()
+ # a cell a repair already gave way, its frame between refused, is not tried again
+ out, again = held_fill.again(repaired, _between(), record, ring=True, skip=[9])
+ assert again is None and out[9].tobytes() == frames[8].tobytes()
+
+
+def test_the_holds_the_motion_means_are_kept_and_listed_in_the_strip(tmp_path):
+ # Frame 5 shown four times: longer than a drawing on threes, the motion's own hold.
+ frames = shown_again(walk(N + 6), {5: 4})
+ d = _cut(tmp_path, "hold", frames, length=N + 3, interpolate=_between())
+ meta = _meta(d)
+ assert meta["held_fill"]["made"] == [] and [r["start"] for r in meta["held_fill"]["held_runs"]] == [5]
+ assert meta["holds"] == [{"from": 5, "to": 8, "kind": "motion-hold",
+ "reason": meta["held_fill"]["before"]["held_runs"][0]["why"]}]
+ assert [c.tobytes() for c in _cells(d)[5:9]] == [frames[5].tobytes()] * 4
+
+
+def test_a_loop_records_what_its_cut_was_asked_and_is_cut_again_from_it_the_same(tmp_path):
+ frames = _held_clip()
+ keyed = save(frames, tmp_path / "k")
+ first = loop_mod.run_loop(keyed, tmp_path / "a", 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=N + 1,
+ anchor="none", repair="off", interpolate=_between())
+ report = json.loads(Path(first["report"]).read_text())
+ assert report["cut_args"]["fill_held"] == "auto" and report["cut_args"]["length"] == N + 1
+ again = loop_mod.cut_again(report, tmp_path / "b", report_path=tmp_path / "b.json", fill_held="off")
+ assert again["held_fill"]["made"] == [] and [r["start"] for r in again["held_fill"]["held_runs"]] == [5]
+ assert [c.tobytes() for c in _cells(tmp_path / "b")] == [f.tobytes() for f in frames[: N + 1]]
+ with pytest.raises(ValueError, match="no cut_args"):
+ loop_mod.cut_again({k: v for k, v in report.items() if k != "cut_args"}, tmp_path / "c", report_path=tmp_path / "c.json")
+
+
+def test_an_effect_s_lifetime_names_its_held_cells(tmp_path, capsys):
+ import shutil
+
+ from tests.video.test_effect import cut, lifetime_frames
+
+ keyed = lifetime_frames(tmp_path)
+ shutil.copyfile(keyed / "frame-040.png", keyed / "frame-041.png") # the burst stalls a frame
+ cut(keyed, tmp_path / "out")
+ assert "of the effect's lifetime show one picture" in capsys.readouterr().err
+
+
+# --- video-cycle-align: the cut as filmed in, no picture shown again out ------------------------------------------
+
+
+def test_an_aligned_set_whose_cuts_hold_a_picture_twice_delivers_none_shown_again(tmp_path):
+ clip = _held_clip()
+ dirs = [_cut(tmp_path, n, c, length=N + 1, fill_held="off") for n, c in (("A", clip), ("B", clip))]
+ report = align.align_set(dirs, interpolate=_between())
+ for d, row in zip(dirs, report["loops"]):
+ cells = _cells(d)
+ assert len(cells) == N + 1 and _shown_again(cells) == []
+ meta = _meta(d)
+ # the strip's record is the alignment's, not the cut's
+ assert meta["held_fill"]["made"] and meta["held_fill"] == row["held_fill"] and meta["holds"] == []
+ assert any("held_fill" in c for c in meta["cycle_align"]["cells_from"])
+
+
+def test_the_alignment_cuts_a_filled_loop_again_with_the_fill_off_and_aligns_the_frames_as_filmed(tmp_path):
+ clip = _held_clip()
+ dirs = [_cut(tmp_path, n, c, length=N + 1, interpolate=_between()) for n, c in (("A", clip), ("B", clip))]
+ assert all(_meta(d)["held_fill"]["made"] == [6] for d in dirs) # video-loop on its own fills, a loop delivered
+ report = align.align_set(dirs, interpolate=_between())
+ for d, row in zip(dirs, report["loops"]):
+ source = sorted((d / align.SOURCE_DIR).glob("frame-*.png"))
+ # the frames aligned are the cut as filmed: frame 5 shown twice, not the frame made between
+ assert Path(source[6]).read_bytes() == Path(source[5]).read_bytes()
+ assert row["cut_again"]["made_before"] == [6] and row["cut_again"]["fill_held"] == "off"
+ assert not align.filled(json.loads((d / align.SOURCE_DIR / "walk.strip.json").read_text()))
+ assert _shown_again(_cells(d)) == []
+ again = align.align_set(dirs, interpolate=_between()) # a second alignment reads the staged cut, cutting nothing
+ assert all("cut_again" not in r for r in again["loops"])
+
+
+def test_a_filled_loop_whose_cut_cannot_be_made_again_stops_the_set_naming_it(tmp_path):
+ clip = _held_clip()
+ dirs = [_cut(tmp_path, n, c, length=N + 1, interpolate=_between()) for n, c in (("A", clip), ("B", clip))]
+ report_path = dirs[1] / "walk.loop.report.json"
+ report = json.loads(report_path.read_text())
+ report.pop("cut_args") # a report from before cuts recorded what they were asked
+ report_path.write_text(json.dumps(report))
+ with pytest.raises(SystemExit, match=r"no cut_args.*video-loop --fill-held off"):
+ align.align_set(dirs, interpolate=_between())
+ assert not (dirs[1] / align.SOURCE_DIR / "walk.strip.json").exists()
+
+
+def test_an_aligned_set_asked_for_at_a_rate_of_its_own_is_given_frames_between_every_loop_alike(tmp_path):
+ clip = walk(N + 6)
+ dirs = [_cut(tmp_path, n, c, length=N, fill_held="off") for n, c in (("A", clip), ("B", clip))]
+ report = align.align_set(dirs, interpolate=_between(), out_fps=60.0)
+ assert report["out_fps"] == 60.0
+ for d in dirs:
+ cells = _cells(d)
+ meta = _meta(d)
+ assert len(cells) == 60 and _shown_again(cells) == []
+ assert meta["out_fps"] == 60.0 and meta["source_fps"] == 24.0 and meta["cycle_seconds"] == pytest.approx(1.0)
+ again = align.align_set(dirs, interpolate=_between()) # aligned again from cycle.source/ at the clip's rate
+ assert again["lengths"] == [N, N] and "out_fps" not in _meta(dirs[0])
+ with pytest.raises(SystemExit, match="is not above"):
+ align.align_set(dirs, interpolate=_between(), out_fps=12.0)
+
+
+# Pinned on the engine before this change (4f5ccd5): a set with no held cell is aligned as it was.
+UNHELD_ALIGNED = "68abe86925f7ccd67dc86ed7b6d8214a4d3d7b0b3a3429e6c8b4ed8215e73d4c"
+
+
+def test_an_aligned_set_with_no_held_cell_is_delivered_as_before(tmp_path):
+ clip = walk(N + 6)
+ dirs = [_cut(tmp_path, n, c, length=L, fill_held="off") for n, c, L in (("A", clip, N), ("B", clip, N + 4))]
+ align.align_set(dirs, interpolate=_between())
+ pictures = picture_digest(sorted(p for d in dirs for p in (d / "cycle").glob("frame-*.png")))
+ assert pictures == UNHELD_ALIGNED
+ off = [_cut(tmp_path, n + "off", c, length=L, fill_held="off") for n, c, L in (("A", clip, N), ("B", clip, N + 4))]
+ align.align_set(off, interpolate=_between(), fill_held="off")
+ assert picture_digest(sorted(p for d in off for p in (d / "cycle").glob("frame-*.png"))) == pictures
+
+
+# --- video-set: the directions it aligns cut as filmed, the ones no alignment took cut again filled ----------------
+
+
+def _set(monkeypatch, tmp_path, *, align_result, out_fps=None):
+ from sprite_gen.video import batch
+
+ seen: list[dict] = []
+ again: list[dict] = []
+ monkeypatch.setattr(batch.frames_mod, "run_frames", lambda clip, out, **kw: {
+ "fps": 24, "frames": 10, "alpha_zero_pct_min": 50, "alpha_zero_pct_max": 60, "keyed_dir": str(out)})
+ lp = {"cycle": {"length": 10, "period_global": 10, "ratio": 0.2}, "resampled_seam_ratio": 0.2, "n_out": 10,
+ "gif": {"file": "loop.gif"}, "webp": {"file": "loop.webp"}, "strip": {"path": "strip.png"},
+ "held_fill": {"cells": 10, "poses": 9, "held_runs": [{"start": 3, "length": 2}], "made": [],
+ "before": {"cells": 10, "poses": 9, "held_runs": [{"start": 3, "length": 2, "filled": False,
+ "why": "--fill-held off"}]}}}
+
+ def run_loop(*a, **kw):
+ seen.append(kw)
+ Path(kw["report_path"]).write_text(json.dumps({"cut_args": {}, "frames_dir": str(a[0])}))
+ return lp
+
+ def cut_again(report, out_dir, *, report_path, **asked):
+ again.append(asked)
+ return {**lp, "held_fill": {**lp["held_fill"], "made": [4], "held_runs": [], "poses": 10}}
+
+ def video(image, prompt, out, report, **kw):
+ out.write_bytes(b"test-video")
+ report.write_text(json.dumps({"prompt": prompt}))
+ return 0
+
+ monkeypatch.setattr(batch.loop_mod, "run_loop", run_loop)
+ monkeypatch.setattr(batch.loop_mod, "cut_again", cut_again)
+ monkeypatch.setattr(batch.align_mod, "align_set", align_result)
+ monkeypatch.setattr(batch, "_staggered_start", lambda gap: None)
+ stills = {}
+ for view in ("front", "back"):
+ stills[view] = tmp_path / f"{view}.png"
+ still = Image.new("RGBA", (64, 64), (0, 255, 0, 255))
+ still.paste((200, 80, 30, 255), (24, 16, 40, 56))
+ still.save(stills[view])
+ result = batch.run_set(bases=stills, states=["walk", "idle"], root=tmp_path / "set", character=None, duration=3,
+ resolution="720p", key="green", concurrency=1, force=False, gap=0, video_runner=video,
+ out_fps=out_fps)
+ return result, seen, again
+
+
+def test_a_set_cuts_the_directions_it_aligns_as_filmed_and_hands_the_alignment_the_fill_and_the_rate(monkeypatch, tmp_path):
+ asked: list[dict] = []
+
+ def align_set(dirs, **kw):
+ asked.append(kw)
+ return {"length": 10, "lengths": [10, 10], "between": "auto", "made_by_rife": 0, "replaced": 0, "retake": [],
+ "unnamed_feet": [], "feet_given": {}, "warnings": [],
+ "loops": [{"from": 10, "to": 10, "made_by_rife": 0, "turned_by": 0, "turned_on": "stride", "start_foot": None,
+ "start_foot_source": None, "seam_ratio": 1.0, "retake": None, "strip": {"frames": 10},
+ "held_fill": {"cells": 10, "poses": 10, "held_runs": [], "made": [4],
+ "before": {"cells": 10, "poses": 9, "held_runs": []}}} for _ in dirs]}
+
+ # Before, --out-fps with an alignment was refused ("pass --align-cycles off with it").
+ result, seen, again = _set(monkeypatch, tmp_path, align_result=align_set, out_fps=60.0)
+ by = {(kw["state"], kw["view"]): (kw["fill_held"], kw["out_fps"]) for kw in seen}
+ assert by == {("walk", "front"): ("off", None), ("walk", "back"): ("off", None),
+ ("idle", "front"): ("auto", 60.0), ("idle", "back"): ("auto", 60.0)}
+ assert [(kw["fill_held"], kw["out_fps"]) for kw in asked] == [("auto", 60.0)]
+ assert again == []
+ walks = [r for r in result["items"] if r["state"] == "walk"]
+ assert all(r["loop"]["poses"] == "10/10" and r["loop"]["held_fill"]["made"] == [4] for r in walks)
+
+
+def test_a_direction_cut_for_an_alignment_that_did_not_take_it_is_cut_again_filled(monkeypatch, tmp_path):
+ def align_set(dirs, **kw):
+ raise SystemExit("video-cycle-align: refused for the test")
+
+ result, seen, again = _set(monkeypatch, tmp_path, align_result=align_set)
+ assert again == [{"fill_held": "auto", "out_fps": None}] * 2
+ walks = [r for r in result["items"] if r["state"] == "walk"]
+ assert all(r["loop"]["cut_again"]["why"] == "not aligned" and r["loop"]["held_fill"]["made"] == [4] for r in walks)