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): a loop whose foot the view cannot name is told it, one loop at a time (--foot, video-set --align-foot); the report lists it under unnamed_feet with its two strike frames

Soohong Kimad656695e485
diff --git a/sprite_gen/video/align.py b/sprite_gen/video/align.py
index c10bc63..28a9cea 100644
--- a/sprite_gen/video/align.py
+++ b/sprite_gen/video/align.py
@@ -36,6 +36,13 @@ it is, `--cycles <loop>=k` takes one cycle — a k-th of it, from the start whos
is the most like it — out of the loop as filmed (`take_cycle`) and aligns that. Nothing changes the
number of cycles in a loop but `--cycles`.
+Where a loop's view cannot tell its feet apart (`start_foot` null, with `foot_why`), it starts on its
+larger strike, and the report names it under `unnamed_feet` with its two strike frames as they now
+stand in `cycle/` (`candidates`, the first being the frame it starts on) — for whoever looks, a
+person or a vision model. The answer comes back the same way as a count: `--foot <loop>=left|right`
+says which own foot lands on the first candidate, and that loop alone starts as `--start-foot` lands
+(half a cycle on, where the other foot lands first), recorded `start_foot_source: "given"`.
+
A set that needs a made frame where no RIFE is installed raises `rife.RifeNotInstalled` with
nothing rewritten: this command fails on it, `video-set` skips the alignment with a warning.
"""
@@ -297,7 +304,8 @@ def foot_strike_start(frames: list[Image.Image], *, view: str | None = None) ->
return foot_strike(frames, view=view)["start"]
-def foot_strike(frames: list[Image.Image], *, view: str | None = None, foot: str = START_FOOT) -> dict[str, Any]:
+def foot_strike(frames: list[Image.Image], *, view: str | None = None, foot: str = START_FOOT,
+ given: str | None = None) -> dict[str, Any]:
"""Where a loop starts: the frame a heel has just landed, read off one signal smoothed over its
neighbours (1-2-1), never off the frame's top edge, which a long ear or a hat's point owns.
@@ -318,9 +326,17 @@ def foot_strike(frames: list[Image.Image], *, view: str | None = None, foot: str
on (not the other peak: one step can stride much less than the other, or not peak at all).
With the loop's `view` (`side@right`, `front`, …) the one where `foot` lands is taken
(`strike_foot`); without a view, or where the view's cue cannot tell, the larger, the first on
- a tie, and `start_foot` is None with the reason."""
+ a tie, and `start_foot` is None with the reason.
+
+ `given` is the own foot that lands on the larger strike (`strikes[0]`) as whoever looked at the
+ loop saw it (`--foot`): the loop starts where `foot` lands — that strike or the one half a cycle
+ on — with `start_foot_source` "given", whatever the view's cue says; where the cue named the feet
+ otherwise, `foot_disagrees` says so. `start_foot_source` is "engine" where the cue named them,
+ None where nobody did."""
if foot not in handed_mod.SIDES:
raise ValueError(f"foot must be left or right, not {foot!r}")
+ if given is not None and given not in handed_mod.SIDES:
+ raise ValueError(f"the given foot must be left or right, not {given!r}")
sig = strike_signals(frames)
swing = legs_mod.swings(sig)
legs = legs_mod.legs_by(sig)
@@ -336,17 +352,28 @@ def foot_strike(frames: list[Image.Image], *, view: str | None = None, foot: str
first = max(range(n), key=lambda k: smooth[k])
second = (first + n // 2) % n
out: dict[str, Any] = {"start": first, "by": by, "stride_swing": round(swing["stride"], 4), "reach_swing": round(swing["reach"], 4),
- "strikes": [first, second], "start_foot": None}
+ "strikes": [first, second], "start_foot": None, "start_foot_source": None}
if view is None:
- return {**out, "foot_why": "no view given for this loop"}
- if by == "body_low":
- return {**out, "foot_why": f"no legs to read: the foot band swings {swing['stride']:.3f} of the body's height "
- f"(legs from {STRIDE_MIN}), the lowest row {swing['reach']:.3f} (from {REACH_MIN})"}
- found = strike_foot(frames, (first, second), name, facing or None)
- if found["feet"] is None:
- return {**out, "foot": found, "foot_why": found["why"]}
- start = (first, second)[found["feet"].index(foot)]
- return {**out, "start": start, "start_foot": foot, "foot": found}
+ read: dict[str, Any] = {**out, "foot_why": "no view given for this loop"}
+ elif by == "body_low":
+ read = {**out, "foot_why": f"no legs to read: the foot band swings {swing['stride']:.3f} of the body's height "
+ f"(legs from {STRIDE_MIN}), the lowest row {swing['reach']:.3f} (from {REACH_MIN})"}
+ else:
+ found = strike_foot(frames, (first, second), name, facing or None)
+ if found["feet"] is None:
+ read = {**out, "foot": found, "foot_why": found["why"]}
+ else:
+ read = {**out, "start": (first, second)[found["feet"].index(foot)], "start_foot": foot, "start_foot_source": "engine", "foot": found}
+ if given is None:
+ return read
+ feet = [given, next(s for s in handed_mod.SIDES if s != given)]
+ told = {**{k: v for k, v in read.items() if k != "foot_why"}, "start": (first, second)[feet.index(foot)], "start_foot": foot,
+ "start_foot_source": "given", "foot_given": feet}
+ if read["start_foot"] is None:
+ told["foot_unnamed_why"] = read["foot_why"]
+ elif read["foot"]["feet"] != feet:
+ told["foot_disagrees"] = read["foot"]["feet"]
+ return told
def _ring(frames: list[Image.Image]) -> np.ndarray:
@@ -419,27 +446,35 @@ def _suspect_line(entry: dict[str, Any]) -> str:
return f"{entry['dir']}: may hold " + "; or ".join(parts)
-def _resolve_cycles(cycles: dict[str, int] | None, loops: list[tuple[Path, Path, dict[str, Any], float]]) -> dict[int, int]:
- """`--cycles` keys to loop positions: a key names a loop by its directory, its strip's name, its
- directory's name or — for a directory named `loop` (a video-set item) — its parent's name, and
- must name exactly one."""
- out: dict[int, int] = {}
- for key, k in (cycles or {}).items():
- if k not in CYCLES:
- raise SystemExit(f"video-cycle-align: --cycles {key}={k}: a loop holds {', '.join(map(str, CYCLES))} cycles here")
+def _resolve_loops(flag: str, given: dict[str, Any] | None, loops: list[tuple[Path, Path, dict[str, Any], float]],
+ allowed: tuple[Any, ...]) -> dict[int, Any]:
+ """`--cycles` or `--foot` keys to loop positions: a key names a loop by its directory, its strip's
+ name, its directory's name or — for a directory named `loop` (a video-set item) — its parent's
+ name, and must name exactly one; its value must be one of `allowed`."""
+ out: dict[int, Any] = {}
+ for key, value in (given or {}).items():
+ if value not in allowed:
+ raise SystemExit(f"video-cycle-align: {flag} {key}={value}: "
+ + (f"a loop holds {', '.join(map(str, CYCLES))} cycles here" if flag == "--cycles"
+ else f"the foot that lands on the loop's first strike is one of {', '.join(allowed)}"))
path = Path(key).expanduser()
hits = [i for i, (d, meta_path, _, _) in enumerate(loops)
if (path.exists() and path.resolve() == d)
or key in (meta_path.name[: -len(".strip.json")], d.name) or (d.name == "loop" and key == d.parent.name)]
hits = sorted(set(hits))
if len(hits) != 1:
- raise SystemExit(f"video-cycle-align: --cycles {key}={k} names {len(hits)} of the --loop-dir given; name one by its directory")
+ raise SystemExit(f"video-cycle-align: {flag} {key}={value} names {len(hits)} of the --loop-dir given; name one by its directory")
if hits[0] in out:
- raise SystemExit(f"video-cycle-align: --cycles names {loops[hits[0]][0]} twice")
- out[hits[0]] = k
+ raise SystemExit(f"video-cycle-align: {flag} names {loops[hits[0]][0]} twice")
+ out[hits[0]] = value
return out
+def _resolve_cycles(cycles: dict[str, int] | None, loops: list[tuple[Path, Path, dict[str, Any], float]]) -> dict[int, int]:
+ """`--cycles` keys to loop positions (`_resolve_loops`)."""
+ return _resolve_loops("--cycles", cycles, loops, CYCLES)
+
+
def _loop_files(loop_dir: Path) -> tuple[Path, dict[str, Any]]:
metas = sorted(loop_dir.glob("*.strip.json"))
if len(metas) != 1:
@@ -512,6 +547,16 @@ def _rebuild(loop_dir: Path, meta_path: Path, meta: dict[str, Any], frames: list
return merged
+def _unnamed_foot(row: dict[str, Any]) -> dict[str, Any]:
+ """A loop whose foot nobody named, for whoever looks: its two strikes as frames of the rebuilt
+ `cycle/` (the first is the frame it starts on), why the engine could not say, and the `--foot`
+ arguments that settle it — which own foot lands on the first."""
+ cycle = Path(row["dir"]) / "cycle"
+ return {"dir": row["dir"], "name": row["name"], "view": row["view"], "foot_why": row["foot_why"],
+ "candidates": [{"strike": n, "frame": k, "path": str(cycle / f"frame-{k:03d}.png")} for n, k in enumerate(row["strikes"])],
+ "settle": [f"--foot {row['dir']}={s}" for s in handed_mod.SIDES]}
+
+
def _fault_line(name: str, m: dict[str, Any]) -> str:
"""A made frame's faults, in words, and what became of it."""
what = [*([f"has {100 * m['dark_excess']:.2f} % more dark pixels inside the body than either source frame beside it — a smear"]
@@ -527,7 +572,7 @@ def _fault_line(name: str, m: dict[str, Any]) -> str:
def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate: rife_mod.Interpolate | None = None,
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) -> dict[str, Any]:
+ state: str | None = None, feet: dict[str, str] | 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.
@@ -537,7 +582,13 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:
to the number of cycles it holds, as someone who looked counted them: 1 aligns it as it is, more
takes one cycle out of it (`take_cycle`). A suspect with no count stops the set before anything
is rewritten (`multi_cycle` fail: `CycleSuspects`, the report written with `applied` false) or is
- aligned as it is with a warning (warn)."""
+ aligned as it is with a warning (warn).
+
+ `feet` maps a loop (named as `cycles` does) to the own foot that lands on its larger strike, as
+ whoever looked saw it (`--foot`): that loop starts where `start_foot` lands, recorded
+ `start_foot_source` "given" (`foot_strike`). A loop whose foot nobody named is listed under the
+ report's `unnamed_feet`, with its two strike frames in the rebuilt `cycle/` (`candidates`) and the
+ `--foot` arguments that settle it."""
if len(loop_dirs) < 1:
raise SystemExit("video-cycle-align: at least one --loop-dir")
if views is not None and len(views) != len(loop_dirs):
@@ -571,6 +622,7 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:
except ValueError as exc:
raise SystemExit(f"video-cycle-align: {exc}") from exc
given = _resolve_cycles(cycles, loops)
+ told = _resolve_loops("--foot", feet, loops, handed_mod.SIDES)
screens = [cycle_screen(frames, fps=fps, state=state or meta.get("state")) for (_, _, meta, _), frames in zip(loops, sources)]
suspects: list[dict[str, Any]] = []
taken: dict[int, dict[str, Any]] = {}
@@ -599,6 +651,7 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:
*([f"--between {between}"] if between != DEFAULT_BETWEEN else []), *([f"--start-foot {start_foot}"] if start_foot != START_FOOT else []),
*([f"--state {state}"] if state else []), *([f"--report {report_path}"] if report_path is not None else []),
*(f"--cycles {loops[i][0]}={k}" for i, k in sorted(given.items())),
+ *(f"--foot {loops[i][0]}={f}" for i, f in sorted(told.items())),
*(f"--cycles {e['dir']}=<{'|'.join(s.rpartition('=')[2] for s in e['settle'])}>" for e in stopped)]
command = " ".join(rerun)
message = ("video-cycle-align: " + "; ".join(_suspect_line(e) for e in stopped)
@@ -610,7 +663,7 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:
loop_mod.write_loop_report(report_path.expanduser().resolve(), {
"kind": "sprite-gen-video-cycle-align-report", "applied": False, "refused": "cycle-suspects", "why": message, "command": command,
"multi_cycle": multi_cycle, "lengths": [len(f) for f in sources], "fps": round(fps, 4), "suspects": suspects,
- "cycles_given": {str(loops[i][0]): k for i, k in given.items()}})
+ "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()}})
raise CycleSuspects(message, suspects, command)
cycle_warnings += [f"{_suspect_line(e)}; aligned as it is (--multi-cycle warn) — at the set's length it plays "
f"{max(row['cycles'] for row in e['candidates'])} times as fast as the rest if it does"
@@ -632,7 +685,7 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:
for i, ((d, *_), frames, view) in enumerate(zip(loops, sources, views or [None] * len(loops))):
try:
out, facts = resample(frames, target, lazy, between=between)
- strike = foot_strike(out, view=view, foot=start_foot)
+ strike = foot_strike(out, view=view, foot=start_foot, given=told.get(i))
except rife_mod.RifeNotInstalled as exc:
raise rife_mod.RifeNotInstalled(f"{d}: {exc}") from exc
except (ValueError, rife_mod.RifeUnavailable) as exc:
@@ -641,7 +694,10 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:
drawings = held_drawings(frames, fps=fps, clip=loops[i][2].get("drawings"), cut=loops[i][2].get("cycle_drawings"))
again = retake(drawings, facts, fps=fps)
record = {**facts, "drawings": drawings, "retake": again, "turned_by": start, "turned_on": strike["by"], "view": view, "start_foot": strike["start_foot"],
- **({"foot": strike["foot"]} if "foot" in strike else {}), **({"foot_why": strike["foot_why"]} if "foot_why" in strike else {}),
+ "start_foot_source": strike["start_foot_source"],
+ # the two strikes as they stand in the rebuilt cycle/: the larger first
+ "strikes": [(k - start) % target for k in strike["strikes"]],
+ **{key: strike[key] for key in ("foot", "foot_why", "foot_given", "foot_unnamed_why", "foot_disagrees") if key in strike},
"stride_swing": strike["stride_swing"], "reach_swing": strike["reach_swing"],
"fps": round(fps, 4), "source": SOURCE_DIR, "cycles_given": given.get(i), "cycle_screen": screens[i],
**({"cycle_taken": taken[i]} if i in taken else {}),
@@ -661,16 +717,21 @@ 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 = cycle_warnings + [_retake_line(r["dir"] if shared else r["name"], r["retake"]) for r in rows if r["retake"]] + warnings
- if len(rows) > 1 and views is None:
- warnings.append("no view given (--view): each loop starts on its larger strike, whichever foot that is")
- else:
- warnings += [f"{r['name']}: starts on its larger strike, foot not named — {r['foot_why']}" for r in rows
- if r["view"] is not None and r["start_foot"] is None]
+ unnamed = [_unnamed_foot(r) for r in rows if r["start_foot"] is None]
+ if len(rows) > 1 and views is None and unnamed:
+ warnings.append("no view given (--view): each loop " + ("not named by --foot " if told else "")
+ + "starts on its larger strike, whichever foot that is (`unnamed_feet`)")
+ warnings += [f"{r['dir'] if shared else r['name']}: starts on its larger strike, foot not named — {r['foot_why']}; look at "
+ f"cycle/frame-{r['strikes'][0]:03d}.png and say which own foot lands there: --foot {r['dir']}=left|right"
+ for r in rows if r["start_foot"] is None and r["view"] is not None]
+ warnings += [f"{r['dir'] if shared else r['name']}: --foot says {r['foot_given'][0]} lands on its larger strike, its view's "
+ f"{r['foot']['cue']} said {r['foot_disagrees'][0]}; started as given" for r in rows if r.get("foot_disagrees")]
report = {"kind": "sprite-gen-video-cycle-align-report", "applied": True, "length": target,
"length_rule": "requested" if length is not None else "median",
"between": between, "start_foot": start_foot, "retake": retakes, "warnings": warnings,
- "lengths": lengths, "multi_cycle": multi_cycle, "suspects": suspects,
+ "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),
"interpolator": ({"kind": "rife-ncnn-vulkan", **located[0]} if located else
{"kind": "injected"} if any(r.get("smear") for r in rows) else None),
@@ -693,6 +754,10 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
help="how many cycles a loop holds, as counted by whoever looked at it (repeatable; LOOP is its --loop-dir, its "
"strip's name or its directory's name): 1 aligns it as it is; 2 or 3 takes one cycle out of it as filmed "
"(cycle.source/) and aligns that. Only this changes the number of cycles in a loop")
+ parser.add_argument("--foot", action="append", default=[], metavar="LOOP=left|right",
+ help="which own foot lands on a loop's first strike candidate, as seen by whoever looked at it, for a loop the "
+ "report lists under `unnamed_feet` (repeatable; LOOP is named as for --cycles): that loop starts as "
+ "--start-foot lands, recorded start_foot_source given")
parser.add_argument("--multi-cycle", choices=MULTI_CYCLE, default="fail",
help="a loop that may hold two or three cycles (a half or a third of it returns to a pose on the motion's path) "
"and has no --cycles: fail (default) stops the set before anything is rewritten, the report naming it under "
@@ -719,21 +784,36 @@ def parse_cycles(values: list[str]) -> dict[str, int]:
return out
+def parse_feet(values: list[str], *, prog: str = "video-cycle-align", flag: str = "--foot") -> dict[str, str]:
+ """`--foot LOOP=left|right` values as {LOOP: foot}."""
+ out: dict[str, str] = {}
+ for v in values:
+ key, sep, foot = v.rpartition("=")
+ if not sep or not key or foot not in handed_mod.SIDES:
+ raise SystemExit(f"{prog}: {flag} expects LOOP=left|right (the own foot that lands on the loop's first strike), got {v!r}")
+ if key in out:
+ raise SystemExit(f"{prog}: {flag} names {key} twice")
+ out[key] = foot
+ return out
+
+
def run(**kwargs: object) -> int:
try:
report = align_set(list(kwargs["loop_dir"]), length=kwargs.get("length"), report_path=kwargs.get("report"), # type: ignore[arg-type]
between=str(kwargs.get("between") or DEFAULT_BETWEEN), views=kwargs.get("view"), # type: ignore[arg-type]
start_foot=str(kwargs.get("start_foot") or START_FOOT),
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")) # type: ignore[arg-type]
+ state=kwargs.get("state"), feet=parse_feet(list(kwargs.get("foot") or []))) # 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 — "
f"`{rife_mod.INSTALL_COMMAND}` (docs/loop-repair.md)") from exc
for line in report["warnings"]:
print(f"video-cycle-align: warning: {line}", file=sys.stderr)
- print(json.dumps({k: report[k] for k in ("length", "lengths", "cycles_given", "between", "made_by_rife", "replaced", "retake", "cycle_seconds")}
- | {"loops": [{k: r[k] for k in ("name", "from", "to", "made_by_rife", "turned_by", "turned_on", "start_foot", "seam_ratio")} for r in report["loops"]]},
+ print(json.dumps({k: report[k] for k in ("length", "lengths", "cycles_given", "feet_given", "between", "made_by_rife", "replaced", "retake",
+ "unnamed_feet", "cycle_seconds")}
+ | {"loops": [{k: r[k] for k in ("name", "from", "to", "made_by_rife", "turned_by", "turned_on", "start_foot", "start_foot_source",
+ "seam_ratio")} for r in report["loops"]]},
ensure_ascii=False, indent=2))
return 0
diff --git a/sprite_gen/video/batch.py b/sprite_gen/video/batch.py
index 43c5126..b5d833e 100644
--- a/sprite_gen/video/batch.py
+++ b/sprite_gen/video/batch.py
@@ -660,15 +660,23 @@ def _align_view(r: dict[str, Any]) -> str | None:
return r["direction"] + (f"@{r['turned']}" if r["direction"] in handed_mod.LATERAL_VIEWS else "")
-def align_gaits(results: list[dict[str, Any]], root: Path, mode: str, *, interpolate: Any = None, between: str = align_mod.DEFAULT_BETWEEN) -> dict[str, Any]:
+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]:
"""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.
Two cases skip the state instead of failing it, each loop keeping its own length, the record
saying why (`reason`) and a warning line naming what settles it: a frame is to be made and no
RIFE is installed (`rife-not-installed`), or a loop may hold two or three cycles and nobody has
- counted them (`cycle-suspects`, the loops under `suspects`; `video-cycle-align --cycles`)."""
+ counted them (`cycle-suspects`, the loops under `suspects`; `video-cycle-align --cycles`).
+
+ `feet` maps an item to the own foot that lands on its loop's first strike (`--align-foot`,
+ `video-cycle-align --foot`), handed to its state's alignment. A state that names loops whose foot
+ nobody named carries them under `unnamed_feet`; a foot given for an item no alignment took (the
+ item failed, or its state was not aligned) is named in its state's `feet_unused` and a warning."""
out: dict[str, Any] = {}
+ feet = dict(feet or {})
+ asked: dict[str, dict[str, str]] = {}
if mode == "off":
return out
by_state: dict[str, list[dict[str, Any]]] = {}
@@ -678,10 +686,12 @@ def align_gaits(results: list[dict[str, Any]], root: Path, mode: str, *, interpo
for state, rows in by_state.items():
if len(rows) < 2:
continue
+ asked[state] = {r["item"]: feet.pop(r["item"]) for r in rows if r["item"] in feet}
+ told = {str(Path(r["dir"]) / "loop"): asked[state][r["item"]] for r in rows if r["item"] in asked[state]}
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)
+ views=[_align_view(r) for r in rows], state=state, feet=told)
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}
@@ -702,12 +712,28 @@ def align_gaits(results: list[dict[str, Any]], root: Path, mode: str, *, interpo
continue
out[state] = {"ok": True, "applied": True, "length": report["length"], "lengths": report["lengths"], "between": report["between"],
"made_by_rife": report["made_by_rife"], "replaced": report["replaced"], "retake": report["retake"],
+ "unnamed_feet": report["unnamed_feet"], "feet_given": report["feet_given"],
"warnings": report["warnings"], "report": str(root / f"{state}.cycle-align.json")}
for line in report["warnings"]:
print(f"video-set: warning: {state}: {line}", file=sys.stderr)
for r, row in zip(rows, report["loops"]):
- r["loop"]["cycle_align"] = {k: row[k] for k in ("from", "to", "made_by_rife", "turned_by", "turned_on", "start_foot", "seam_ratio", "retake")}
+ 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"]
+ # a foot told for an item no alignment took (its state not aligned, or the item failed) is never dropped quietly
+ for state, told_items in asked.items():
+ if told_items and not out[state].get("applied"):
+ out[state]["feet_unused"] = told_items
+ for item, foot in feet.items():
+ r = next((r for r in results if r["item"] == item), None)
+ if r is None:
+ raise SystemExit(f"video-set: --align-foot {item}={foot} names no item of the set")
+ why = f"{item} failed" if not r.get("ok") else f"{r['state']} was not aligned (filmed in fewer than two directions)"
+ out.setdefault(r["state"], {"ok": True, "applied": False, "why": why}).setdefault("feet_unused", {})[item] = foot
+ for state, a in out.items():
+ if a.get("feet_unused"):
+ print(f"video-set: warning: {state}: --align-foot {', '.join(f'{i}={f}' for i, f in a['feet_unused'].items())} not applied "
+ f"({a.get('why') or a.get('error') or 'the item failed'})", file=sys.stderr)
return out
@@ -762,10 +788,13 @@ def run_set(
redraw_runner: Callable[..., int] = run_redraw_cli,
still_provider: str | None = None,
handed: list[Handed] | None = None,
+ align_feet: dict[str, str] | None = None,
) -> dict[str, Any]:
"""`bases` maps a view to its still; `facing` is right, left or `right,left` (`facings_of`), and a view filmed
both ways is keyed `view@right` and `view@left` (`resolve_bases`). `handed` (`handedness.parse`) puts each
- asymmetric item's side into every clip prompt; it refuses `facing_fix` mirror, which would move it."""
+ asymmetric item's side into every clip prompt; it refuses `facing_fix` mirror, which would move it.
+ `align_feet` (`--align-foot`) maps an item of a walk or run filmed in two or more directions to the
+ own foot that lands on its loop's first strike (`align_gaits`); any other item is refused up front."""
if align_cycles not in ALIGN_MODES:
raise SystemExit(f"video-set: --align-cycles must be one of {', '.join(ALIGN_MODES)}")
if anchor == "motion-auto" and any(not loop_mod.profile_for(state).gait for state in states):
@@ -788,6 +817,12 @@ def run_set(
raise SystemExit(f"video-set: base still for '{direction}' not found: {base}")
# (item, direction, state, facing, base); a set filmed both ways names a lateral item's facing
items = [(f"{d}-{f}-{s}" if both and f else f"{d}-{s}", d, s, f or facings[0], b) for d, f, b in views for s in states]
+ aligned_items = [i for i, _, s, _, _ in items if align_cycles == "auto" and loop_mod.profile_for(s).gait
+ and sum(1 for _, _, s2, _, _ in items if s2 == s) >= 2]
+ 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 "
+ f"more directions, --align-cycles auto): {', '.join(aligned_items) or 'none'}")
results: list[dict[str, Any]] = []
# States share a base. A run-local lock ensures exactly one vision call per
# side still and facing, even when several state workers reach it together.
@@ -811,7 +846,7 @@ def run_set(
results.append(r)
print(json.dumps({k: r[k] for k in ("item", "ok") if k in r} | ({"error": r["error"]} if not r.get("ok") else {"seam": r["loop"]["seam_ratio"]}), ensure_ascii=False), flush=True)
results.sort(key=lambda r: [i for i, *_ in items].index(r["item"]))
- aligned = align_gaits(results, root, align_cycles, interpolate=interpolate, between=align_between)
+ aligned = align_gaits(results, root, align_cycles, interpolate=interpolate, between=align_between, feet=align_feet)
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.
@@ -824,6 +859,8 @@ def run_set(
f"(the loops under `suspects` in {a['report']}, docs/loop-repair.md section 4)"
for st, a in aligned.items() if a.get("reason") == "cycle-suspects"]
warnings += [f"cycle-align:{st}: {line}" for st, a in aligned.items() for line in a.get("warnings", [])]
+ warnings += [f"cycle-align:{st}: --align-foot {item}={foot} not applied ({a.get('why') or a.get('error') or 'the item failed'})"
+ for st, a in aligned.items() for item, foot in a.get("feet_unused", {}).items()]
payload = {"kind": "sprite-gen-video-set-report", "root": str(root), "states": states, "facing": facing, "facing_fix": facing_fix, "directions": list(bases), **({"handed": [vars(h) for h in handed]} if handed else {}), "body_height": body_height, "ok": sum(1 for r in results if r.get("ok")), "failed": failed, "warnings": warnings, "items": results, "cycle_align": aligned}
atomic_write_text(root / "set.report.json", json.dumps(payload, ensure_ascii=False, indent=2) + "\n")
print(table)
@@ -868,6 +905,10 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--still-provider", help="image provider for the mid-step redraw (default: sprite-gen gen's own default)")
parser.add_argument("--align-cycles", choices=ALIGN_MODES, default="auto", help="auto (default): after the loops are cut, every walk/run filmed in two or more directions is resampled to the set's median cycle length and turned to start on a foot strike (video-cycle-align; RIFE makes only the frames between source frames — where no RIFE is installed the alignment is skipped with a warning and recorded); off: each loop keeps its own length")
parser.add_argument("--align-between", choices=align_mod.BETWEEN, default=align_mod.DEFAULT_BETWEEN, help="how the alignment fills a time between two source frames (video-cycle-align --between): auto (default) makes the frame with RIFE and takes the nearer source frame where it smeared or lost its outline, rife keeps every made frame, nearest takes the nearer source frame")
+ parser.add_argument("--align-foot", action="append", default=[], metavar="ITEM=left|right",
+ help="which own foot lands on the first strike of an item's loop (e.g. front-walk=left), for a loop the "
+ "alignment report lists under `unnamed_feet` (video-cycle-align --foot; repeatable): that loop starts as "
+ "the set's start foot lands, recorded start_foot_source given")
parser.add_argument("--force", action="store_true", help="regenerate clips that already exist")
@@ -885,6 +926,7 @@ def run(**kwargs: object) -> int:
align_between=str(kwargs.get("align_between") or align_mod.DEFAULT_BETWEEN),
walk_start=str(kwargs.get("walk_start") or "redraw"), still_provider=kwargs.get("still_provider"), # type: ignore[arg-type]
handed=handed_mod.parse_all(list(kwargs.get("handed") or [])) or None, # type: ignore[arg-type]
+ align_feet=align_mod.parse_feet(list(kwargs.get("align_foot") or []), prog="video-set", flag="--align-foot"),
)
return 0 if not payload["failed"] else 1
diff --git a/tests/video/test_cycle_align_foot.py b/tests/video/test_cycle_align_foot.py
new file mode 100644
index 0000000..2b26b3b
--- /dev/null
+++ b/tests/video/test_cycle_align_foot.py
@@ -0,0 +1,221 @@
+# SPDX-License-Identifier: Apache-2.0
+"""A loop whose foot the engine cannot name is told it, one loop at a time (docs/loop-repair.md
+section 4): the report lists it under `unnamed_feet` with its two strike frames in `cycle/`, and
+`--foot <loop>=left|right` — which own foot lands on the first — turns that loop alone to start as
+`--start-foot` lands, recorded `start_foot_source: "given"`.
+
+The figures are the drawn walker of test_cycle_align: its right heel lands at phase 0, its left at
+pi. Seen from the side its near (right) leg is drawn light over the shaded far leg, which names the
+feet; drawn unshaded, nothing tells them apart and the foot is left unnamed."""
+
+from __future__ import annotations
+
+import json
+import math
+from pathlib import Path
+
+import pytest
+
+from sprite_gen.video import align, batch
+from sprite_gen.video import loop as loop_mod
+
+from tests.video.test_cycle_align import _figure
+
+N = 12 # frames a cycle; the loops are cut at phase 5/12 so no loop starts on a strike as cut
+OUTPUTS = ("walk.strip.png", "walk.strip.json", "walk.gif", "walk.webp")
+
+
+def _cut(root: Path, name: str, **kw) -> Path:
+ keyed = root / f"{name}-keyed"
+ keyed.mkdir(parents=True)
+ for k in range(N + 6):
+ _figure(2 * math.pi * ((k + 5) % N) / N, **kw).save(keyed / f"{k:04d}.png")
+ out = root / 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=N, anchor="none", repair="off")
+ return out
+
+
+def _set(root: Path) -> list[Path]:
+ """Front and side (shaded): the feet named. W: a side view drawn unshaded — not named."""
+ return [_cut(root, "S", view="front"), _cut(root, "E", view="side"), _cut(root, "W", view="side", shaded=False)]
+
+
+VIEWS = ["front", "side@right", "side@right"]
+
+
+def _bytes(d: Path) -> dict[str, bytes]:
+ return {name: (d / name).read_bytes() for name in OUTPUTS} | {p.name: p.read_bytes() for p in sorted((d / "cycle").glob("frame-*.png"))}
+
+
+def _rows(report: dict) -> dict[str, dict]:
+ return {Path(r["dir"]).name: r for r in report["loops"]}
+
+
+def test_a_loop_whose_foot_is_not_named_is_listed_with_its_two_strike_frames(tmp_path):
+ dirs = _set(tmp_path)
+ report = align.align_set(dirs, views=VIEWS, report_path=tmp_path / "walk.cycle-align.json")
+ rows = _rows(report)
+ assert [rows[k]["start_foot_source"] for k in "SEW"] == ["engine", "engine", None]
+ assert rows["W"]["start_foot"] is None and "shade does not follow the step" in rows["W"]["foot_why"]
+ assert report["feet_given"] == {} and len(report["unnamed_feet"]) == 1
+ entry = report["unnamed_feet"][0]
+ assert entry["dir"] == str(dirs[2]) and entry["view"] == "side@right" and entry["foot_why"] == rows["W"]["foot_why"]
+ # the first candidate is the frame the loop starts on; the second is half a cycle on
+ assert [(c["strike"], c["frame"]) for c in entry["candidates"]] == [(0, 0), (1, N // 2)]
+ assert [c["path"] for c in entry["candidates"]] == [str(dirs[2] / "cycle" / f"frame-{k:03d}.png") for k in (0, N // 2)]
+ assert all(Path(c["path"]).is_file() for c in entry["candidates"])
+ assert entry["settle"] == [f"--foot {dirs[2]}=left", f"--foot {dirs[2]}=right"]
+ assert any("cycle/frame-000.png" in w and f"--foot {dirs[2]}=left|right" in w for w in report["warnings"])
+ written = json.loads((tmp_path / "walk.cycle-align.json").read_text())
+ assert written["unnamed_feet"] == report["unnamed_feet"]
+ assert json.loads((dirs[2] / "walk.strip.json").read_text())["cycle_align"]["start_foot_source"] is None
+
+
[email protected]("key", ["W", "dir"])
+def test_the_foot_given_for_one_loop_turns_that_loop_alone_half_a_cycle(tmp_path, key):
+ """Its left foot lands on the first strike: the loop starts half a cycle on, where its right
+ lands. The other two loops come out byte for byte as they were."""
+ dirs = _set(tmp_path)
+ align.align_set(dirs, views=VIEWS)
+ before = {d.name: _bytes(d) for d in dirs}
+ report = align.align_set(dirs, views=VIEWS, feet={"W" if key == "W" else str(dirs[2]): "left"})
+ rows = _rows(report)
+ for d in dirs[:2]:
+ assert _bytes(d) == before[d.name], d.name
+ w = rows["W"]
+ assert w["start_foot"] == "right" and w["start_foot_source"] == "given" and w["foot_given"] == ["left", "right"]
+ assert "shade does not follow the step" in w["foot_unnamed_why"] and "foot_why" not in w
+ assert w["strikes"] == [N // 2, 0]
+ for k in range(N): # frame k now is the frame half a cycle on as it was
+ assert (dirs[2] / "cycle" / f"frame-{k:03d}.png").read_bytes() == before["W"][f"frame-{(k + N // 2) % N:03d}.png"]
+ assert report["unnamed_feet"] == [] and report["feet_given"] == {str(dirs[2]): "left"}
+ assert not any("foot not named" in line for line in report["warnings"])
+ assert json.loads((dirs[2] / "walk.strip.json").read_text())["cycle_align"]["start_foot_source"] == "given"
+ # told again, the same loop: the answer is about the loop as filmed, so nothing moves
+ turned = _bytes(dirs[2])
+ align.align_set(dirs, views=VIEWS, feet={"W": "left"})
+ assert _bytes(dirs[2]) == turned
+
+
+def test_the_foot_given_that_lands_first_keeps_the_start_and_records_who_said_it(tmp_path):
+ dirs = _set(tmp_path)
+ align.align_set(dirs, views=VIEWS)
+ before = {d.name: _bytes(d) for d in dirs}
+ report = align.align_set(dirs, views=VIEWS, feet={"W": "right"})
+ assert {d.name: {k: v for k, v in _bytes(d).items() if k != "walk.strip.json"} for d in dirs} == \
+ {k: {n: b for n, b in v.items() if n != "walk.strip.json"} for k, v in before.items()}
+ w = _rows(report)["W"]
+ assert w["strikes"] == [0, N // 2] and w["start_foot_source"] == "given" and w["foot_given"] == ["right", "left"]
+
+
+def test_a_foot_given_against_the_views_own_reading_is_taken_and_named(tmp_path):
+ dirs = _set(tmp_path)
+ named = _rows(align.align_set(dirs, views=VIEWS))["E"]
+ landing = named["foot"]["feet"][0] # the own foot the shade says lands on the first strike
+ other = "left" if landing == "right" else "right"
+ report = align.align_set(dirs, views=VIEWS, feet={"E": other})
+ e = _rows(report)["E"]
+ assert e["start_foot_source"] == "given" and e["foot_disagrees"] == named["foot"]["feet"]
+ assert e["turned_by"] != named["turned_by"]
+ assert any(f"--foot says {other}" in line and f"said {landing}" in line for line in report["warnings"])
+
+
+def test_a_foot_for_no_loop_or_not_a_foot_is_refused_before_anything_is_rewritten(tmp_path):
+ dirs = _set(tmp_path)
+ align.align_set(dirs, views=VIEWS)
+ before = {d.name: _bytes(d) for d in dirs}
+ with pytest.raises(SystemExit, match="--foot nope=left names 0 of the --loop-dir given"):
+ align.align_set(dirs, views=VIEWS, feet={"nope": "left"})
+ with pytest.raises(SystemExit, match="--foot walk=left names 3"): # every loop's strip is `walk`
+ align.align_set(dirs, views=VIEWS, feet={"walk": "left"})
+ with pytest.raises(SystemExit, match="--foot W=up: the foot that lands on the loop's first strike is one of left, right"):
+ align.align_set(dirs, views=VIEWS, feet={"W": "up"})
+ with pytest.raises(SystemExit, match="--foot names .* twice"):
+ align.align_set(dirs, views=VIEWS, feet={"W": "left", str(dirs[2]): "left"})
+ assert {d.name: _bytes(d) for d in dirs} == before
+ for bad in (["W=up"], ["W"], ["=left"], ["W=left", "W=right"]):
+ with pytest.raises(SystemExit, match="--foot"):
+ align.parse_feet(bad)
+ with pytest.raises(SystemExit, match="names 0"):
+ align.main([*(f"--loop-dir={d}" for d in dirs), *(f"--view={v}" for v in VIEWS), "--foot", "nope=left"])
+ assert {d.name: _bytes(d) for d in dirs} == before
+
+
+def test_the_command_takes_foot(tmp_path, capsys):
+ dirs = _set(tmp_path)
+ assert align.main([*(f"--loop-dir={d}" for d in dirs), *(f"--view={v}" for v in VIEWS), "--foot", "W=left",
+ "--report", str(tmp_path / "r.json")]) == 0
+ out = json.loads(capsys.readouterr().out)
+ assert out["feet_given"] == {str(dirs[2]): "left"} and out["unnamed_feet"] == []
+ assert [r["start_foot_source"] for r in out["loops"]] == ["engine", "engine", "given"]
+
+
+def test_a_stopped_set_carries_the_foot_given_into_the_command_that_settles_it(tmp_path, monkeypatch):
+ dirs = _set(tmp_path)
+ real = align.cycle_screen
+
+ def suspect_w(frames, **kw):
+ screen = real(frames, **kw)
+ if len(frames) == N and frames[0].tobytes() == align._source_frames(dirs[2])[0].tobytes():
+ screen = {**screen, "suspects": [{"period": N // 2, "seconds": 0.25, "divisor": 2, "cycles": 2, "why": "a half returns"}]}
+ return screen
+
+ monkeypatch.setattr(align, "cycle_screen", suspect_w)
+ with pytest.raises(align.CycleSuspects) as stop:
+ align.align_set(dirs, views=VIEWS, feet={"W": "left"}, report_path=tmp_path / "r.json")
+ assert f"--foot {dirs[2]}=left" in stop.value.command
+ assert json.loads((tmp_path / "r.json").read_text())["feet_given"] == {str(dirs[2]): "left"}
+
+
+def _rows_for_set(root: Path) -> list[dict]:
+ rows = []
+ for item, kw in (("front-walk", dict(view="front")), ("side-walk", dict(view="side", shaded=False))):
+ d = root / item
+ _cut(d, "loop", **kw)
+ rows.append({"item": item, "direction": item.split("-")[0], "state": "walk", "turned": "right", "dir": str(d), "ok": True,
+ "loop": {"n_out": N}})
+ return rows
+
+
+def test_video_set_hands_an_items_foot_to_its_states_alignment(tmp_path, capsys):
+ rows = _rows_for_set(tmp_path)
+ first = batch.align_gaits(rows, tmp_path, "auto")
+ assert [e["dir"] for e in first["walk"]["unnamed_feet"]] == [str(tmp_path / "side-walk" / "loop")]
+ assert rows[1]["loop"]["cycle_align"]["start_foot_source"] is None
+ told = batch.align_gaits(rows, tmp_path, "auto", feet={"side-walk": "left"})
+ assert told["walk"]["applied"] and told["walk"]["unnamed_feet"] == []
+ assert told["walk"]["feet_given"] == {str(tmp_path / "side-walk" / "loop"): "left"}
+ assert [r["loop"]["cycle_align"]["start_foot_source"] for r in rows] == ["engine", "given"]
+ assert "feet_unused" not in told["walk"]
+ with pytest.raises(SystemExit, match="--align-foot back-walk=left names no item"):
+ batch.align_gaits(rows, tmp_path, "auto", feet={"back-walk": "left"})
+
+
+def test_video_set_names_a_foot_no_alignment_took(tmp_path, capsys):
+ rows = _rows_for_set(tmp_path)
+ rows.append({"item": "back-walk", "direction": "back", "state": "walk", "dir": str(tmp_path / "back-walk"), "ok": False, "error": "no clip"})
+ out = batch.align_gaits(rows, tmp_path, "auto", feet={"back-walk": "left"})
+ assert out["walk"]["applied"] and out["walk"]["feet_unused"] == {"back-walk": "left"}
+ assert "--align-foot back-walk=left not applied" in capsys.readouterr().err
+
+
+def test_video_set_refuses_a_foot_for_an_item_it_does_not_align_before_filming(tmp_path):
+ from PIL import Image
+
+ base = tmp_path / "front.png"
+ Image.new("RGBA", (8, 8), (255, 0, 0, 255)).save(base)
+ side = tmp_path / "side.png"
+ Image.new("RGBA", (8, 8), (0, 255, 0, 255)).save(side)
+
+ def no_film(*a, **kw):
+ raise AssertionError("refused before any clip is filmed")
+
+ common = dict(bases={"front": base, "side": side}, root=tmp_path / "set", character=None, duration=None, resolution="480p",
+ key="green", concurrency=1, force=False, gap=0.0, video_runner=no_film)
+ with pytest.raises(SystemExit, match="--align-foot front-idle=left: front-idle is not an item the set aligns"):
+ batch.run_set(states=["idle", "walk"], align_feet={"front-idle": "left"}, **common)
+ with pytest.raises(SystemExit, match="--align-foot front-walk=left: .*none"):
+ batch.run_set(states=["walk"], align_cycles="off", align_feet={"front-walk": "left"}, **common)
+ with pytest.raises(SystemExit, match="--align-foot expects ITEM|--align-foot expects LOOP"):
+ batch.run(base=[f"front={base}"], out_dir=tmp_path / "x", align_foot=["front-walk=up"])