Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
feat(video-chain): pieces of keyed clips on one canvas played as one move, where they join and when each frame shows being the caller's, the frames between, no picture shown again and the record the engine's
Soohong Kimf2dba1abb91f
diff --git a/sprite_gen/_modules.py b/sprite_gen/_modules.pyindex 3b09591..0c8af73 100644--- a/sprite_gen/_modules.py+++ b/sprite_gen/_modules.py@@ -37,6 +37,7 @@ MODULE_DOMAIN = {'sway_inspect': 'video','set_sheet': 'video','stop': 'video',+ 'chain': 'video','compare': 'video','restoration': 'video','source': 'video',diff --git a/sprite_gen/cli.py b/sprite_gen/cli.pyindex d01cb50..dc46512 100644--- a/sprite_gen/cli.py+++ b/sprite_gen/cli.py@@ -28,6 +28,7 @@ from sprite_gen.video import sway as video_swayfrom sprite_gen.video import sway_inspect as video_sway_inspectfrom sprite_gen.video import set_sheet as video_set_sheetfrom sprite_gen.video import stop as video_stop+from sprite_gen.video import chain as video_chainfrom sprite_gen.video import compare as video_comparefrom sprite_gen.video import restoration as video_restorationfrom sprite_gen.video import source as video_source@@ -402,6 +403,11 @@ COMMANDS: dict[str, tuple[str, Callable[[argparse.ArgumentParser], None], Callabvideo_stop.add_arguments,video_stop.run,),+ "video-chain": (+ "Pieces of keyed clips on one canvas played as one move: where they join and when each frame shows is yours, the frames between, no picture shown again and the record are the engine's.",+ video_chain.add_arguments,+ video_chain.run,+ ),# The face layer (docs/face-parts.md): a talking clip's lower face cut to be laid on body motions, and a line baked# with the pack's own player."video-face": (diff --git a/sprite_gen/video/chain.py b/sprite_gen/video/chain.pynew file mode 100644index 0000000..f47c934--- /dev/null+++ b/sprite_gen/video/chain.py@@ -0,0 +1,668 @@+# SPDX-License-Identifier: Apache-2.0+"""`sprite-gen video-chain` — pieces of keyed clips on one canvas played as one move, at the time the caller gives+(docs/video-pipeline.md section 9).++The caller says what only the scene knows: where the pieces join (each piece's frames, `--piece NAME=DIR:FROM:TO`) and+when each frame is shown. A pose alike does not tell a join (a body is joined where its path goes on), and the time is+read off a camera and an eye: the engine picks neither. What the engine does is what every other way out of it does:++- **The pieces** are one canvas and one key, or they are refused: every frame the same size, every piece keyed the same+ way and at one rate (`frames.report.json` beside the frames, or `--key` and `--fps` for a piece no report speaks for).+- **The chain** is the frames of the pieces in turn, numbered from 0, each join with the frames between it asks for+ (`--bridge K`, at k/(K+1)). A place on the chain is a number on that count.+- **The time** is one of three: the chain at its own rate; `--out-fps F`, evenly from its first frame to its last+ (`held_fill.times`); `--places FILE`, a place for each frame delivered. A place between two frames is made between them+ and judged (`held_fill.at_times`, `held_fill.judge`, again at another fraction of `align.RETIME_T` within half the+ place's spacing); one no frame made is taken for is the nearer frame, named.+- **The faults that refuse a frame** are every fault `judge` can find, or those `--refuse` names. Which of them are a+ fault in a material and which are the material's own (art painted without a line reads as outline loss on every frame+ made) is read off the material by whoever knows it, as a scene's time is: the engine does not pick. The judge and its+ bars do not change. `held`, the bar of a frame made off its time and the final reading refuse whatever `--refuse`+ says; a fault found and not refused stays on the frame's record (`kept_faults`) and on a `warning:` line naming it.+- **No picture shown again.** The frames delivered are read (`held_fill.same_steps`) and each run the list of holds meant+ (`--holds`) does not name is made again between the poses beside it (`held_fill.fill`, its rules for what it keeps;+ `--fill-held off` makes none). Then they are read as `inspect-holds` reads a delivery (`qa.holds.inspect`): a frame+ still showing the picture before it, on no list, fails the chain, by its number. A piece drawn on twos or threes+ (`held.measure`) is not filled: its holds are listed, or the chain fails. A chain that reads no frame against the frame+ before is an error, never a chain with none shown again (`qa.holds.NothingRead`); so is one none of whose joins can be+ read.+- **No RIFE:** a frame to make takes the nearer frame, with a `warning:` line and the record; `--gate` fails it.+- **The record** opens with the faults this run refused for (`refuse`), and gives each frame's `source` (`{piece, frame}`,+ or `{between: [a, b], t}`), its judged values and its refused tries; each join's pose distance, in steps of the two pieces (the median step between their neighbouring frames, the+ distance `video-stop` reads, `gait_fallback.poses`), and the frames within `--near` of it whose poses are closer. Those+ are told and never taken.++A failed chain's frames are left in `keyed.refused/` and no `keyed/` is handed over."""++from __future__ import annotations++import argparse+import json+import math+import shutil+import sys+import tempfile+from collections.abc import Collection, Sequence+from dataclasses import dataclass+from pathlib import Path+from typing import Any++from PIL import Image++from sprite_gen._deps import np+from sprite_gen.qa import holds as holds_mod+from sprite_gen.spec.runio import atomic_write_text, refuse_overlap+from sprite_gen.util.cli_kwargs import namespace_from_kwargs+from sprite_gen.util.console import utf8_streams+from sprite_gen.video import evidence as evidence_mod+from sprite_gen.video import gait_fallback+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 loop as loop_mod+from sprite_gen.video import rife as rife_mod+from sprite_gen.video.frames import KEYS_READ, refused_dir+from sprite_gen.video.interpolation_quality import ghost_screen++PROG = "video-chain"+REPORT_KIND = "sprite-gen-video-chain-report"+REPORT_NAME = "chain.report.json"+FRAMES_REPORT = "frames.report.json" # `video-frames`' report, beside its keyed/+KEYED = "keyed" # the folder a chain's frames are handed over in, as `video-frames` hands over its own+NEAR = 6 # how far either way of a join its closer poses are looked for, frames+NEAR_SHOWN = 5 # how many of them the record names+ROOM = 40 # px kept round the figures when they are read and made: RIFE reads the frame it is given, a canvas's empty rest with it+RATE_SAME = 1e-3 # two rates this near are one+EXIT_OK, EXIT_SHOWN_AGAIN, EXIT_ERROR = 0, 1, 2+++class ChainRefused(ValueError):+ """Pieces, a time or a reading the chain cannot be made from: exit EXIT_ERROR, nothing handed over."""+++@dataclass+class Piece:+ name: str+ folder: Path+ files: list[Path] # every frame of the clip, in name order: a join's closer poses may lie past the piece+ first: int+ last: int+ key: str | None+ fps: float | None+ start: int = 0 # the chain's number of its first frame++ @property+ def used(self) -> range:+ return range(self.first, self.last + 1)++ def source(self, frame: int) -> dict[str, Any]:+ return {"piece": self.name, "frame": frame}+++# --- the pieces -------------------------------------------------------------------------------------------------------++def _frames_report(folder: Path) -> dict[str, Any]:+ path = folder.parent / FRAMES_REPORT+ return json.loads(path.read_text(encoding="utf-8")) if folder.name == KEYED and path.is_file() else {}+++def _stated_key(report: dict[str, Any]) -> str | None:+ """The key a `video-frames` report says its frames were keyed on; a report that says only `auto` says none."""+ if report.get("alpha_mode") == "brightness":+ return "brightness"+ key = report.get("key_read") or report.get("key")+ return None if key in (None, "auto") else str(key)+++def read_piece(spec: str) -> Piece:+ """`NAME=DIR:FROM:TO`: frames FROM..TO, both ends in, counted from 0 in name order, of the keyed PNGs in DIR (or in its+ keyed/, a `video-frames` folder)."""+ name, eq, rest = spec.partition("=")+ parts = rest.rsplit(":", 2)+ if not eq or not name or len(parts) != 3:+ raise ChainRefused(f"--piece {spec!r}: NAME=DIR:FROM:TO")+ try:+ first, last = int(parts[1]), int(parts[2])+ except ValueError:+ raise ChainRefused(f"--piece {spec!r}: FROM and TO are whole frame numbers from 0") from None+ given = Path(parts[0]).expanduser().resolve()+ folder = given / KEYED if (given / KEYED).is_dir() else given+ files = sorted(folder.glob("*.png"))+ if not files:+ raise ChainRefused(f"piece {name}: no *.png frames in {folder}")+ if not 0 <= first <= last < len(files):+ raise ChainRefused(f"piece {name}: frames {first}..{last}, and {folder} holds frames 0..{len(files) - 1}")+ report = _frames_report(folder)+ return Piece(name, folder, files, first, last, _stated_key(report), report.get("fps"))+++def _one_key(pieces: Sequence[Piece], key: str | None) -> str:+ """The one key of `pieces`, each as its report says or as `key` (`--key`) says for one no report speaks for."""+ named = [(p.name, p.key) for p in pieces if p.key is not None] + ([("--key", key)] if key is not None else [])+ if len({k for _, k in named}) > 1:+ raise ChainRefused("the pieces are keyed differently (" + ", ".join(f"{n} {k}" for n, k in named) + "): a chain is one key")+ unknown = [p.name for p in pieces if p.key is None]+ if unknown and key is None:+ raise ChainRefused(f"no report says what {', '.join(unknown)} {'is' if len(unknown) == 1 else 'are'} keyed on (no "+ f"{FRAMES_REPORT} beside the frames, or one that says only auto): name it with --key")+ return named[0][1] # type: ignore[return-value]+++def _one_rate(pieces: Sequence[Piece], fps: float | None) -> float | None:+ """The pieces' one rate, as their reports say or as `fps` (`--fps`) says."""+ named = [(p.name, float(p.fps)) for p in pieces if p.fps] + ([("--fps", float(fps))] if fps else [])+ if any(abs(r - named[0][1]) > RATE_SAME for _, r in named):+ raise ChainRefused("the pieces are at different rates (" + ", ".join(f"{n} {r:g}" for n, r in named) + "): a chain plays at one")+ return named[0][1] if named else None+++def _bridges(given: Sequence[int], joins: int) -> list[int]:+ """Each join's frames between: one value for every join, or one a join in order."""+ if any(k < 0 for k in given):+ raise ChainRefused("--bridge: a number of frames between, 0 or more")+ if not given:+ return [0] * joins+ if not joins:+ raise ChainRefused("--bridge: one piece has no join")+ if len(given) == 1:+ return list(given) * joins+ if len(given) != joins:+ raise ChainRefused(f"--bridge given {len(given)} times, and the pieces have {joins} joins: once for all of them, or once for each")+ return list(given)+++def _read_places(path: Path) -> list[float]:+ """A place for each frame delivered: a JSON list, or an object's `places`."""+ try:+ data = json.loads(Path(path).expanduser().read_text(encoding="utf-8"))+ except (OSError, ValueError) as exc:+ raise ChainRefused(f"--places {path}: {exc}") from None+ places = data.get("places") if isinstance(data, dict) else data+ if not isinstance(places, list) or not places:+ raise ChainRefused(f"--places {path}: a list of places, or an object whose `places` is one")+ if not all(isinstance(p, (int, float)) and not isinstance(p, bool) and math.isfinite(p) for p in places):+ raise ChainRefused(f"--places {path}: every place is a number on the chain's count")+ return [float(p) for p in places]+++def _read_refuse(text: str | None) -> frozenset[str] | None:+ """`--refuse`'s faults, `held` always among them; None where it was not given (every fault refuses)."""+ if text is None:+ return None+ named = [name.strip() for name in text.split(",")]+ unknown = [name for name in named if name not in held_fill_mod.FAULTS]+ if unknown:+ raise ChainRefused(f"--refuse: {', '.join(repr(name) for name in unknown)} {'is' if len(unknown) == 1 else 'are'} no fault: "+ f"one of {', '.join(held_fill_mod.FAULTS)}")+ return frozenset(named) | {"held"}+++def _canvas_and_box(pieces: Sequence[Piece]) -> tuple[tuple[int, int], tuple[int, int, int, int] | None]:+ """The one size of every frame used, and the box of everything they draw with ROOM round it (None where they draw+ nothing). Refused where a frame is another size, or a piece is opaque (no key was taken off it)."""+ size = None+ box = None+ for p in pieces:+ keyed = False+ for k in p.used:+ with Image.open(p.files[k]) as raw:+ image = raw.convert("RGBA")+ if size is None:+ size = image.size+ elif image.size != size:+ raise ChainRefused(f"piece {p.name}'s frame {k} is {image.width}x{image.height} and the chain's first is "+ f"{size[0]}x{size[1]}: a chain is one canvas")+ alpha = image.getchannel("A")+ keyed = keyed or alpha.getextrema()[0] < 255+ b = alpha.getbbox()+ if b is not None:+ box = b if box is None else (min(box[0], b[0]), min(box[1], b[1]), max(box[2], b[2]), max(box[3], b[3]))+ if not keyed:+ raise ChainRefused(f"piece {p.name}'s frames are opaque: a chain is of keyed frames (video-frames)")+ assert size is not None+ if box is None:+ return size, None+ return size, (max(0, box[0] - ROOM), max(0, box[1] - ROOM), min(size[0], box[2] + ROOM), min(size[1], box[3] + ROOM))+++# --- the joins --------------------------------------------------------------------------------------------------------++def read_join(left: Piece, right: Piece, frames: dict[tuple[str, int], Image.Image], near: int) -> dict[str, Any]:+ """The join from `left`'s last frame into `right`'s first: the pose distance, in steps (the median step between+ neighbouring frames of the two pieces), and the pairs within `near` frames of it whose poses are closer, nearest+ first. `reads` false, with why, where a frame shows no figure or the pieces do not move. Told, never taken."""+ head = {"from": left.source(left.last), "into": right.source(right.first), "near": near}+ wanted = {(left.name, k) for k in left.used} | {(right.name, k) for k in right.used}+ around_l = [k for k in range(left.last - near, left.last + near + 1) if 0 <= k < len(left.files)]+ around_r = [k for k in range(right.first - near, right.first + near + 1) if 0 <= k < len(right.files)]+ files = {(p.name, k): p.files[k] for p, ks in ((left, around_l), (right, around_r)) for k in ks}+ keys = sorted(wanted | set(files))+ images = [frames[k] if k in frames else Image.open(files[k]).convert("RGBA") for k in keys]+ boxes = gait_fallback.subject_boxes(images)+ if np.isnan(boxes[:, 0]).all():+ return {**head, "reads": False, "why": "no frame shows a figure"}+ poses = dict(zip(keys, gait_fallback.poses(images, boxes)))+ bare = [k for k in ((left.name, left.last), (right.name, right.first)) if np.isnan(poses[k]).any()]+ if bare:+ return {**head, "reads": False, "why": f"no figure on {', '.join(f'{n} {k}' for n, k in bare)}"}++ def apart(a: tuple[str, int], b: tuple[str, int]) -> float:+ return float(np.nanmean(np.abs(poses[a] - poses[b])))++ neighbours = [apart((p.name, k), (p.name, k + 1)) for p in (left, right) for k in range(p.first, p.last)+ if not (np.isnan(poses[(p.name, k)]).any() or np.isnan(poses[(p.name, k + 1)]).any())]+ step = float(np.median(neighbours)) if neighbours else 0.0+ if not step > 0:+ return {**head, "reads": False, "why": "the pieces do not move: no step to read the join in"}+ at = apart((left.name, left.last), (right.name, right.first)) / step+ closer = []+ for i in around_l:+ for j in around_r:+ a, b = (left.name, i), (right.name, j)+ if (i, j) == (left.last, right.first) or np.isnan(poses[a]).any() or np.isnan(poses[b]).any():+ continue+ steps = apart(a, b) / step+ if steps < at:+ closer.append({"from": left.source(i), "into": right.source(j), "steps": round(steps, 4)})+ closer.sort(key=lambda c: (c["steps"], abs(c["from"]["frame"] - left.last) + abs(c["into"]["frame"] - right.first)))+ return {**head, "reads": True, "step": round(step, 6), "steps": round(at, 4), "closer": closer[:NEAR_SHOWN], "closer_found": len(closer)}+++# --- the frames -------------------------------------------------------------------------------------------------------++def _passed(attempt: dict[str, Any]) -> bool:+ return not attempt["faults"] and "window_over" not in attempt+++def _tries(how: dict[str, Any]) -> tuple[dict[str, Any] | None, list[dict[str, Any]]]:+ """A frame's tries (`held_fill._made`): the one taken, None where none was, and those refused."""+ tries = how.get("tries") or []+ return (tries[-1], tries[:-1]) if "taken" not in how and tries and _passed(tries[-1]) else (None, tries)+++def _judged(taken: dict[str, Any] | None) -> dict[str, Any]:+ """What the try taken for a frame gives its record: the values it was judged by, and the faults found and not refused."""+ if taken is None:+ return {"judged": None}+ return {"judged": taken["judged"], **({"kept_faults": taken["kept_faults"]} if "kept_faults" in taken else {})}+++def _nearest(frames: Sequence[Image.Image], at: Sequence[float]) -> tuple[list[Image.Image], dict[str, Any]]:+ """`held_fill.at_times`' answer with nothing to make frames with: each place the nearer frame, named."""+ near = [min(round(p), len(frames) - 1) for p in at]+ rows = [{"cell": k, "between": [math.floor(p), math.floor(p) + 1], "taken": near[k], "t": round(p - math.floor(p), 4), "tries": []}+ for k, p in enumerate(at) if abs(p - near[k]) > held_fill_mod.SNAP]+ return [frames[k] for k in near], {"made": 0, "shown_again": [r["cell"] for r in rows], "frames": rows, "source_frames": near}+++def _spacing(places: Sequence[float]) -> list[float]:+ """How far apart each place is from those beside it: the less of the two gaps that is not none, a frame where none is.+ A frame refused at its place is made again within half of this."""+ out = []+ for k, p in enumerate(places):+ gaps = [abs(p - places[j]) for j in (k - 1, k + 1) if 0 <= j < len(places) and places[j] != p]+ out.append(min(gaps) if gaps else 1.0)+ return out+++class _Maker:+ """Frames made between others, RIFE located once one is asked for; `missing` holds why none could be where RIFE is+ not installed, and every place then takes the nearer frame (`_nearest`)."""++ def __init__(self, interpolate: rife_mod.Interpolate | None, reads: bool, refuse: frozenset[str] | None):+ self.made_by: list[dict[str, str]] = []+ self.given = interpolate is not None+ self.lazy = loop_mod._located(interpolate, self.made_by)+ self.reads = reads+ self.refuse = refuse+ self.missing: dict[str, Any] | None = None++ def at(self, frames: list[Image.Image], at: Sequence[float], spacing: float | Sequence[float]) -> tuple[list[Image.Image], dict[str, Any]]:+ if self.missing is None:+ try:+ return held_fill_mod.at_times(frames, self.lazy, at, ring=False, spacing=spacing, reads=self.reads, refuse=self.refuse)+ except rife_mod.RifeNotInstalled as exc:+ self.missing = {"why": "RIFE is not installed", "rife": str(exc), "install": rife_mod.install_command()}+ return _nearest(frames, at)++ def fill(self, frames: list[Image.Image], same: list[bool], mode: str) -> tuple[list[Image.Image], dict[str, Any]]:+ out, record = loop_mod.fill_cut(frames, self.lazy, ring=False, same=same, mode=mode, hold=None, refuse=self.refuse)+ record.pop("interpolator", None) # this chain's, one for all it made: `named`+ if "unmade" in record and self.missing is None:+ self.missing = {k: record["unmade"][k] for k in ("why", "rife", "install")}+ return out, record++ def named(self) -> dict[str, Any] | None:+ if self.made_by:+ return {**self.made_by[0], **self.lazy.counts()} # type: ignore[attr-defined]+ return {"kind": "injected"} if self.given else None+++def _links(pieces: Sequence[Piece], bridges: Sequence[int], loaded: dict[tuple[str, int], Image.Image],+ maker: _Maker) -> list[dict[str, Any]]:+ """The chain, frame by frame: each a piece's (`source`, `file`, `image`), or one made between a join's two frames+ (`source` with `bridge`, `image`, its judged values and refused tries)."""+ links: list[dict[str, Any]] = []+ for j, p in enumerate(pieces):+ if j and bridges[j - 1]:+ left, count = pieces[j - 1], bridges[j - 1]+ a, b = left.source(left.last), p.source(p.first)+ ends = [loaded[(left.name, left.last)], loaded[(p.name, p.first)]]+ out, made = maker.at(ends, [(k + 1) / (count + 1) for k in range(count)], 1 / (count + 1))+ rows = {r["cell"]: r for r in made["frames"]}+ for k, image in enumerate(out):+ row = rows.get(k, {})+ taken, refused = _tries(row)+ src = made["source_frames"][k]+ link: dict[str, Any] = {"image": image, "refused": refused, "bridge": j - 1}+ if src is None:+ link["source"] = {"between": [a, b], "t": row["t"], "bridge": True}+ link.update(_judged(taken))+ else:+ link.update(source=b if src else a, file=(p if src else left).files[p.first if src else left.last])+ if "taken" in row:+ link["taken"] = True+ links.append(link)+ p.start = len(links)+ links += [{"source": p.source(k), "file": p.files[k], "image": loaded[(p.name, k)]} for k in p.used]+ return links+++def _cell(k: int, place: float, links: Sequence[dict[str, Any]], timed: dict[str, Any], rows: dict[int, dict[str, Any]]) -> dict[str, Any]:+ """The record of frame `k` as the time gave it: where it comes from, the values it was judged by and what was+ refused for it."""+ src = timed["source_frames"][k]+ row = rows.get(k, {})+ taken, refused = _tries(row)+ if src is None:+ a, b = row["between"]+ return {"frame": k, "place": place, "source": {"between": [links[a]["source"], links[b]["source"]], "t": row["t"]},+ **_judged(taken), "refused": refused}+ link = links[src]+ cell = {"frame": k, "place": place, "source": link["source"], "refused": refused or link.get("refused", [])}+ if link.get("judged") is not None:+ cell.update(judged=link["judged"], **({"kept_faults": link["kept_faults"]} if "kept_faults" in link else {}))+ if "taken" in row:+ cell["nearer_frame"] = True+ return cell+++def _drawn_pieces(pieces: Sequence[Piece], loaded: dict[tuple[str, int], Image.Image], rate: float | None) -> dict[str, int]:+ """The pieces drawn on twos or threes, read on their own frames as filmed (`held.measure`): a place may show any frame+ twice, and that is no drawing."""+ found = {}+ for p in pieces:+ thumbs = [loop_mod._small_features(loaded[(p.name, k)]) for k in p.used]+ steps = [float(np.abs(a - b).mean()) for a, b in zip(thumbs, thumbs[1:])]+ hold = held_mod.measure(steps, fps=rate or 24.0)["hold"] if steps else None+ if hold in held_mod.HOLDS:+ found[p.name] = hold+ return found+++def _masked(same: Sequence[bool], cells: Sequence[dict[str, Any]], entries: Sequence[dict[str, Any]], drawn: dict[str, int]) -> list[bool]:+ """The steps the fill may make again: those into a frame a list of holds names are as meant, and so are a drawn piece's+ between its own frames."""+ def in_drawn(k: int) -> bool:+ a, b = cells[k]["source"], cells[k + 1]["source"]+ return a.get("piece") in drawn and a.get("piece") == b.get("piece")++ return [bool(s) and not any(e["from"] <= k + 1 <= e["to"] for e in entries) and not in_drawn(k) for k, s in enumerate(same)]+++def _place_on(out_dir: Path, name: str, images: Sequence[Image.Image], cells: Sequence[dict[str, Any]], files: Sequence[Path | None],+ size: tuple[int, int], box: tuple[int, int, int, int]) -> Path:+ """The frames in a working folder beside `name` and handed over whole, a frame of a piece byte for byte as it came."""+ out_dir.mkdir(parents=True, exist_ok=True)+ work = Path(tempfile.mkdtemp(prefix=f".{name}-", dir=out_dir))+ try:+ for cell, image, file in zip(cells, images, files):+ target = work / f"frame-{cell['frame'] + 1:04d}.png"+ if file is not None:+ shutil.copyfile(file, target)+ continue+ canvas = Image.new("RGBA", size, (0, 0, 0, 0))+ canvas.paste(image, box[:2])+ canvas.save(target)+ final = out_dir / name+ work.rename(final)+ except BaseException:+ shutil.rmtree(work, ignore_errors=True)+ raise+ return final+++def _kept_lines(cells: Sequence[dict[str, Any]]) -> list[str]:+ """The frames delivered with a fault `--refuse` did not name, frame by frame, those with the same faults on one line."""+ alike: dict[tuple[str, ...], list[int]] = {}+ for cell in cells:+ if "kept_faults" in cell:+ alike.setdefault(tuple(cell["kept_faults"]), []).append(cell["frame"])+ return [f"frame{'s' if len(frames) > 1 else ''} {', '.join(map(str, frames))} kept with {', '.join(faults)}: found, and not named by --refuse" for faults, frames in alike.items()]+++def _said_runs(row: dict[str, Any]) -> str:+ return ", ".join(str(r["from"]) if r["from"] == r["to"] else f"{r['from']}-{r['to']}" for r in row["unlistedRuns"])+++def make_chain(pieces: Sequence[str], out_dir: Path, *, bridge: Sequence[int] = (), places: Path | None = None, out_fps: float | None = None,+ fps: float | None = None, key: str | None = None, holds: Sequence[Path] = (), scene: str | None = None, figure: str = "figure",+ fill_held: str = "auto", gate: bool = False, near: int = NEAR, refuse: str | None = None, report_path: Path | None = None,+ interpolate: rife_mod.Interpolate | None = None) -> dict[str, Any]:+ """The chain's frames in `out_dir/keyed/` and its report (`chain.report.json`, or `report_path`); see the module. The+ payload's `exit` is 0, or EXIT_SHOWN_AGAIN where the frames are refused (a frame shown again on no list, or, with+ `gate`, no RIFE to make what was asked for): they are in `keyed.refused/`. `ChainRefused` where nothing could be made+ or read. `interpolate` stands in for RIFE."""+ if fill_held not in held_fill_mod.MODES:+ raise ChainRefused(f"--fill-held {fill_held!r}: one of {', '.join(held_fill_mod.MODES)}")+ if key is not None and key not in KEYS_READ:+ raise ChainRefused(f"--key {key!r}: one of {', '.join(KEYS_READ)}")+ if places is not None and out_fps is not None:+ raise ChainRefused("--places and --out-fps: give one time")+ if out_fps is not None and not (math.isfinite(out_fps) and out_fps > 0):+ raise ChainRefused(f"--out-fps {out_fps:g}: a rate above 0")+ if fps is not None and not (math.isfinite(fps) and fps > 0):+ raise ChainRefused(f"--fps {fps:g}: a rate above 0")+ if near < 0:+ raise ChainRefused(f"--near {near}: a number of frames, 0 or more")+ refused_for = _read_refuse(refuse)+ if not pieces:+ raise ChainRefused("no --piece: NAME=DIR:FROM:TO, once for each piece in the order they play")+ chain_pieces = [read_piece(spec) for spec in pieces]+ names = [p.name for p in chain_pieces]+ if len(set(names)) != len(names):+ raise ChainRefused(f"--piece: two pieces are named {next(n for n in names if names.count(n) > 1)}")+ bridges = _bridges(bridge, len(chain_pieces) - 1)+ the_key = _one_key(chain_pieces, key)+ rate = _one_rate(chain_pieces, fps)+ if out_fps is not None and rate is None:+ raise ChainRefused(f"--out-fps needs the pieces' rate: no {FRAMES_REPORT} beside their frames says one, so name it with --fps")+ asked = _read_places(places) if places is not None else None+ count = sum(len(p.used) for p in chain_pieces) + sum(bridges)+ off = [p for p in asked or [] if not 0 <= p <= count - 1]+ if off:+ raise ChainRefused(f"--places: {off[0]:g} is off the chain, whose frames are numbered 0..{count - 1}")+ entries = holds_mod.for_scene(holds_mod.read_lists(holds), scene)+ out_dir = Path(out_dir).expanduser().resolve()+ target = Path(report_path or out_dir / REPORT_NAME).expanduser().resolve()+ keyed_dir, refused = out_dir / KEYED, refused_dir(out_dir / KEYED)+ refuse_overlap({**{f"piece {p.name}": p.folder for p in chain_pieces}, **({"--places": Path(places)} if places else {}),+ **{f"--holds {h}": Path(h) for h in holds}},+ {"keyed in --out-dir": keyed_dir, "keyed.refused in --out-dir": refused,+ ("--report" if report_path else f"{REPORT_NAME} in --out-dir"): target}, verb=PROG)+ size, box = _canvas_and_box(chain_pieces)+ base: dict[str, Any] = {+ "kind": REPORT_KIND, "producer": evidence_mod.engine_identity(),+ "refuse": [f for f in held_fill_mod.FAULTS if refused_for is None or f in refused_for], "key": the_key, "canvas": list(size), "fill_held": fill_held, "gate": gate,+ "pieces": [{"name": p.name, "frames_dir": str(p.folder), "from": p.first, "to": p.last, "key": p.key or the_key,+ "key_from": FRAMES_REPORT if p.key else "--key", "source": evidence_mod.source_identity([p.files[k] for k in p.used], rate or 0.0)}+ for p in chain_pieces],+ }+ shutil.rmtree(keyed_dir, ignore_errors=True) # from here an earlier run's frames are no longer handed over+ shutil.rmtree(refused, ignore_errors=True)++ def refuse(error: str, **more: Any) -> ChainRefused:+ loop_mod.write_loop_report(target, {**base, **more, "status": "failed", "error": error})+ return ChainRefused(error)++ if box is None:+ raise refuse(f"{holds_mod.NOTHING}: no piece draws a figure on any frame", read={"inspected": 0, "unlisted": 0, "table": {}})+ loaded = {(p.name, k): Image.open(p.files[k]).convert("RGBA").crop(box) for p in chain_pieces for k in p.used}+ joins = [read_join(chain_pieces[j], chain_pieces[j + 1], loaded, near) for j in range(len(chain_pieces) - 1)]+ for j, b in enumerate(bridges):+ joins[j]["bridge"] = b+ base["joins"] = joins+ if joins and not any(j["reads"] for j in joins):+ raise refuse("no join was read: " + "; ".join(f"{j['from']['piece']} into {j['into']['piece']}: {j['why']}" for j in joins))+ filmed = [loaded[(p.name, k)] for p in chain_pieces for k in p.used]+ maker = _Maker(interpolate, bool(ghost_screen(filmed)["reads"]), refused_for)+ warnings: list[str] = []+ try:+ links = _links(chain_pieces, bridges, loaded, maker)+ if asked is not None:+ at, kind = asked, "places"+ spacing: float | list[float] = _spacing(at)+ elif out_fps is not None:+ at, kind = held_fill_mod.times(count, float(rate), out_fps, ring=False) if count > 1 else [0.0], "out-fps" # type: ignore[arg-type]+ spacing = float(rate) / out_fps # type: ignore[arg-type]+ else:+ at, kind, spacing = [float(k) for k in range(count)], "clip", 1.0+ base["chain"] = {"frames": count, "pieces": {p.name: [p.start, p.start + len(p.used) - 1] for p in chain_pieces},+ "bridges": [{"place": k, "source": link["source"], "judged": link.get("judged"), "refused": link["refused"],+ **({"kept_faults": link["kept_faults"]} if "kept_faults" in link else {})}+ for k, link in enumerate(links) if "bridge" in link]}+ base["time"] = {"kind": kind, "fps": rate, **({"out_fps": out_fps} if out_fps is not None else {}),+ **({"places_file": str(Path(places).expanduser().resolve())} if places is not None else {}), "frames": len(at)}+ shown, timed = maker.at([link["image"] for link in links], at, spacing)+ rows = {r["cell"]: r for r in timed["frames"]}+ cells = [_cell(k, at[k], links, timed, rows) for k in range(len(at))]+ files: list[Path | None] = [links[s]["file"] if s is not None and "file" in links[s] else None for s in timed["source_frames"]]+ drawn = _drawn_pieces(chain_pieces, loaded, rate)+ same = held_fill_mod.same_steps(shown) if len(shown) > 1 else []+ delivered, filled = maker.fill(shown, _masked(same, cells, entries, drawn), fill_held)+ except rife_mod.RifeUnavailable as exc:+ raise refuse(f"{exc}; the chain's frames between are to be made: fix RIFE") from exc+ sources = [cell["source"] for cell in cells]+ for made in filled["frames"]:+ taken, tried = _tries(made)+ a, b = made["between"]+ c = made["cell"]+ cells[c].pop("kept_faults", None) # those of the picture it showed before it was made+ cells[c].update(source={"between": [sources[a], sources[b]], "t": made["t"]}, **_judged(taken), refused=tried)+ files[c] = None+ for run in filled["before"]["held_runs"]:+ for tried in run.get("tries") or []:+ cells[tried["cell"]]["refused"] = [t for t in tried["tries"] if not _passed(t)]+ base.update(frames=cells, held_fill=held_fill_mod.public(filled), interpolator=maker.named(), drawn_pieces=drawn,+ holds={"lists": sorted({e["file"] for e in entries})})+ try:+ read = holds_mod.inspect(holds_mod.alpha_figures(delivered, name=figure), listed=entries)+ except holds_mod.NothingRead as exc:+ raise refuse(f"{holds_mod.NOTHING}: {exc}", read=exc.report or {"inspected": 0, "unlisted": 0, "table": {}}) from None+ base["read"] = read+ if maker.missing is not None:+ base["rife"] = maker.missing+ between = [c["frame"] for c in cells if "nearer_frame" in c]+ if between:+ warnings.append(f"{len(between)} frame{'s' if len(between) > 1 else ''} ({', '.join(map(str, between))}) took the nearer frame for a place between two: "+ f"RIFE is not installed, so none was made; run `{maker.missing['install']}` and make the chain again (docs/video-pipeline.md section 9)")+ if any("bridge" in link and "taken" in link for link in links):+ warnings.append(f"a join's frames between are the frames beside it: RIFE is not installed; run `{maker.missing['install']}` and make the chain again")+ else:+ warnings += [f"frame {k} took the nearer frame: every frame made for its place was refused ({', '.join(sorted({f for t in cells[k]['refused'] for f in t['faults']})) or 'ghost band'})"+ for k in timed["shown_again"]]+ warnings += [f"the frame between at chain place {k} is the frame beside it: every frame made for it was refused" for k, link in enumerate(links) if "taken" in link]+ warnings += loop_mod.fill_lines(filled)+ warnings += _kept_lines(cells)+ warnings += [f"the join from {j['from']['piece']} into {j['into']['piece']} could not be read: {j['why']}" for j in joins if not j["reads"]]+ shown_again = read["unlisted"]+ named = "; ".join(f"{name} frame{'s' if row['unlisted'] > 1 else ''} {_said_runs(row)}" for name, row in read["table"].items() if row["unlisted"])+ failed: str | None = None+ if maker.missing is not None:+ if shown_again:+ warnings.append(f"{shown_again} frame{'s' if shown_again > 1 else ''} show{'' if shown_again > 1 else 's'} the picture of the frame before: {named}")+ if gate:+ failed = f"--gate: RIFE is not installed, and the chain's frames between were not made{f' ({named} shown again)' if shown_again else ''}"+ elif shown_again:+ why = sorted({r["why"] for r in filled["before"]["held_runs"] if not r.get("filled") and r.get("why")})+ drawn_said = [f"{n} is drawn on {'twos' if h == 2 else 'threes'}" for n, h in drawn.items()]+ failed = (f"{shown_again} frame{'s' if shown_again > 1 else ''} show{'' if shown_again > 1 else 's'} the picture of the frame before and "+ f"{'are' if shown_again > 1 else 'is'} on no list: {named}" + (f" ({'; '.join(why + drawn_said)})" if why or drawn_said else "")+ + ". List a hold meant in --holds, or change the places or the pieces"+ + ("; a fault named that is the material's own and no fault in it is left out of --refuse (docs/video-pipeline.md section 9)"+ if any(r.get("faults") for r in filled["before"]["held_runs"]) else ""))+ final = _place_on(out_dir, refused.name if failed else KEYED, delivered, cells, files, size, box)+ payload = {**base, "status": "failed" if failed else "passed", "warnings": warnings, **({"error": failed} if failed else {}),+ ("refused_dir" if failed else "keyed_dir"): str(final)}+ loop_mod.write_loop_report(target, payload)+ payload.update(report=str(target), exit=EXIT_SHOWN_AGAIN if failed else EXIT_OK)+ return payload+++def add_arguments(parser: argparse.ArgumentParser) -> None:+ parser.add_argument("--piece", action="append", default=[], metavar="NAME=DIR:FROM:TO",+ help="a piece, in the order they play: frames FROM..TO (both in, counted from 0 in name order) of the keyed "+ "PNGs in DIR or DIR/keyed. Where a piece ends and the next begins is yours to choose: the join's pose is "+ "reported, never chosen")+ parser.add_argument("--bridge", action="append", type=int, default=[], metavar="K",+ help="frames made between a join's two frames, at k/(K+1): once for every join, or once per join in order (default 0)")+ time = parser.add_mutually_exclusive_group()+ time.add_argument("--out-fps", type=float, help="the chain resampled evenly from its first frame to its last at this rate (default: at its own rate)")+ time.add_argument("--places", type=Path, help="a JSON list (or an object's `places`) of a place on the chain for each frame "+ "delivered, its frames numbered from 0 with a bridge's among them; a place between two frames is made between them")+ parser.add_argument("--holds", action="append", type=Path, default=[], help="a list of the holds meant, as inspect-holds reads it, "+ "frames counted on the frames delivered: those stay; or a folder, every *.holds.json under it (repeat for more)")+ parser.add_argument("--scene", help="the scene this is, for a list whose holds name scenes")+ parser.add_argument("--figure", default="figure", help="the figure's name, for a list whose holds name figures (several: the name and 0, 1, ...)")+ parser.add_argument("--fill-held", choices=held_fill_mod.MODES, default="auto",+ help="auto (default): a frame showing the picture before it, on no list, is made again between the poses beside it "+ "(docs/loop-repair.md section 7); off: none is, and any left fails the chain as one refused does")+ parser.add_argument("--gate", action="store_true", help="fail where RIFE is not installed and a frame was to be made (else the nearer frame and a warning line)")+ parser.add_argument("--refuse", metavar="FAULT,FAULT", help=f"the faults that refuse a frame made, of {', '.join(held_fill_mod.FAULTS)} (default: all). Which are a fault "+ "in your material and which are its own is yours to read off it (docs/video-pipeline.md section 9); held and the final reading refuse whatever this says, "+ "and a fault left out stays on the frame's record and a warning line")+ parser.add_argument("--key", choices=KEYS_READ, help=f"what the pieces are keyed on, for one with no {FRAMES_REPORT} that says; a report that says otherwise refuses the chain")+ parser.add_argument("--fps", type=float, help=f"the pieces' rate, for one with no {FRAMES_REPORT} that says (needed by --out-fps)")+ parser.add_argument("--near", type=int, default=NEAR, help=f"how many frames either way of a join to look for closer poses, reported only (default {NEAR})")+ parser.add_argument("--out-dir", type=Path, required=True, help="writes keyed/ and chain.report.json here; a refused chain leaves keyed.refused/ and no keyed/")+ parser.add_argument("--report", type=Path, help=f"report path (default <out-dir>/{REPORT_NAME})")+++def run(**kwargs: object) -> int:+ """Make the chain and print what became of it. 0; 1 where a frame shown again is on no list (or --gate and no RIFE); 2 on+ an error, a chain that read nothing among them."""+ parser = argparse.ArgumentParser(add_help=False)+ add_arguments(parser)+ args = namespace_from_kwargs(parser, kwargs)+ try:+ payload = make_chain(args.piece, args.out_dir, bridge=args.bridge, places=args.places, out_fps=args.out_fps, fps=args.fps, key=args.key,+ holds=args.holds, scene=args.scene, figure=args.figure, fill_held=args.fill_held, gate=args.gate, near=args.near,+ refuse=args.refuse, report_path=args.report)+ except (ValueError, OSError) as exc:+ print(f"{PROG}: {exc}", file=sys.stderr)+ return EXIT_ERROR+ except SystemExit as exc: # a refusal of the shared helpers (`refuse_overlap`): an error here as any other+ print(exc, file=sys.stderr)+ return EXIT_ERROR+ held = payload["held_fill"]+ print(json.dumps({"keyed_dir": payload.get("keyed_dir"), "refused_dir": payload.get("refused_dir"), "frames": len(payload["frames"]),+ "made": sum(1 for c in payload["frames"] if "between" in c["source"]),+ "poses_cells": {"before": held_fill_mod.said(held["before"]), "after": held_fill_mod.said(held)},+ "refuse": payload["refuse"], "unlisted": payload["read"]["unlisted"], "listed": sum(r["listed"] for r in payload["read"]["table"].values()),+ "joins": [{"from": j["from"], "into": j["into"], "bridge": j["bridge"], "steps": j.get("steps"), "closer": j.get("closer_found")} for j in payload["joins"]],+ "interpolator": payload["interpolator"], "report": payload["report"]}, ensure_ascii=False, indent=2))+ for line in payload["warnings"]:+ print(f"{PROG}: warning: {line}", file=sys.stderr)+ if "error" in payload:+ print(f"{PROG}: {payload['error']}", file=sys.stderr)+ return payload["exit"]+++def main(argv: list[str] | None = None) -> int:+ utf8_streams()+ parser = argparse.ArgumentParser(prog=f"sprite-gen {PROG}", description=__doc__.split("\n\n")[0])+ add_arguments(parser)+ return run(**vars(parser.parse_args(argv)))+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/sprite_gen/video/frames.py b/sprite_gen/video/frames.pyindex ea19dee..aa786de 100644--- a/sprite_gen/video/frames.py+++ b/sprite_gen/video/frames.py@@ -89,6 +89,7 @@ EDGE_ROWS = 4 # rows/cols inspected at each edge# from is the evidence: if the still carries (almost) no key-coloured material, every# key tint in the clip was painted by the model and is spill.SPILL_MODES = ("auto", "small", "full")+KEYS_READ = ("green", "magenta", "white", "brightness") # what a clip's frames are keyed on, where `video-chain` compares them (brightness: no key, `--alpha-mode brightness`)SPILL_FULL_FRACTION = 1.0 # every tinted cluster is spill, whatever its sizeSPILL_FULL_MIN_TINT = _SPILL_FULL_MIN_TINT # ... and whatever its strength (see extract.py)SPILL_REFERENCE_MAX = 0.005 # the still's own key material ≤ the engine's small-cluster share → full@@ -375,12 +376,12 @@ def _reference_window(reference: Path, key: str) -> tuple[str, Image.Image | Nonstill is kept in the mode it was decoded in and read a band of rows at a time; only thewindow is converted to RGBA, and the full-size image is released before it is keyed."""- from sprite_gen.frames.cutout import KEY_TARGETS, _EXTRACT_KEY_THRESHOLD, _corner_average, _detect_key_kind+ from sprite_gen.frames.cutout import KEY_TARGETS, _EXTRACT_KEY_THRESHOLDfrom sprite_gen.frames.extract import detect_background_key_rgb, subject_windowimage = Image.open(reference)image.load()- kind = _detect_key_kind(_corner_average(image)) if key == "auto" else key+ kind = key_kind(image, key)if kind not in ("green", "magenta"):return kind, None, None, {}target = KEY_TARGETS[kind]@@ -398,6 +399,13 @@ def _reference_window(reference: Path, key: str) -> tuple[str, Image.Image | Nonreturn kind, window, painted, facts+def key_kind(image: Image.Image, key: str) -> str:+ """The key a frame of a clip is keyed on: `key`, or what its corners read as where that is `auto`."""+ from sprite_gen.frames.cutout import _corner_average, _detect_key_kind++ return _detect_key_kind(_corner_average(image)) if key == "auto" else key++def decide_spill(reference: Path, key: str) -> dict[str, Any]:"""`auto`: key the reference still with the same matte and measure its ownkey-coloured material. None worth the name → `full`; some → `small`.@@ -745,6 +753,9 @@ def run_frames(clip: Path, out_dir: Path, *, key: str, allow_edge_contact: bool,atomic_write_text(target, json.dumps(payload, ensure_ascii=False, indent=2) + "\n")raisepayload = {**head, "status": "passed", "keyed_dir": str(keyed_dir), "key": key, "spill": decision, **meta, **report}+ if alpha_mode != "brightness":+ with Image.open(files[0]) as first:+ payload["key_read"] = key_kind(first, key) # what it was keyed on, where `key` says only auto (`video-chain`)if source_manifest is not None:from sprite_gen.video.evidence import engine_identitypayload["producer"] = engine_identity()diff --git a/sprite_gen/video/held_fill.py b/sprite_gen/video/held_fill.pyindex 36f87f3..26d2e82 100644--- a/sprite_gen/video/held_fill.py+++ b/sprite_gen/video/held_fill.py@@ -50,7 +50,7 @@ docs/video-pipeline.md "Root motion")."""from __future__ import annotationsimport math-from collections.abc import Callable, Sequence+from collections.abc import Callable, Collection, Sequencefrom typing import Anyfrom PIL import Image, ImageFilter@@ -174,6 +174,10 @@ def still_kept(frame: Image.Image, a: Image.Image, b: Image.Image) -> dict[str,return {"reads": True, "still_px": int(still.sum()), "kept": round(least, 4), "at_row": at, "window_px": win}+# What `judge` can find in a frame made: `faults`' and its own. `video-chain --refuse` names among these.+FAULTS = ("smear", "outline", "ghost", "torn", "hole", "doubled", "contact", "held")++def judge(frame: Image.Image, a: Image.Image, b: Image.Image, t: float, *, reads: bool,before: Image.Image | None = None) -> tuple[dict[str, Any], list[str]]:"""A frame made between `a` and `b` at `t`: the alignment's measure and faults (`align.measure_made`, `faults`),@@ -192,13 +196,17 @@ def judge(frame: Image.Image, a: Image.Image, b: Image.Image, t: float, *, readsdef _made(interpolate: rife_mod.Interpolate, a: Image.Image, b: Image.Image, t: float, window: tuple[float, float], *,- reads: bool, before: Image.Image | None = None) -> tuple[Image.Image | None, dict[str, Any]]:+ reads: bool, before: Image.Image | None = None, refuse: Collection[str] | None = None) -> tuple[Image.Image | None, dict[str, Any]]:"""The frame between `a` and `b` at `t`, or at the fraction of RETIME_T nearest it inside `window` that is madewith no fault (`judge`, `before` the cell delivered before it, None where that is `a`) and, made only off its time,with its ghost band under RETIME_WINDOW_MAX in every window (align's bar for a frame made again at anotherfraction); None and what each try was refused for, where none is. The frames between run from `a` to `b`, so onethat shows `a` or the cell before it again (`held`, `shows`) is made again only later, one that shows `b` only- earlier, and one that shows both not again: a fraction on the side of a picture it showed would show it too."""+ earlier, and one that shows both not again: a fraction on the side of a picture it showed would show it too.++ `refuse` (None: every fault) names the faults a frame is refused for, a caller's word for its material+ (`video-chain --refuse`). `held` refuses it whatever `refuse` says: no frame between is a held cell again. The bar+ of a frame made off its time stands too. A try's `faults` are those it is refused for, `kept_faults` the rest."""from sprite_gen.video.align import RETIME_T, RETIME_WINDOW_MAXlo, hi = window@@ -207,10 +215,14 @@ def _made(interpolate: rife_mod.Interpolate, a: Image.Image, b: Image.Image, t:if not lo < at < hi:continueframe = interpolate(a, b, at)- measure, wrong = judge(frame, a, b, at, reads=reads, before=before)+ measure, found = judge(frame, a, b, at, reads=reads, before=before)+ wrong = found if refuse is None else [f for f in found if f in refuse or f == "held"]+ kept = [f for f in found if f not in wrong]seen = at != t and (measure.get("ghost_window") or 0.0) >= RETIME_WINDOW_MAX- tries.append({"t": round(at, 4), "faults": wrong, **({"shows": measure["shows"]} if measure["shows"] else {}),- **({"window_over": RETIME_WINDOW_MAX} if seen and not wrong else {})})+ tries.append({"t": round(at, 4), "faults": wrong, **({"kept_faults": kept} if kept else {}),+ **({"shows": measure["shows"]} if measure["shows"] else {}),+ **({"window_over": RETIME_WINDOW_MAX} if seen and not wrong else {}),+ "judged": {k: v for k, v in measure.items() if k != "shows"}})if not wrong and not seen:return frame, {"t": round(at, 4), **({"from_t": round(t, 4)} if at != t else {}),"contact": measure["contact"], "look": looks(measure), "tries": tries}@@ -259,7 +271,7 @@ def _fillable(run: dict[str, int], n: int, *, ring: bool, on: int | None = None,def _make_run(frames: Sequence[Image.Image], interpolate: rife_mod.Interpolate, a: int, b: int, cells: Sequence[int], *,- reads: bool) -> tuple[list[tuple[int, Image.Image]], list[dict[str, Any]]]:+ reads: bool, refuse: Collection[str] | None = None) -> tuple[list[tuple[int, Image.Image]], list[dict[str, Any]]]:"""Each of `cells` made between frame `a` and frame `b` (a loop's `b` n is its first cell across the wrap) at its owntime, within half a cell of it (`_made`), the cell delivered before each the one made before it: the frames taken,up to the first refused, and how each was tried."""@@ -270,7 +282,7 @@ def _make_run(frames: Sequence[Image.Image], interpolate: rife_mod.Interpolate,t = (c - a) / (b - a)half = 0.5 / (b - a)frame, how = _made(interpolate, frames[a], frames[b % n], t, (t - half, t + half), reads=reads,- before=taken[-1][1] if taken else None)+ before=taken[-1][1] if taken else None, refuse=refuse)tried.append({"cell": c, "between": [a, b % n], **how})if frame is None:break@@ -280,7 +292,8 @@ def _make_run(frames: Sequence[Image.Image], interpolate: rife_mod.Interpolate,def fill(frames: list[Image.Image], interpolate: rife_mod.Interpolate | None, *, ring: bool,same: Sequence[bool] | None = None, mode: str = "auto", reads: bool | None = None,- hold: int | None = None, wrap: bool | None = None, drawn_on: int | None = None) -> tuple[list[Image.Image], dict[str, Any]]:+ hold: int | None = None, wrap: bool | None = None, drawn_on: int | None = None,+ refuse: Collection[str] | None = None) -> tuple[list[Image.Image], dict[str, Any]]:"""`frames` with each held run's cells made again between the run's first cell and the next pose (see the module),and the record: the reading before (`before`, each run `filled` or why not, and a loop's wrap, `wrap`), the cellsmade (`made`, and how each was, `frames`), the cells left for want of an interpolator (`unmade`, `interpolate`@@ -289,7 +302,8 @@ def fill(frames: list[Image.Image], interpolate: rife_mod.Interpolate | None, *,`wrap`, for a loop, whether its last cell shows its first cell's picture as filmed (`wrap_same` of `frames` whereNone); `reads` whether the ghost screen reads the cut (read on `frames` where None); `hold` the cut's held-drawingsreading (`held.measure_cycle`); `drawn_on` the hold of a cut known drawn on twos or threes where its own runs do- not read so (a loop resampled to another length from one drawn so, every run of it kept).+ not read so (a loop resampled to another length from one drawn so, every run of it kept); `refuse` the faults a+ frame made is refused for (`_made`).A loop whose last cells show its first cell's picture again (`wrap`) keeps its first cell: the cells before the wrapthat show it are made again between the pose before them and the first cell, as one run with the cells after it that@@ -328,7 +342,7 @@ def fill(frames: list[Image.Image], interpolate: rife_mod.Interpolate | None, *,return {**row, "filled": False, "why": "no interpolator"}if reads is None:reads = bool(ghost_screen(frames)["reads"])- taken, tried = _make_run(frames, interpolate, a, b, cells, reads=reads)+ taken, tried = _make_run(frames, interpolate, a, b, cells, reads=reads, refuse=refuse)if len(taken) < len(cells):refused = sorted({f for row_ in tried for t_ in row_["tries"] for f in t_["faults"]})return {**row, "filled": False, "faults": refused, "tries": tried,@@ -429,11 +443,12 @@ def times(n: int, fps: float, out_fps: float, *, ring: bool) -> list[float]:def at_times(frames: list[Image.Image], interpolate: rife_mod.Interpolate, at: Sequence[float], *, ring: bool,- spacing: float | Sequence[float], reads: bool | None = None) -> tuple[list[Image.Image], dict[str, Any]]:+ spacing: float | Sequence[float], reads: bool | None = None,+ refuse: Collection[str] | None = None) -> tuple[list[Image.Image], dict[str, Any]]:"""`frames` at the times `at`, in frames of the cut: a cell on a frame's time is that frame, one between two framesshowing one picture is that picture, any other is made between the two at its own time (`_made`, within half its- `spacing` of it: frames a cell, one for all or one each), and one no frame made is taken for is the nearer frame and- named (`shown_again`). The record: how many were made, the cells shown again, how each was (`frames`), and the+ `spacing` of it: frames a cell, one for all or one each; `refuse` the faults one is refused for), and one no frame+ made is taken for is the nearer frame and named (`shown_again`). The record: how many were made, the cells shown again, how each was (`frames`), and theframe each cell is, None where it was made (`source_frames`)."""n = len(frames)same = same_steps(frames + ([frames[0]] if ring else []))@@ -457,7 +472,7 @@ def at_times(frames: list[Image.Image], interpolate: rife_mod.Interpolate, at: St = tau - ahalf = (spacing if isinstance(spacing, (int, float)) else spacing[k]) / 2frame, how = _made(interpolate, frames[a], frames[(a + 1) % n], t, (t - half, t + half), reads=reads,- before=out[-1] if out else None)+ before=out[-1] if out else None, refuse=refuse)if frame is None:out.append(frames[near % n])source_frames.append(near % n)diff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.pyindex 3031d44..32400f3 100644--- a/sprite_gen/video/loop.py+++ b/sprite_gen/video/loop.py@@ -40,6 +40,7 @@ import sysfrom dataclasses import dataclassfrom functools import partialfrom pathlib import Path+from collections.abc import Collectionfrom typing import Anyfrom PIL import Image@@ -1417,13 +1418,14 @@ def _located(interpolate: rife_mod.Interpolate | None, made_by: list[dict[str, sdef fill_cut(frames: list[Image.Image], interpolate: rife_mod.Interpolate | None, *, ring: bool, same: list[bool] | None,- mode: str, hold: int | None, wrap: bool | None = None) -> tuple[list[Image.Image], dict[str, Any]]:- """`held_fill.fill` on the cut, with RIFE located only once a frame is to be made: a cut with no held cell, or only- runs kept as filmed, needs no binary. The record names the interpolator that made the frames. A frame to make and no- RIFE installed: the held cells are delivered as filmed, and the record says which and how to install it (`unmade`)."""+ mode: str, hold: int | None, wrap: bool | None = None, refuse: Collection[str] | None = None) -> tuple[list[Image.Image], dict[str, Any]]:+ """`held_fill.fill` on the cut (`refuse` the faults a frame made is refused for, every one where None), with RIFE+ located only once a frame is to be made: a cut with no held cell, or only runs kept as filmed, needs no binary. The+ record names the interpolator that made the frames. A frame to make and no RIFE installed: the held cells are+ delivered as filmed, and the record says which and how to install it (`unmade`)."""made_by: list[dict[str, str]] = []lazy = _located(interpolate, made_by)- asked = partial(held_fill_mod.fill, ring=ring, same=same, mode=mode, hold=hold, wrap=wrap)+ asked = partial(held_fill_mod.fill, ring=ring, same=same, mode=mode, hold=hold, wrap=wrap, refuse=refuse)try:frames, record = asked(frames, lazy)except rife_mod.RifeNotInstalled as exc:diff --git a/tests/video/test_chain.py b/tests/video/test_chain.pynew file mode 100644index 0000000..fac0cc3--- /dev/null+++ b/tests/video/test_chain.py@@ -0,0 +1,650 @@+# SPDX-License-Identifier: Apache-2.0+"""`video-chain`: pieces of keyed clips on one canvas played as one move (docs/video-pipeline.md section 9). Where they join+and when each frame shows is the caller's; the frames between, no picture shown again and the record are the engine's.++Each way of giving the time holds its frames against the same chain with nothing to make frames with: the nearer frame+shows a picture again, and `inspect-holds --gate`, reading what was delivered, fails it; with frames between it passes.+The interpolator is `Between`, a stand-in that draws the synthetic clip again at the time asked for; one test runs RIFE."""++from __future__ import annotations++import json+import math+import os+import shutil+import subprocess+import sys+from pathlib import Path++import pytest+from PIL import Image, ImageDraw++from sprite_gen.qa import holds as holds_mod+from sprite_gen.video import chain, held_fill+from tests.video.held_fill_inputs import Between, H, N, W, save+++def walk_at(time: float) -> Image.Image:+ """One figure, read as one by `inspect-holds` (a torso and head, two legs going round a hip joined to it), `time`+ frames into a cycle of N: every part of a frame, a third of one too, moves it."""+ im = Image.new("RGBA", (W, H), (0, 0, 0, 0))+ d = ImageDraw.Draw(im)+ d.rectangle((50, 30, 70, 90), fill=(90, 90, 200, 255))+ d.rectangle((48, 10, 72, 30), fill=(230, 190, 160, 255))+ phase = 2 * math.pi * time / N+ x, y = 40 * math.cos(phase), 40 * math.sin(phase)+ d.line((60, 85, 60 + x, 85 + y), fill=(200, 160, 40, 255), width=14)+ d.line((60, 85, 60 - x, 85 - y), fill=(180, 60, 60, 255), width=14)+ return im+++def walk(frames: int = N + 6) -> list[Image.Image]:+ return [walk_at(k) for k in range(frames)]+++def clip(tmp_path: Path, name: str, frames: list[Image.Image] | None = None, *, key: str | None = None, fps: float | None = None) -> Path:+ """A clip's keyed frames as `video-frames` leaves them, with its report where a key or a rate is given."""+ out = tmp_path / name+ save(frames if frames is not None else walk(N + 6), out / "keyed")+ if key is not None or fps is not None:+ (out / "frames.report.json").write_text(json.dumps({"key": "auto", "key_read": key, "fps": fps}))+ return out+++def between() -> Between:+ return Between(walk_at, [k / 12 for k in range(12 * N)], period=N)+++def no_rife(monkeypatch, tmp_path: Path) -> None:+ monkeypatch.delenv("SPRITE_GEN_RIFE", raising=False)+ path = [d for d in os.environ.get("PATH", "").split(os.pathsep) if d and not (Path(d) / "rife-ncnn-vulkan").exists()]+ monkeypatch.setenv("PATH", os.pathsep.join(path))+ monkeypatch.setenv("SPRITE_GEN_DATA_DIR", str(tmp_path / "data"))+++def make(tmp_path: Path, pieces: list[str], **kw) -> dict:+ kw.setdefault("key", "green")+ kw.setdefault("interpolate", between())+ return chain.make_chain(pieces, tmp_path / "out", **kw)+++def delivered(out: dict) -> list[Image.Image]:+ return [Image.open(f).convert("RGBA") for f in sorted(Path(out["keyed_dir"]).glob("*.png"))]+++def gate(folder: str | Path, *lists: Path) -> int:+ """`inspect-holds --gate` on what was delivered: the reading a user of the engine makes before handing it on."""+ args = [sys.executable, "-m", "sprite_gen.cli", "inspect-holds", "--source", str(folder), "--gate"]+ for path in lists:+ args += ["--holds", str(path)]+ return subprocess.run(args, capture_output=True, encoding="utf-8").returncode+++def places_file(tmp_path: Path, places: list[float]) -> Path:+ path = tmp_path / "places.json"+ path.write_text(json.dumps({"places": places}))+ return path+++def holds_file(tmp_path: Path, *holds: tuple[int, int]) -> Path:+ path = tmp_path / "meant.holds.json"+ path.write_text(json.dumps({"holds": [{"from": a, "to": b, "reason": "the figure stops on the ledge"} for a, b in holds]}))+ return path+++# --- the three times, each no picture shown again ------------------------------------------------------------------++def test_a_join_that_shows_one_picture_twice_is_made_between_where_the_nearer_frame_shows_it_again(tmp_path, monkeypatch):+ """The second clip starts on the frame the first ends on (a clip made from the other's last frame)."""+ d = clip(tmp_path, "a")+ pieces = [f"one={d}:0:9", f"two={d}:9:20"]+ out = make(tmp_path / "with", pieces)+ assert out["status"] == "passed" and out["exit"] == 0 and out["read"]["unlisted"] == 0+ assert gate(out["keyed_dir"]) == 0+ assert out["frames"][10]["source"] == {"between": [{"piece": "one", "frame": 9}, {"piece": "two", "frame": 10}], "t": 0.5}+ assert not any(held_fill.same_steps(delivered(out)))++ no_rife(monkeypatch, tmp_path)+ bare = make(tmp_path / "without", pieces, interpolate=None)+ assert gate(bare["keyed_dir"]) == 1+++def test_an_even_resample_makes_its_places_between_where_the_nearer_frame_shows_one_again(tmp_path, monkeypatch):+ d = clip(tmp_path, "a", fps=24.0)+ pieces = [f"one={d}:0:9", f"two={d}:10:20"]+ out = make(tmp_path / "with", pieces, out_fps=60.0)+ assert out["time"] == {"kind": "out-fps", "fps": 24.0, "out_fps": 60.0, "frames": 51}+ assert out["read"]["unlisted"] == 0 and gate(out["keyed_dir"]) == 0+ assert not any(held_fill.same_steps(delivered(out)))+ assert out["frames"][1]["place"] == pytest.approx(0.4)++ no_rife(monkeypatch, tmp_path)+ bare = make(tmp_path / "without", pieces, interpolate=None, out_fps=60.0)+ assert bare["exit"] == 0 and bare["read"]["unlisted"] > 0+ assert gate(bare["keyed_dir"]) == 1+++def test_a_list_of_places_makes_each_between_where_the_nearer_frame_shows_one_again(tmp_path, monkeypatch):+ d = clip(tmp_path, "a")+ pieces = [f"one={d}:0:9", f"two={d}:10:20"]+ places = places_file(tmp_path, [2, 2.5, 3, 3.25, 3.5, 3.75, 4, 9, 9.5, 10, 12])+ out = make(tmp_path / "with", pieces, places=places)+ assert out["read"]["unlisted"] == 0 and gate(out["keyed_dir"]) == 0+ assert [c["place"] for c in out["frames"]] == [2, 2.5, 3, 3.25, 3.5, 3.75, 4, 9, 9.5, 10, 12]+ assert out["frames"][1]["source"] == {"between": [{"piece": "one", "frame": 2}, {"piece": "one", "frame": 3}], "t": 0.5}+ assert out["frames"][8]["source"] == {"between": [{"piece": "one", "frame": 9}, {"piece": "two", "frame": 10}], "t": 0.5}+ assert out["frames"][0]["source"] == {"piece": "one", "frame": 2}++ no_rife(monkeypatch, tmp_path)+ assert gate(make(tmp_path / "without", pieces, interpolate=None, places=places)["keyed_dir"]) == 1+++def test_a_place_shown_twice_is_made_between_it_and_the_next_and_off_it_fails_by_its_number(tmp_path):+ """The caller's places show a clip frame on two frames in a row, as a time picked on whole frames does."""+ d = clip(tmp_path, "a")+ places = places_file(tmp_path, [2, 3, 3, 4, 5, 6])+ out = make(tmp_path / "on", [f"one={d}:0:9"], places=places)+ assert out["exit"] == 0 and out["read"]["unlisted"] == 0+ assert out["frames"][2]["source"] == {"between": [{"piece": "one", "frame": 3}, {"piece": "one", "frame": 4}], "t": 0.5}++ off = make(tmp_path / "off", [f"one={d}:0:9"], places=places, fill_held="off",+ interpolate=lambda a, b, t: pytest.fail("--fill-held off makes none"))+ assert off["status"] == "failed" and off["exit"] == chain.EXIT_SHOWN_AGAIN+ assert off["read"]["table"]["figure"]["unlistedRuns"][0]["from"] == 2+ assert "figure frame 2" in off["error"]+ assert "keyed_dir" not in off and Path(off["refused_dir"]).is_dir() and not (tmp_path / "off" / "out" / "keyed").exists()+++def test_a_frame_filmed_twice_inside_a_piece_is_made_between_the_poses_beside_it(tmp_path):+ frames = walk(N + 6)+ frames[6] = frames[5]+ d = clip(tmp_path, "a", frames)+ out = make(tmp_path, [f"one={d}:0:12"])+ assert out["read"]["unlisted"] == 0 and out["held_fill"]["before"]["held_runs"][0]["filled"] is True+ cell = out["frames"][6]+ assert cell["source"] == {"between": [{"piece": "one", "frame": 5}, {"piece": "one", "frame": 7}], "t": 0.5}+ assert cell["judged"]["contact"]["reads"] in (True, False) and cell["refused"] == []+++def test_a_join_s_bridge_makes_its_frames_between_and_they_take_a_place_on_the_chain(tmp_path):+ d = clip(tmp_path, "a")+ out = make(tmp_path, [f"one={d}:0:3", f"two={d}:5:7"], bridge=[1])+ assert out["chain"]["frames"] == 8 and out["chain"]["pieces"] == {"one": [0, 3], "two": [5, 7]}+ bridge = out["frames"][4]+ assert bridge["source"] == {"between": [{"piece": "one", "frame": 3}, {"piece": "two", "frame": 5}], "t": 0.5, "bridge": True}+ assert bridge["place"] == 4 and bridge["judged"]["contact"]["reads"] in (True, False)+ assert out["chain"]["bridges"][0]["place"] == 4+ assert out["joins"][0]["bridge"] == 1+ assert gate(out["keyed_dir"]) == 0+++# --- what is kept ----------------------------------------------------------------------------------------------------++def test_a_hold_on_the_list_stays_and_the_same_hold_on_no_list_is_made_between(tmp_path):+ frames = walk(N + 6)+ frames[6] = frames[5]+ d = clip(tmp_path, "a", frames)+ meant = holds_file(tmp_path, (6, 6))+ out = make(tmp_path / "listed", [f"one={d}:0:12"], holds=[meant], interpolate=lambda a, b, t: pytest.fail("the hold is meant: no frame between"))+ assert out["exit"] == 0 and out["read"]["unlisted"] == 0+ assert out["read"]["table"]["figure"]["listedRuns"][0]["reason"] == "the figure stops on the ledge"+ got = delivered(out)+ assert got[6].tobytes() == got[5].tobytes()+ assert gate(out["keyed_dir"], meant) == 0+ assert gate(out["keyed_dir"]) == 1++ unlisted = make(tmp_path / "unlisted", [f"one={d}:0:12"])+ assert unlisted["read"]["unlisted"] == 0 and unlisted["held_fill"]["made"] == [6]+ assert gate(unlisted["keyed_dir"]) == 0++ narrowed = make(tmp_path / "narrowed", [f"one={d}:0:12"], holds=[meant], refuse="ghost", interpolate=lambda a, b, t: pytest.fail("a fault left out fills no hold meant"))+ assert narrowed["exit"] == 0 and narrowed["held_fill"]["made"] == []+++def test_a_hold_longer_than_a_drawing_on_threes_is_not_made_away_it_fails_until_it_is_listed(tmp_path):+ frames = walk(N + 6)+ for k in (6, 7, 8, 9):+ frames[k] = frames[5]+ d = clip(tmp_path, "a", frames)+ out = make(tmp_path / "unlisted", [f"one={d}:0:14"], interpolate=lambda a, b, t: pytest.fail("a hold the motion means is kept"))+ assert out["exit"] == chain.EXIT_SHOWN_AGAIN and "figure frames 6-9" in out["error"] and "longer than a drawing on threes" in out["error"]+ assert make(tmp_path / "listed", [f"one={d}:0:14"], holds=[holds_file(tmp_path, (6, 9))])["exit"] == 0+++def test_a_chain_s_last_frame_shown_again_has_no_next_pose_and_fails_by_its_number(tmp_path):+ frames = walk(N + 6)+ frames[12] = frames[11]+ d = clip(tmp_path, "a", frames)+ out = make(tmp_path, [f"one={d}:0:12"], interpolate=lambda a, b, t: pytest.fail("no pose after it to make a frame towards"))+ assert out["exit"] == chain.EXIT_SHOWN_AGAIN and "figure frame 12" in out["error"] and "closing pose" in out["error"]+++def test_a_piece_drawn_on_twos_keeps_its_drawings_and_says_so(tmp_path):+ twos = [walk_at(k // 2 * 2) for k in range(26)]+ d = clip(tmp_path, "a", twos)+ out = make(tmp_path, [f"one={d}:0:25"], interpolate=lambda a, b, t: pytest.fail("a drawing is not filled"))+ assert out["drawn_pieces"] == {"one": 2} and out["exit"] == chain.EXIT_SHOWN_AGAIN and "one is drawn on twos" in out["error"]+++def test_a_frame_with_every_try_refused_stays_named_and_fails_the_chain(tmp_path):+ frames = walk(N + 6)+ frames[6] = frames[5]+ d = clip(tmp_path, "a", frames)+ # a frame between that shows the picture before it: `held`, every fraction+ out = make(tmp_path, [f"one={d}:0:12"], interpolate=lambda a, b, t: a)+ assert out["exit"] == chain.EXIT_SHOWN_AGAIN and "figure frame 6" in out["error"]+ assert out["frames"][6]["refused"] and "held" in out["frames"][6]["refused"][0]["faults"]+ assert any("kept as filmed" in w for w in out["warnings"])+++# --- the faults that refuse a frame ----------------------------------------------------------------------------------++def finding(monkeypatch, *faults: str, when=lambda t: True, **measure) -> None:+ """The judge as it is, finding `faults` too in a frame made `when` its fraction says: a material whose frames read so."""+ real = held_fill.judge++ def judge(frame, a, b, t, *, reads, before=None):+ found, wrong = real(frame, a, b, t, reads=reads, before=before)+ return {**found, **measure}, wrong + [f for f in faults if when(t)]++ monkeypatch.setattr(held_fill, "judge", judge)+++def test_a_material_every_frame_of_which_reads_a_fault_fails_by_default_and_passes_with_the_fault_left_out(tmp_path, monkeypatch):+ finding(monkeypatch, "outline")+ d = clip(tmp_path, "a")+ places = places_file(tmp_path, [1, 1.5, 2, 3])+ every = make(tmp_path / "every", [f"one={d}:0:4"], places=places)+ assert every["status"] == "failed" and every["exit"] == chain.EXIT_SHOWN_AGAIN and every["refuse"] == list(held_fill.FAULTS)+ assert every["frames"][1]["refused"][0]["faults"] == ["outline"] and "kept_faults" not in every["frames"][1]+ assert "figure frame 2" in every["error"] and "--refuse" in every["error"]++ left_out = make(tmp_path / "left_out", [f"one={d}:0:4"], places=places, refuse="ghost,hole,doubled,held")+ assert left_out["exit"] == chain.EXIT_OK and left_out["read"]["unlisted"] == 0 and gate(left_out["keyed_dir"]) == 0+ cell = left_out["frames"][1]+ assert cell["source"] == {"between": [{"piece": "one", "frame": 1}, {"piece": "one", "frame": 2}], "t": 0.5}+ assert cell["kept_faults"] == ["outline"] and cell["judged"] and cell["refused"] == []+ assert "kept_faults" not in left_out["frames"][0]+ assert left_out["warnings"] == ["frame 1 kept with outline: found, and not named by --refuse"]+++def test_the_record_opens_with_the_faults_this_run_refused_for(tmp_path):+ d = clip(tmp_path, "a")+ make(tmp_path / "every", [f"one={d}:0:4"])+ make(tmp_path / "given", [f"one={d}:0:4"], refuse="held,hole,ghost")+ head = lambda name: json.loads((tmp_path / name / "out" / "chain.report.json").read_text())+ assert head("every")["refuse"] == list(held_fill.FAULTS)+ assert head("given")["refuse"] == ["ghost", "hole", "held"]+ assert list(head("given"))[:3] == ["kind", "producer", "refuse"]+++def test_the_faults_refuse_names_are_all_the_judge_can_find():+ from sprite_gen.video.interpolation_quality import faults++ over = dict.fromkeys(("dark_excess", "outline_loss", "ghost", "ghost_window", "torn", "hole", "doubled"), 1.0)+ assert set(faults(over)) | {"contact", "held"} == set(held_fill.FAULTS)++[email protected]("given, words", [("ghost,halo", "'halo' is no fault"), ("", "'' is no fault"), ("ghost,,held", "'' is no fault"), ("GHOST", "'GHOST' is no fault")])+def test_a_name_that_is_no_fault_is_an_error_before_anything_is_touched(tmp_path, given, words):+ d = clip(tmp_path, "a")+ earlier = tmp_path / "out" / "keyed"+ earlier.mkdir(parents=True)+ with pytest.raises(chain.ChainRefused, match=words):+ make(tmp_path, [f"one={d}:0:4"], refuse=given)+ assert earlier.is_dir()+ proc = _cli("--piece", f"one={d}:0:4", "--key", "green", "--refuse", given, "--out-dir", str(tmp_path / "cli"))+ assert proc.returncode == chain.EXIT_ERROR and words in proc.stderr and proc.stdout == ""+ assert not (tmp_path / "cli").exists()+++def test_held_refuses_a_frame_whatever_refuse_says(tmp_path):+ d = clip(tmp_path, "a")+ out = make(tmp_path, [f"one={d}:0:4"], places=places_file(tmp_path, [1, 1.5, 2, 3]), refuse="ghost", interpolate=lambda a, b, t: a)+ assert out["refuse"] == ["ghost", "held"]+ assert "held" in out["frames"][1]["refused"][0]["faults"] and "between" not in out["frames"][1]["source"]+ assert out["exit"] == chain.EXIT_SHOWN_AGAIN+++def test_the_bar_of_a_frame_made_off_its_time_refuses_whatever_refuse_says(tmp_path, monkeypatch):+ """Refused at its own time, and no fault at any other: a ghost band over the bar still refuses those."""+ finding(monkeypatch, "ghost", when=lambda t: abs(t - 0.5) < 1e-6, ghost_window=0.01)+ d = clip(tmp_path, "a")+ out = make(tmp_path, [f"one={d}:0:4"], places=places_file(tmp_path, [1, 1.5, 2, 3]), refuse="ghost,held")+ cell = out["frames"][1]+ assert "between" not in cell["source"] and cell["nearer_frame"] is True+ assert cell["refused"][0]["faults"] == ["ghost"] and all(t["window_over"] and not t["faults"] for t in cell["refused"][1:]) and cell["refused"][1:]+ assert out["exit"] == chain.EXIT_SHOWN_AGAIN+++def test_the_final_reading_fails_a_frame_shown_again_whatever_refuse_says(tmp_path):+ d = clip(tmp_path, "a")+ out = make(tmp_path, [f"one={d}:0:4"], places=places_file(tmp_path, [1, 2, 2, 3]), refuse="held", fill_held="off")+ assert out["exit"] == chain.EXIT_SHOWN_AGAIN and "figure frame 2" in out["error"] and "--refuse" not in out["error"]+++def test_a_cell_filled_and_a_bridge_keep_the_faults_they_were_made_with(tmp_path, monkeypatch):+ finding(monkeypatch, "outline")+ frames = walk(N + 6)+ frames[2] = frames[1]+ d = clip(tmp_path, "a", frames)+ out = make(tmp_path, [f"one={d}:0:4", f"two={d}:5:7"], bridge=[1], refuse="ghost,held,contact")+ assert out["exit"] == chain.EXIT_OK, out.get("error")+ filled = out["frames"][2]+ assert filled["source"] == {"between": [{"piece": "one", "frame": 1}, {"piece": "one", "frame": 3}], "t": 0.5}+ assert filled["kept_faults"] == ["outline"]+ assert out["chain"]["bridges"][0]["kept_faults"] == ["outline"] and out["frames"][5]["kept_faults"] == ["outline"]+ assert out["warnings"] == ["frames 2, 5 kept with outline: found, and not named by --refuse"]+++def test_a_cell_filled_keeps_its_own_faults_and_none_of_the_picture_it_showed(tmp_path, monkeypatch):+ """A bridge's frame shown twice: the second is filled, and its record is the frame made for it."""+ finding(monkeypatch, "outline", when=lambda t: abs(t - 0.5) > 0.01)+ d = clip(tmp_path, "a")+ places = places_file(tmp_path, [3, 4, 5, 5, 6, 7, 8])+ out = make(tmp_path, [f"one={d}:0:4", f"two={d}:5:7"], bridge=[2], places=places, refuse="ghost,held,contact")+ assert out["exit"] == chain.EXIT_OK, out.get("error")+ shown, filled = out["frames"][2], out["frames"][3]+ assert shown["source"]["bridge"] is True and shown["kept_faults"] == ["outline"]+ assert filled["source"]["t"] == 0.5 and "kept_faults" not in filled and filled["judged"]+++def test_a_cut_asked_with_no_refuse_refuses_for_every_fault_and_keeps_none(monkeypatch):+ finding(monkeypatch, "outline")+ frames = walk(12)+ frames[6] = frames[5]+ out, record = held_fill.fill(frames, between(), ring=False)+ assert record["made"] == [] and out[6] is frames[6]+ assert record["before"]["held_runs"][0]["faults"] == ["outline"]+ assert not any("kept_faults" in t for row in record["before"]["held_runs"][0]["tries"] for t in row["tries"])+++# --- no RIFE ---------------------------------------------------------------------------------------------------------++def _cli(*args: str, env: dict | None = None) -> subprocess.CompletedProcess:+ return subprocess.run([sys.executable, "-m", "sprite_gen.cli", "video-chain", *args], capture_output=True, encoding="utf-8", env=env)+++def test_no_rife_takes_the_nearer_frame_warns_and_records_it_and_gate_fails_it(tmp_path, monkeypatch):+ no_rife(monkeypatch, tmp_path)+ d = clip(tmp_path, "a")+ places = places_file(tmp_path, [2, 2.5, 3, 3.5, 4, 4.5, 5])+ args = ["--piece", f"one={d}:0:9", "--key", "green", "--places", str(places)]+ plain = _cli(*args, "--out-dir", str(tmp_path / "plain"))+ assert plain.returncode == 0, plain.stderr+ assert "video-chain: warning: 3 frames (1, 3, 5) took the nearer frame" in plain.stderr and "rife install" in plain.stderr+ report = json.loads((tmp_path / "plain" / "chain.report.json").read_text())+ assert report["status"] == "passed" and report["rife"]["why"] == "RIFE is not installed"+ assert all(c["source"].get("piece") == "one" and c["nearer_frame"] for c in report["frames"] if c["frame"] in (1, 3, 5))+ assert (tmp_path / "plain" / "keyed").is_dir()++ gated = _cli(*args, "--gate", "--out-dir", str(tmp_path / "gated"))+ assert gated.returncode == chain.EXIT_SHOWN_AGAIN+ assert "--gate: RIFE is not installed" in gated.stderr+ assert not (tmp_path / "gated" / "keyed").exists() and (tmp_path / "gated" / "keyed.refused").is_dir()+ assert json.loads((tmp_path / "gated" / "chain.report.json").read_text())["status"] == "failed"+++def test_no_rife_a_held_cell_and_a_bridge_warn_and_a_chain_with_nothing_to_make_says_nothing(tmp_path, monkeypatch):+ no_rife(monkeypatch, tmp_path)+ frames = walk(N + 6)+ frames[6] = frames[5]+ d = clip(tmp_path, "a", frames)+ held = make(tmp_path / "held", [f"one={d}:0:12", f"two={d}:14:16"], bridge=[1], interpolate=None)+ assert held["exit"] == 0 and held["held_fill"]["unmade"]["why"] == "RIFE is not installed"+ joined = " ".join(held["warnings"])+ assert "shown as filmed" in joined and "a join's frames between are the frames beside it" in joined and "rife install" in joined++ plain = clip(tmp_path, "plain")+ nothing = make(tmp_path / "nothing", [f"one={plain}:0:5", f"two={plain}:6:9"], interpolate=None)+ assert nothing["exit"] == 0 and nothing["warnings"] == [] and "rife" not in nothing and nothing["interpolator"] is None+++def test_a_rife_that_fails_is_an_error_never_a_chain_as_filmed(tmp_path):+ from sprite_gen.video import rife++ def broken(a, b, t):+ raise rife.RifeUnavailable("rife-ncnn-vulkan failed")++ d = clip(tmp_path, "a")+ with pytest.raises(ValueError, match="rife-ncnn-vulkan failed"):+ make(tmp_path, [f"one={d}:0:3", f"two={d}:5:7"], bridge=[1], interpolate=broken)+ assert json.loads((tmp_path / "out" / "chain.report.json").read_text())["status"] == "failed"+ assert not (tmp_path / "out" / "keyed").exists()+++# --- the pieces --------------------------------------------------------------------------------------------------------++def test_pieces_on_two_canvases_are_refused_and_nothing_is_touched(tmp_path):+ d = clip(tmp_path, "a")+ wider = clip(tmp_path, "b", [Image.new("RGBA", (130, 140), (0, 0, 0, 0))] * 3)+ earlier = tmp_path / "out" / "keyed"+ earlier.mkdir(parents=True)+ with pytest.raises(chain.ChainRefused, match="a chain is one canvas"):+ make(tmp_path, [f"one={d}:0:3", f"two={wider}:0:2"])+ assert earlier.is_dir()+++def test_pieces_on_two_keys_are_refused_as_is_a_key_no_report_or_flag_says(tmp_path):+ green, magenta = clip(tmp_path, "g", key="green"), clip(tmp_path, "m", key="magenta")+ with pytest.raises(chain.ChainRefused, match="keyed differently .*one green, two magenta"):+ make(tmp_path, [f"one={green}:0:3", f"two={magenta}:4:6"], key=None)+ with pytest.raises(chain.ChainRefused, match="keyed differently .*one green, --key magenta"):+ make(tmp_path, [f"one={green}:0:3"], key="magenta")+ bare = clip(tmp_path, "bare")+ with pytest.raises(chain.ChainRefused, match="no report says what two is keyed on"):+ make(tmp_path, [f"one={green}:0:3", f"two={bare}:4:6"], key=None)+ out = make(tmp_path, [f"one={green}:0:3", f"two={bare}:4:6"], key="green")+ assert out["key"] == "green" and [p["key_from"] for p in out["pieces"]] == ["frames.report.json", "--key"]+++def test_a_report_that_says_only_auto_says_no_key_and_a_brightness_cut_is_its_own(tmp_path):+ d = clip(tmp_path, "a")+ (d / "frames.report.json").write_text(json.dumps({"key": "auto"}))+ with pytest.raises(chain.ChainRefused, match="no report says"):+ make(tmp_path, [f"one={d}:0:3"], key=None)+ (d / "frames.report.json").write_text(json.dumps({"key": "auto", "alpha_mode": "brightness"}))+ assert make(tmp_path, [f"one={d}:0:3"], key=None)["key"] == "brightness"+++def test_opaque_frames_are_no_keyed_pieces_and_a_rate_is_one(tmp_path):+ opaque = clip(tmp_path, "o", [Image.new("RGBA", (120, 140), (9, 200, 9, 255))] * 4)+ with pytest.raises(chain.ChainRefused, match="opaque"):+ make(tmp_path, [f"one={opaque}:0:3"])+ slow, fast = clip(tmp_path, "s", fps=24.0), clip(tmp_path, "f", fps=30.0)+ with pytest.raises(chain.ChainRefused, match="different rates"):+ make(tmp_path, [f"one={slow}:0:3", f"two={fast}:4:6"])+ bare = clip(tmp_path, "bare")+ with pytest.raises(chain.ChainRefused, match="--out-fps needs the pieces' rate"):+ make(tmp_path, [f"one={bare}:0:3"], out_fps=60.0)++[email protected]("pieces, kw, words", [+ (["no-equals"], {}, "NAME=DIR:FROM:TO"),+ (["one={d}:x:3"], {}, "whole frame numbers"),+ (["one={d}:0:999"], {}, "holds frames 0.."),+ (["one={d}:5:2"], {}, "holds frames 0.."),+ (["one={d}:0:3", "one={d}:4:6"], {}, "two pieces are named one"),+ (["one={d}:0:3"], {"bridge": [1]}, "one piece has no join"),+ (["one={d}:0:3", "two={d}:4:6"], {"bridge": [1, 2]}, "2 times"),+ (["one={d}:0:3", "two={d}:4:6"], {"bridge": [-1]}, "0 or more"),+ (["one={d}:0:3"], {"out_fps": 0.0, "fps": 24.0}, "a rate above 0"),+ ([], {}, "no --piece"),+])+def test_what_is_no_chain_is_refused_in_words(tmp_path, pieces, kw, words):+ d = clip(tmp_path, "a")+ with pytest.raises(chain.ChainRefused, match=words.replace(".", r"\.")):+ make(tmp_path, [p.format(d=d) for p in pieces], **kw)+++def test_places_off_the_chain_or_no_list_are_refused(tmp_path):+ d = clip(tmp_path, "a")+ with pytest.raises(chain.ChainRefused, match=r"off the chain, whose frames are numbered 0\.\.3"):+ make(tmp_path, [f"one={d}:0:3"], places=places_file(tmp_path, [1, 3.5]))+ bad = tmp_path / "bad.json"+ for body in ('{"places": []}', '{"places": [1, "x"]}', "{", '{"places": [true]}'):+ bad.write_text(body)+ with pytest.raises(chain.ChainRefused, match="--places"):+ make(tmp_path, [f"one={d}:0:3"], places=bad)+ with pytest.raises(chain.ChainRefused, match="give one time"):+ make(tmp_path, [f"one={d}:0:3"], places=bad, out_fps=30.0, fps=24.0)+++def test_a_chain_never_writes_over_what_it_reads(tmp_path):+ d = clip(tmp_path, "a")+ with pytest.raises(SystemExit, match="video-chain"):+ chain.make_chain([f"one={d}:0:3"], d, key="green", interpolate=between())+++# --- a reading of nothing --------------------------------------------------------------------------------------------++def test_a_chain_that_draws_nothing_is_an_error_at_the_command_line_and_in_the_report(tmp_path):+ empty = clip(tmp_path, "e", [Image.new("RGBA", (120, 140), (0, 0, 0, 0))] * 4)+ proc = _cli("--piece", f"one={empty}:0:3", "--key", "green", "--gate", "--out-dir", str(tmp_path / "out"))+ assert proc.returncode == chain.EXIT_ERROR+ assert holds_mod.NOTHING in proc.stderr and proc.stdout == ""+ report = json.loads((tmp_path / "out" / "chain.report.json").read_text())+ assert report["status"] == "failed" and report["read"]["inspected"] == 0+ assert not (tmp_path / "out" / "keyed").exists()+++def test_a_chain_of_one_frame_reads_no_frame_against_another_and_is_an_error(tmp_path):+ d = clip(tmp_path, "a")+ proc = _cli("--piece", f"one={d}:3:3", "--key", "green", "--out-dir", str(tmp_path / "out"))+ assert proc.returncode == chain.EXIT_ERROR and holds_mod.NOTHING in proc.stderr+ assert json.loads((tmp_path / "out" / "chain.report.json").read_text())["read"]["inspected"] == 0+++def test_a_chain_none_of_whose_joins_can_be_read_is_an_error(tmp_path):+ """Pieces that do not move have no step to read a join in: a chain does not pass on a join it could not read."""+ still = clip(tmp_path, "s", [walk_at(0)] * 6)+ with pytest.raises(chain.ChainRefused, match="no join was read: one into two: the pieces do not move"):+ make(tmp_path, [f"one={still}:0:2", f"two={still}:3:5"], holds=[holds_file(tmp_path, (0, 5))], interpolate=lambda a, b, t: a)+ assert json.loads((tmp_path / "out" / "chain.report.json").read_text())["status"] == "failed"+++def test_a_join_that_cannot_be_read_beside_one_that_can_warns(tmp_path):+ blank = Image.new("RGBA", (120, 140), (0, 0, 0, 0))+ frames = walk(10) + [blank] + walk(10)+ d = clip(tmp_path, "a", frames)+ out = make(tmp_path, [f"one={d}:0:5", f"two={d}:6:10", f"three={d}:12:15"], interpolate=lambda a, b, t: pytest.fail("nothing to make"), near=0)+ assert [j["reads"] for j in out["joins"]] == [True, False]+ assert any("could not be read: no figure on two 10" in w for w in out["warnings"])+++# --- the record ------------------------------------------------------------------------------------------------------++def test_the_record_gives_each_frame_its_source_judged_values_and_refused_tries(tmp_path):+ d = clip(tmp_path, "a", fps=24.0)+ calls = []++ def fussy(a, b, t):+ """The stand-in's frame, but its first try at each place shows the frame before it: `held`, refused."""+ calls.append(t)+ return a if len(calls) == 1 else good(a, b, t)++ good = between()+ out = chain.make_chain([f"one={d}:0:4"], tmp_path / "out", key="green", interpolate=fussy, places=places_file(tmp_path, [1, 1.5, 2, 3]))+ report = json.loads((tmp_path / "out" / "chain.report.json").read_text())+ assert report["kind"] == chain.REPORT_KIND and report["status"] == "passed" and out["exit"] == chain.EXIT_OK+ made = report["frames"][1]+ assert made["source"]["between"] == [{"piece": "one", "frame": 1}, {"piece": "one", "frame": 2}]+ assert made["place"] == 1.5 and made["source"]["t"] != 0.5 # made again at another fraction+ assert made["refused"][0]["t"] == 0.5 and "held" in made["refused"][0]["faults"] and "a" in made["refused"][0]["shows"]+ for value in ("outline_loss", "dark_excess", "hole", "doubled", "contact"):+ assert value in made["judged"] and value in made["refused"][0]["judged"]+ assert report["frames"][0] == {"frame": 0, "place": 1.0, "source": {"piece": "one", "frame": 1}, "refused": []}+ assert report["time"] == {"kind": "places", "fps": 24.0, "places_file": str((tmp_path / "places.json").resolve()), "frames": 4}+ assert report["interpolator"] == {"kind": "injected"} and out["report"].endswith("chain.report.json")+ piece = report["pieces"][0]+ assert (piece["name"], piece["from"], piece["to"], piece["key"]) == ("one", 0, 4, "green") and len(piece["source"]["sha256"]) == 64+++def test_a_join_tells_its_pose_distance_in_steps_and_the_closer_poses_and_takes_none(tmp_path):+ """The walk's cycle comes back: the join far from its pose has a closer one a few frames off, and it stays where it was given."""+ d = clip(tmp_path, "a")+ out = make(tmp_path, [f"one={d}:0:6", f"two={d}:14:20"], near=3, bridge=[1])+ join = out["joins"][0]+ assert join["from"] == {"piece": "one", "frame": 6} and join["into"] == {"piece": "two", "frame": 14}+ assert join["reads"] is True and join["steps"] > 1 and join["step"] > 0 and join["near"] == 3+ closer = join["closer"]+ assert closer and closer[0]["steps"] < join["steps"] and all(a["steps"] <= b["steps"] for a, b in zip(closer, closer[1:]))+ assert len(closer) <= chain.NEAR_SHOWN and join["closer_found"] >= len(closer)+ assert all(abs(c["from"]["frame"] - 6) <= 3 and abs(c["into"]["frame"] - 14) <= 3 for c in closer)+ assert out["frames"][6]["source"] == {"piece": "one", "frame": 6} and out["frames"][8]["source"] == {"piece": "two", "frame": 14}+++def test_a_frame_of_a_piece_is_delivered_byte_for_byte_and_a_chain_with_none_to_make_copies_them_all(tmp_path):+ d = clip(tmp_path, "a")+ out = make(tmp_path, [f"one={d}:0:5", f"two={d}:6:9"], interpolate=lambda a, b, t: pytest.fail("nothing to make"))+ got = sorted(Path(out["keyed_dir"]).glob("*.png"))+ want = sorted((d / "keyed").glob("*.png"))[:10]+ assert [p.read_bytes() for p in got] == [p.read_bytes() for p in want]+ assert [p.name for p in got] == [f"frame-{k + 1:04d}.png" for k in range(10)]+ assert out["held_fill"]["made"] == [] and out["read"]["unlisted"] == 0+++def test_a_frame_made_keeps_the_canvas_and_where_the_figure_stands(tmp_path):+ d = clip(tmp_path, "a")+ out = make(tmp_path, [f"one={d}:0:4"], places=places_file(tmp_path, [1, 1.5, 2]))+ got = delivered(out)+ assert got[1].size == (120, 140) and got[1].tobytes() == walk_at(1.5).tobytes()+++def test_an_earlier_run_s_frames_are_not_handed_over_by_a_failed_one(tmp_path):+ d = clip(tmp_path, "a")+ assert make(tmp_path, [f"one={d}:0:4"])["exit"] == 0+ held = walk(N + 6)+ held[4] = held[3]+ bad = clip(tmp_path, "bad", held)+ out = make(tmp_path, [f"one={bad}:0:4"], interpolate=lambda a, b, t: pytest.fail("the closing pose is kept"))+ assert out["exit"] == chain.EXIT_SHOWN_AGAIN and not (tmp_path / "out" / "keyed").exists()+ assert make(tmp_path, [f"one={d}:0:4"])["exit"] == 0+ assert not (tmp_path / "out" / "keyed.refused").exists()+++def test_the_command_line_says_what_became_of_the_chain(tmp_path):+ d = clip(tmp_path, "a")+ proc = _cli("--piece", f"one={d}:0:5", "--piece", f"two={d}:6:9", "--key", "green", "--out-dir", str(tmp_path / "out"))+ assert proc.returncode == 0, proc.stderr+ said = json.loads(proc.stdout)+ assert said["frames"] == 10 and said["made"] == 0 and said["unlisted"] == 0 and said["poses_cells"] == {"before": "10/10", "after": "10/10"}+ assert said["refuse"] == list(held_fill.FAULTS)+ assert said["joins"][0]["from"] == {"piece": "one", "frame": 5} and said["refused_dir"] is None++[email protected](not (shutil.which("ffmpeg") and shutil.which("ffprobe")), reason="ffmpeg/ffprobe not installed")+def test_clips_from_video_frames_say_their_own_key_and_rate_and_two_keys_refuse_the_chain(tmp_path):+ """Asked `--key auto`, `video-frames` names the key it read, and a chain reads it and the rate from its report."""+ from sprite_gen.video import frames as frames_mod++ def keyed(name: str, key: tuple[int, int, int], body: tuple[int, int, int]) -> tuple[Path, dict]:+ src = tmp_path / name / "src"+ src.mkdir(parents=True)+ for k in range(12):+ im = Image.new("RGB", (128, 128), key)+ ImageDraw.Draw(im).rectangle((40, 30, 56 + 3 * k, 100), fill=body)+ im.save(src / f"f-{k:04d}.png")+ video = tmp_path / name / "clip.mp4"+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-framerate", "24", "-i", str(src / "f-%04d.png"), "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "12", str(video)], check=True)+ return tmp_path / name / "frames", frames_mod.run_frames(video, tmp_path / name / "frames", key="auto", allow_edge_contact=False, report_path=None)++ green, read_green = keyed("g", (0, 255, 0), (200, 40, 40))+ magenta, read_magenta = keyed("m", (255, 0, 255), (40, 200, 200))+ assert read_green["key_read"] == "green" and read_magenta["key_read"] == "magenta"+ out = chain.make_chain([f"one={green}:0:5", f"two={green}:6:11"], tmp_path / "out", interpolate=lambda a, b, t: pytest.fail("nothing to make"))+ assert out["exit"] == chain.EXIT_OK and out["key"] == "green" and out["time"] == {"kind": "clip", "fps": 24.0, "frames": 12}+ assert {p["key_from"] for p in out["pieces"]} == {"frames.report.json"}+ with pytest.raises(chain.ChainRefused, match="keyed differently .*one green, two magenta"):+ chain.make_chain([f"one={green}:0:5", f"two={magenta}:6:11"], tmp_path / "out2")++[email protected]_rife+def test_rife_makes_a_chain_s_bridge_and_places_with_none_shown_again(tmp_path):+ d = clip(tmp_path, "a", fps=24.0)+ proc = _cli("--piece", f"one={d}:0:6", "--piece", f"two={d}:7:12", "--bridge", "0", "--out-fps", "48", "--out-dir", str(tmp_path / "out"), "--key", "green")+ report = json.loads((tmp_path / "out" / "chain.report.json").read_text())+ assert report["interpolator"]["kind"] != "injected" and report["time"]["out_fps"] == 48+ assert proc.returncode == 0, proc.stderr+ assert report["read"]["unlisted"] == 0 and gate(tmp_path / "out" / "keyed") == 0+ assert Image.open(sorted((tmp_path / "out" / "keyed").glob("*.png"))[1]).size == (120, 140)diff --git a/tests/video/test_held_fill.py b/tests/video/test_held_fill.pyindex ec8174a..d239139 100644--- a/tests/video/test_held_fill.py+++ b/tests/video/test_held_fill.py@@ -396,7 +396,7 @@ def test_a_frame_between_that_shows_both_poses_beside_it_is_not_made_again():run = record["before"]["held_runs"][0]assert (run["start"], run["length"], run["filled"], run["faults"]) == (1, 2, False, ["held"])assert calls == [0.5]- assert run["tries"][0]["tries"] == [{"t": 0.5, "faults": ["held"], "shows": ["a", "b"]}]+ assert [{k: v for k, v in tried.items() if k != "judged"} for tried in run["tries"][0]["tries"]] == [{"t": 0.5, "faults": ["held"], "shows": ["a", "b"]}]assert record["made"] == [] and [o.tobytes() for o in out] == [f.tobytes() for f in frames]