Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
feat(stop, video, face-bake): video-stop fills its held cells by default (`--fill-held auto|off`), its opening pose and closing still kept, its sidecar recording `held_fill` and `holds`; a Grok clip (`video`, `video-extend`, `video-edit`, `video-resume`) and a face bake are read for a picture shown again and warn of it, filling nothing
Soohong Kimfa1a49697adb
diff --git a/docs/face-parts.md b/docs/face-parts.mdindex 58c2862..72b9060 100644--- a/docs/face-parts.md+++ b/docs/face-parts.md@@ -223,12 +223,14 @@ With `--play`, the sound track contains the clip's own sound for its `own_mouth`| `frames/frame-NNNNN.png` | RGBA frames at the pack's size. || `voice-baked.wav` | Whole sound track, mono 48 kHz, as long as the frames. || `voice-padded.wav` | Voice with lead and tail silence. |-| `bake.json` | Per frame body, cell, face frame, layer state, level, pixels changed outside the weight, and composite, body, and layer steps. It also records set, rest, `own_mouth_frames`, `line_start`, `wait_frames`, levels, `over_line`, `over_sum`, and verdict. |+| `bake.json` | Per frame body, cell, face frame, layer state, level, pixels changed outside the weight, and composite, body, and layer steps. It also records set, rest, `own_mouth_frames`, `line_start`, `wait_frames`, levels, `over_line`, `over_sum`, `held`, and verdict. || `baked.mp4` | Frames over the matte with sound, when `--video` is set. || `beside.mp4` | Supplied frames on the left and bake on the right, with bake sound, when `--beside` is set. |Steps are read on the face around the mouth in reference coordinates. A composite step over 1.4 times the largest of the body's own step, the layer's own step, and the body's median step is `over_line`. Body and layer motion in one frame can add up even when each is within the line. A frame that is `over_line` and also exceeds the sum of the body and layer steps is `over_sum`.+The body is also read for a picture shown again: a frame whose body cell shows the picture of the frame before, so the body stands still for a frame mid-motion. Two cells are one picture by `held_fill`'s rule ([loop repair](loop-repair.md) section 7), read on the cells as the pack has them. `bake.json` records it as `held`: `frames`, `poses`, the thresholds, and `held_runs` (`start`, `length`, and `body`, the clip and cell of each frame). A run a clip means is recorded with a `why` and a `kind` and not warned of: one longer than three frames (`motion-hold`), the opening or closing pose of a clip played once (cells of one clip that is not the loop, from its first cell or to its last), or cells a body row of the pack lists as `holds` (`from`, `to`, both in, `kind`, `reason`, as a strip's `holds`). Any other run, within a clip, across the loop's wrap, or where a clip comes back to the loop, prints `face-bake: warning: frames A-B show one body picture (…)` with the cells and the poses over the frames. The bake makes no frame: the pack's cells are baked as they are, and the verdict does not change. Make the pack from frames whose held cells are made again (`video-loop --fill-held auto`).+If the planner finds no suitable frame within the body clip and one round of the loop, `face-bake` stops and names the reason. The bake is refused with exit code 1 and verdict `refused` if any frame is `over_sum` or if any pixel outside the layer's weight changes. The frames are still written for inspection.## What it takes from sprite-gendiff --git a/docs/video-pipeline.md b/docs/video-pipeline.mdindex c56fcfa..f170339 100644--- a/docs/video-pipeline.md+++ b/docs/video-pipeline.md@@ -1150,6 +1150,7 @@ sprite-gen video-stop --frames-dir run/frames/keyed --loop run/loop/run.strip.js```- **Speed and the frame cap.** `--speed 2` plays every other frame (still kept last); `--max-frames N` (at least 2) spaces N frames evenly from the first to the still. Each frame is shown one clip tick (`--fps` defaults to the loop's `source_cut` fps, else 24). Strips wider than 32,000 px are refused; pass `--max-frames` or `--speed 2`.+- **Held cells.** A clip that stalls shows one picture on two or three cells in a row. The frames shown are read for this as filmed (`held_fill.same_steps`), and by default (`--fill-held auto`) each such run's cells after its first are made again with RIFE between the run's first cell and the next pose, as `video-loop` makes a cut played once ([loop repair](loop-repair.md) section 7), on the frames at their own size; a cell made stands where the held cell stood. The stop's opening pose and its closing still (the clip's first frame, held) are kept, and so are a run longer than three cells and a clip drawn on twos or threes. A frame between that the judge refuses keeps the run as filmed, and with no RIFE installed every held cell is played as filmed; each prints a `video-stop: warning:` line, the second naming the install command. These are the only frames a stop makes between two others. `--fill-held off` plays every frame as filmed, with a warning line for each held run. The report and the sidecar record `held_fill` as a loop's does (the held runs before and as delivered, the cells made, the poses over the cells), and the sidecar lists the runs kept as the motion means them as `holds` (`from`, `to`, `kind`, `reason`; `held_fill.intended`), which `inspect-holds` and a scene read as holds meant; a stop with no held cell asks for no frame and is the same pictures as before.The outputs are `<name>.strip.png`, `<name>.strip.json`, `<name>.gif` (plays once), `<name>.webp` (plays once), and `<name>.stop.report.json` (or `--report PATH`).diff --git a/docs/video.md b/docs/video.mdindex 15040c9..c6589bc 100644--- a/docs/video.md+++ b/docs/video.md@@ -125,6 +125,28 @@ the request — the unfinished report's `auth_source`; refresh an expired loginagain. Each resume polls afresh, so a clip whose download failed is fetched from theURL the new poll names.+### A picture shown again++A provider sometimes repeats a frame: two frames in a row show one picture, and the+motion stalls there. `video`, `video-extend`, `video-edit` and `video-resume` read the+clip they publish for that, frame by frame with ffmpeg, as video-loop reads its cells+(docs/loop-repair.md section 7): a flat canvas filmed round the subject (the commonest+colour of a 4 px border, if it is half the border or more) is not read, so the subject's+pixels decide; a scene filmed whole is read on every pixel. The clip is published as+the provider made it; nothing is filled. A repeated frame is named on stderr,++```+video: warning: clip.mp4 shows one picture on frames 40-41 (143/144 poses/frames): the clip repeats a frame there, kept as the provider made it; video-loop makes such cells again between the poses beside them (docs/loop-repair.md section 7)+```++and the report records the reading as `held`: `read`, `frames`, `poses`, `cells`,+`background` (the canvas colour, or `null`), the thresholds read with (`pixel_same`,+`changed_max`, `hold_max`) and `held_runs` (`start`, `length`). The clip's opening and+closing pose and a run longer than a drawing on threes (`hold_max`, 3) are recorded with+a `why` and not warned of — a still at either end, or a hold the motion means. With no+ffmpeg, or a file ffmpeg cannot read, `held` is `{"read": false, "why": …}` and the run+says its frames were not read; the clip is still published.+### An unfinished generationxAI accepted the request and the run ended before it did — the poll timeout came with@@ -165,8 +187,8 @@ it)`), or `xai: response was not valid JSON` for a whole answer that is not JSON`video.respect_moderation: false` is:`<verb>: generation <id> refused by the provider's content policy (HTTP 200) respect_moderation=false; nothing was written`.- Output is whatever the model returns (typically H.264 mp4 with audio unless- `--no-audio`). Downstream frame extraction is a separate step and not part of- this command.+ `--no-audio`). It is read for a picture shown again (above) and published as it+ came; downstream frame extraction is a separate step and not part of this command.## Relateddiff --git a/sprite_gen/gen/video.py b/sprite_gen/gen/video.pyindex 4b4a859..92e3d28 100644--- a/sprite_gen/gen/video.py+++ b/sprite_gen/gen/video.py@@ -371,6 +371,7 @@ class VideoResult:output_duration: float | None = None # extend / edit: ffprobe seconds of the published clipextra: dict[str, Any] = field(default_factory=dict)facing: dict[str, Any] | None = None+ held: dict[str, Any] | None = None # the published clip read for a picture shown again (`read_held`), by the CLIdef to_dict(self) -> dict[str, Any]:return {@@ -400,9 +401,105 @@ class VideoResult:"downloads": self.downloads,**({"extra": self.extra} if self.extra else {}),**({"facing": self.facing} if self.facing is not None else {}),+ **({"held": self.held} if self.held is not None else {}),}+# A clip's frames read for a picture shown again (`read_held`). The canvas `video-canvas` films on is one flat colour: the+# commonest colour of the first frame's border (BORDER_PX wide, read in eighths of each channel), where BACKGROUND_SHARE+# or more of the border lies within BACKGROUND_TOL of it (each channel, 0..1), is the background, and a frame's pixels+# within BACKGROUND_TOL of it are not the subject. A clip with no such border (a scene filmed whole) is read on every pixel.+BORDER_PX = 4+BACKGROUND_TOL = 0.12+BACKGROUND_SHARE = 0.5+++def _background(rgba: Any) -> list[float] | None:+ """The flat colour the clip is filmed on, read on its first frame's border (see above), or None."""+ from sprite_gen._deps import np++ b = BORDER_PX+ ring = np.concatenate([rgba[:b].reshape(-1, 4), rgba[-b:].reshape(-1, 4), rgba[:, :b].reshape(-1, 4),+ rgba[:, -b:].reshape(-1, 4)])[:, :3].astype(np.float32) / 255+ bins = np.minimum(np.floor(ring * 8).astype(int), 7)+ codes = bins[:, 0] * 64 + bins[:, 1] * 8 + bins[:, 2]+ colour = np.median(ring[codes == int(np.bincount(codes).argmax())], axis=0)+ share = float((np.abs(ring - colour).max(axis=1) <= BACKGROUND_TOL).mean())+ return [round(float(c), 4) for c in colour] if share >= BACKGROUND_SHARE else None+++def read_held(clip: Path) -> dict[str, Any]:+ """The published clip's frames read for a picture shown again, as `video-loop` reads a cut (`held_fill.same_steps`,+ docs/loop-repair.md section 7): each step of two frames on the subject (the frame less the canvas it is filmed on,+ `_background`), decoded by ffmpeg two frames at a time. The record: `read`, the frames, the background colour (None:+ every pixel), the poses over the frames, and each run of frames showing one picture (`start`, `length`), with `why`+ where the engine keeps such a run as the motion's own — longer than `held_fill.HOLD_MAX`, or the clip's opening or+ closing pose — and none where `video-loop` would make its frames again between the poses beside them. Nothing is+ changed: the provider's frames are the clip, and the material its loops are cut from. A clip ffmpeg cannot read is+ `read` false, with `why`."""+ from PIL import Image++ from sprite_gen._deps import np+ from sprite_gen.video import held_fill++ ffmpeg, ffprobe = shutil.which("ffmpeg"), shutil.which("ffprobe")+ if not ffmpeg or not ffprobe:+ return {"read": False, "why": "ffmpeg and ffprobe are needed to read its frames (install ffmpeg)"}+ probe = subprocess.run([ffprobe, "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height",+ "-of", "json", str(clip)], capture_output=True, text=True)+ try:+ stream = json.loads(probe.stdout)["streams"][0]+ width, height = int(stream["width"]), int(stream["height"])+ except (ValueError, KeyError, IndexError, TypeError):+ return {"read": False, "why": f"ffprobe found no video stream ({probe.stderr.strip()[:200] or 'no answer'})"}+ size = width * height * 4+ proc = subprocess.Popen([ffmpeg, "-v", "error", "-nostdin", "-i", str(clip), "-map", "0:v:0", "-f", "rawvideo",+ "-pix_fmt", "rgba", "pipe:1"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)+ same: list[bool] = []+ background = None+ previous = None+ assert proc.stdout is not None+ while len(data := proc.stdout.read(size)) == size:+ rgba = np.frombuffer(data, np.uint8).reshape(height, width, 4).copy()+ if previous is None:+ background = _background(rgba)+ if background is not None:+ off = np.abs(rgba[..., :3].astype(np.float32) / 255 - np.asarray(background, np.float32)).max(axis=-1)+ rgba[off <= BACKGROUND_TOL, 3] = 0+ frame = Image.fromarray(rgba, "RGBA")+ if previous is not None:+ same.append(held_fill.same_steps([previous, frame])[0])+ previous = frame+ error = proc.stderr.read().decode("utf-8", "replace").strip() if proc.stderr else ""+ if proc.wait() != 0 or previous is None:+ return {"read": False, "why": f"ffmpeg could not read its frames ({error[:200] or 'no frame'})"}+ n = len(same) + 1+ rows = []+ for run in held_fill.runs(same):+ why = (f"held {run['length']} frames, longer than a drawing on threes ({held_fill.HOLD_MAX}): a hold the motion means"+ if run["length"] > held_fill.HOLD_MAX else+ "the clip's opening pose" if run["start"] == 0 else+ "the clip's closing pose" if run["start"] + run["length"] == n else None)+ rows.append({**run, **({"why": why} if why else {})})+ reading = held_fill.reading(same)+ return {"read": True, "frames": n, "background": background, "pixel_same": held_fill.PIXEL_SAME,+ "changed_max": held_fill.CHANGED_MAX, "hold_max": held_fill.HOLD_MAX, "cells": reading["cells"],+ "poses": reading["poses"], "held_runs": rows}+++def held_lines(clip: Path, record: dict[str, Any]) -> list[str]:+ """What the reading found, in words: each run of frames showing one picture that the engine does not keep as the+ motion's own, or why the frames were not read. A run kept as the motion's own says nothing."""+ from sprite_gen.video import held_fill++ if not record["read"]:+ return [f"{clip.name}: its frames were not read for a picture shown again — {record['why']}"]+ return [f"{clip.name} shows one picture on frames {r['start']}-{r['start'] + r['length'] - 1} "+ f"({held_fill.said(record)} poses/frames): the clip repeats a frame there, kept as the provider made it; "+ "video-loop makes such cells again between the poses beside them (docs/loop-repair.md section 7)"+ for r in record["held_runs"] if "why" not in r]++def _validate(request: VideoRequest) -> None:validate_facing(request.facing, request.facing_fix)if request.direction not in (None, *handed_mod.VIEWS):@@ -1067,6 +1164,10 @@ def _publish_report(args: argparse.Namespace, make: Callable[[], VideoResult], *if report_path is not None:atomic_write_text(report_path, json.dumps(unfinished.to_dict(), ensure_ascii=False, indent=2) + "\n")raise+ # The clip as published, read for a picture shown again (docs/loop-repair.md section 7): named, never changed.+ result.held = read_held(result.out)+ for line in held_lines(result.out, result.held):+ print(f"{verb or 'video'}: warning: {line}", file=sys.stderr)payload = result.to_dict()if report_path is not None:atomic_write_text(report_path, json.dumps(payload, ensure_ascii=False, indent=2) + "\n")@@ -1089,7 +1190,7 @@ def _run(args: argparse.Namespace) -> int:reference_images=list(args.reference_images or []),direction=args.direction, facing=args.facing, facing_fix=args.facing_fix,)- return _publish_report(args, lambda: generate_video(request))+ return _publish_report(args, lambda: generate_video(request), verb="video")def _run_extend(args: argparse.Namespace) -> int:@@ -1104,7 +1205,7 @@ def _run_edit(args: argparse.Namespace) -> int:def _run_resume(args: argparse.Namespace) -> int:request = ResumeRequest(request_id=args.request_id, out=args.out)- return _publish_report(args, lambda: resume_video(request))+ return _publish_report(args, lambda: resume_video(request), verb="video-resume")def _build_parser() -> argparse.ArgumentParser:diff --git a/sprite_gen/video/face_bake.py b/sprite_gen/video/face_bake.pyindex e0dc8c2..76e7c0d 100644--- a/sprite_gen/video/face_bake.py+++ b/sprite_gen/video/face_bake.py@@ -16,6 +16,12 @@ cell's anchor, what of the body stays on top over that) and read where the facethe layer's own step and the body's median step is over the line (`over_line`). The body and the layer moving inthe same frame can each be within the line and still add up past it; a frame over the line and over the sum of thetwo steps as well is one the laying put in (`over_sum`), and a bake with one is refused.+- **held**: frames whose body cell shows the picture of the frame before (`held_fill.same_steps`, on the cells as the pack+ has them), the body standing still for a frame mid-motion (docs/loop-repair.md section 7). A run a clip means is+ recorded and not warned of: longer than `held_fill.HOLD_MAX` frames, the opening or closing pose of a clip played+ once (cells of one clip that is not the loop, from its first cell or to its last), or cells a pack's body row lists+ as `holds` (`from`, `to`, both in, a strip's `holds`). Any other is named in a warning and baked as the pack has it:+ the bake makes no frame."""from __future__ import annotations@@ -25,6 +31,7 @@ import hashlibimport jsonimport shutilimport subprocess+import sysimport tempfileimport wavefrom pathlib import Path@@ -36,6 +43,7 @@ from sprite_gen._deps import npfrom sprite_gen.util.console import utf8_streamsfrom sprite_gen.video import face_layer as flfrom sprite_gen.video import face_pack+from sprite_gen.video import held_fill as held_fill_modPROG = "face-bake"RATE = 48000@@ -101,6 +109,66 @@ def _matrix(six: list[float]) -> np.ndarray:return np.array([six[:3], six[3:], [0.0, 0.0, 1.0]])+def _meant(cells: list[tuple[str, int]], bodies: dict[str, dict[str, Any]]) -> tuple[str, str] | None:+ """Why a run of baked frames showing one body picture is a hold a clip means, and its kind, or None: the body+ cells it shows (`cells`, one a frame) read as the clips they are cells of."""+ if len(cells) > held_fill_mod.HOLD_MAX:+ return (f"held {len(cells)} frames, longer than a drawing on threes ({held_fill_mod.HOLD_MAX}): a hold the motion "+ "means"), "motion-hold"+ names = {name for name, _ in cells}+ if len(names) != 1:+ return None+ name = names.pop()+ b, ks = bodies[name], [k for _, k in cells]+ if ks != list(range(ks[0], ks[0] + len(ks))):+ return None # across the loop's wrap+ for h in b.get("holds") or []:+ if h["from"] <= ks[0] and ks[-1] <= h["to"]:+ return str(h.get("reason") or f"a hold the clip {name} lists"), str(h.get("kind") or "listed")+ if b.get("loop"):+ return None+ if ks[0] == 0:+ return f"the clip {name}'s opening pose", "opening"+ if ks[-1] == len(b["cells"]) - 1:+ return f"the clip {name}'s closing pose", "closing"+ return None+++def held_reading(shown: list[tuple[str, int]], same: list[bool], bodies: dict[str, dict[str, Any]]) -> dict[str, Any]:+ """The bake's body read for a picture shown again: its frames, poses and held runs (`held_fill.reading`), each run+ with the body cells it shows and, where a clip means it, why (`_meant`)."""+ record = {**held_fill_mod.reading(same), "pixel_same": held_fill_mod.PIXEL_SAME,+ "changed_max": held_fill_mod.CHANGED_MAX, "hold_max": held_fill_mod.HOLD_MAX}+ for run in record["held_runs"]:+ cells = shown[run["start"]:run["start"] + run["length"]]+ run["body"] = [[name, k] for name, k in cells]+ meant = _meant(cells, bodies)+ if meant is not None:+ run["why"], run["kind"] = meant+ record.pop("cells")+ record["frames"] = len(shown)+ return record+++def said(record: dict[str, Any]) -> str:+ """The body's poses over the bake's frames, as a person is told them: `poses/frames`."""+ return f"{record['poses']}/{record['frames']}"+++def held_lines(record: dict[str, Any]) -> list[str]:+ """A warning for each held run of the bake no clip means."""+ lines = []+ for run in record["held_runs"]:+ if "why" in run:+ continue+ end = run["start"] + run["length"] - 1+ cells = ", ".join(f"{name}:{k}" for name, k in run["body"])+ lines.append(f"frames {run['start']}-{end} show one body picture ({cells}; {said(record)} poses/frames): "+ "the body stands still there mid-motion, baked as the pack has it — make the pack from frames whose "+ "held cells are made again (video-loop --fill-held auto, docs/loop-repair.md section 7)")+ return lines++def bake(pack_dir: Path, voice_path: Path, out: Path, *, play: str | None = None, start: int = 0, tags: list[str] | None = None,lead: float = 0.5, tail: float = 0.6) -> dict[str, Any]:pack = load_pack(pack_dir)@@ -139,9 +207,22 @@ def bake(pack_dir: Path, voice_path: Path, out: Path, *, play: str | None = Nonereturn keeps[name, k]rows, prev = [], None+ # the body's steps, read on the cells as the pack has them: a pair of cells once, however often it is shown+ steps: dict[tuple[tuple[str, int], tuple[str, int]], bool] = {}+ shown: list[tuple[str, int]] = []+ same: list[bool] = []+ last_cell = Nonefor t, f in enumerate(plan["frames"]):b = bodies[f["body"]]cell = Image.open(pack_dir / b["cells"][f["cell"]]).convert("RGBA")+ here = (f["body"], f["cell"])+ if shown:+ pair = (shown[-1], here)+ if pair not in steps:+ steps[pair] = pair[0] == pair[1] or held_fill_mod.same_steps([last_cell, cell])[0]+ same.append(steps[pair])+ shown.append(here)+ last_cell = cellto_body = _matrix(b["to_body"][f["cell"]])sp = None if f["face"] is None else sprite(f["face"])laid = fl.lay(cell, sp, to_body, keep(f["body"], f["cell"]))@@ -188,8 +269,11 @@ def bake(pack_dir: Path, voice_path: Path, out: Path, *, play: str | None = None"off_frames": sum(1 for r in rows if r["layer"] == "off"),"outside_changed_px_max": max((r["outside_changed_px"] for r in rows), default=0),"jump_line": fl.JUMP_LINE, "body_median_step": med, "over_line": over_line, "over_sum": over_sum,- "verdict": "refused" if refused else "pass", "refused": refused, "rows": rows}+ "verdict": "refused" if refused else "pass", "refused": refused,+ "held": held_reading(shown, same, bodies), "rows": rows}(out / "bake.json").write_text(json.dumps(report, ensure_ascii=False, indent=1), encoding="utf-8")+ for line in held_lines(report["held"]):+ print(f"{PROG}: warning: {line}", file=sys.stderr)return report@@ -258,6 +342,8 @@ def run(**kwargs: object) -> int:print(json.dumps({"out": str(out), "frames": report["frames"], "set": report["set"], "rest": report["rest"],"line_start": report["line_start"], "wait_frames": report["wait_frames"], "talk_frames": report["talk_frames"],"over_line": report["over_line"], "over_sum": report["over_sum"], "outside_changed_px_max": report["outside_changed_px_max"],+ "held": {"poses_frames": said(report["held"]),+ "warned": sum(1 for r in report["held"]["held_runs"] if "why" not in r)},"verdict": report["verdict"], "videos": made}, ensure_ascii=False, indent=2))if report["verdict"] != "pass":print(f"{PROG}: refused: " + "; ".join(report["refused"]))diff --git a/sprite_gen/video/stop.py b/sprite_gen/video/stop.pyindex 113c8c1..e53d0c5 100644--- a/sprite_gen/video/stop.py+++ b/sprite_gen/video/stop.py@@ -44,6 +44,12 @@ and a report.- **Ghosts**: the frames shown pass the ghost screen every loop path delivers (`interpolation_quality`),read on them as filmed, as `video-loop` reads its cut; a ghost is named in the report and a warning, byits cell and clip frame, and kept as filmed.+- **Held cells**: the frames shown are read for a picture shown again (`held_fill.same_steps`, on them as filmed)+ and, by default (`--fill-held auto`), each held run's cells are made again between the run's first cell and the+ next pose, as `video-loop` makes a cut played once (docs/loop-repair.md section 7): its opening and closing pose+ (the still), a run longer than `held_fill.HOLD_MAX` and a clip drawn on twos or threes kept as filmed. A frame+ between that is refused, and every held cell where no RIFE is installed, is kept as filmed with a warning line;+ `--fill-held off` plays the frames as filmed.The cells are the loop's cells' scale and placement: the loop's cell sits inside the stop's cell(`loop_cell_origin`), centred on it with the same bottom unless a frame reaches lower, and the sidecar's@@ -71,6 +77,7 @@ from sprite_gen.video import gait_fallbackfrom sprite_gen.video import held_fill as held_fill_modfrom sprite_gen.video import loop as loop_modfrom sprite_gen.video import nonloop+from sprite_gen.video import rife as rife_modfrom sprite_gen.video.interpolation_quality import ghost_screenfrom sprite_gen.video.repair import ALPHA_SOLIDfrom sprite_gen.util.console import utf8_streams@@ -148,7 +155,10 @@ def read_loop(meta_path: Path) -> tuple[dict[str, Any], list[Image.Image], str]:def _scaled(path: Path, scale: float) -> Image.Image:- im = Image.open(path).convert("RGBA")+ return _scale(Image.open(path).convert("RGBA"), scale)+++def _scale(im: Image.Image, scale: float) -> Image.Image:return resize_cell(im, (max(1, round(im.width * scale)), max(1, round(im.height * scale))))@@ -362,9 +372,14 @@ def pick(played: list[int], *, speed: int, max_frames: int | None) -> list[int]:def make_stop(frames_dir: Path, loop_meta: Path, out_dir: Path, *, name: str = "stop", speed: int = 1,max_frames: int | None = None, fps: float | None = None, report_path: Path | None = None,- seam_max: float = SEAM_MAX, run_up_max: float = RUN_UP_MAX_CYCLES) -> dict[str, Any]:+ seam_max: float = SEAM_MAX, run_up_max: float = RUN_UP_MAX_CYCLES, fill_held: str = "auto",+ interpolate: rife_mod.Interpolate | None = None) -> dict[str, Any]:"""Cut the stop and write `<name>.strip.png`, `<name>.strip.json`, `<name>.gif`, `<name>.webp` and the report- (`<name>.stop.report.json`, or `report_path`) into `out_dir`. A refusal writes the report and exits."""+ (`<name>.stop.report.json`, or `report_path`) into `out_dir`. A refusal writes the report and exits. `fill_held`+ auto makes the held cells again between the poses beside them (the module's "Held cells"), with `interpolate`, or+ RIFE located once a frame is to be made; off plays them as filmed."""+ if fill_held not in held_fill_mod.MODES:+ raise SystemExit(f"{PROG}: --fill-held {fill_held!r}: one of {', '.join(held_fill_mod.MODES)}")if speed not in SPEEDS:raise SystemExit(f"{PROG}: --speed {speed}: 1 or 2")if not (math.isfinite(seam_max) and seam_max > 0 and math.isfinite(run_up_max) and run_up_max >= 0):@@ -413,8 +428,26 @@ def make_stop(frames_dir: Path, loop_meta: Path, out_dir: Path, *, name: str = "loop_mod.write_loop_report(target, {**base, **exc.record, "status": "failed", "error": str(exc)})raise SystemExit(str(exc)) from excshown = pick(found["played"], speed=speed, max_frames=max_frames)+ # Read as filmed, at the keyed frames' own size, as video-loop reads its cut: a part-covered band is a+ # number of pixels thick, and scaled down a ghost's band falls under it.+ filmed = [Image.open(files[j]).convert("RGBA") for j in shown]+ screen = ghost_screen(filmed)+ # The stop's frames shown again (docs/loop-repair.md section 7), made again between the poses beside them as a cut+ # played once is, on the frames as filmed at their own size; a cell made stands where the held cell stood (its+ # frame's move), scaled and laid as the clip's frames are.+ try:+ filled, held = loop_mod.fill_cut(filmed, interpolate, ring=False, same=held_fill_mod.same_steps(filmed),+ mode=fill_held, hold=(meta.get("drawings") or {}).get("hold"))+ except (ValueError, rife_mod.RifeUnavailable) as exc:+ error = (f"{PROG}: {exc}; the stop shows a picture again and the frames between are to be made — fix RIFE, or "+ "pass --fill-held off to cut it as filmed (docs/loop-repair.md section 7)")+ loop_mod.write_loop_report(target, {**base, **found, "drift": drift, "status": "failed", "error": error})+ raise SystemExit(error) from exc+ shown_frames = [laid[j] for j in shown]+ for k in held["made"]:+ shown_frames[k] = space.lay(_scale(filled[k], scale), guess)loop_rect = (-space.origin[0], -space.origin[1], w - space.origin[0], h - space.origin[1])- stop_cells, rect = _cells([laid[j] for j in shown], [moves[j] for j in shown], loop_rect)+ stop_cells, rect = _cells(shown_frames, [moves[j] for j in shown], loop_rect)cw, ch = stop_cells[0].sizeif cw * len(stop_cells) > loop_mod.STRIP_MAX_WIDTH:error = (f"{PROG}: {len(stop_cells)} cells of {cw} px make a strip {cw * len(stop_cells)} px wide, over "@@ -424,15 +457,6 @@ def make_stop(frames_dir: Path, loop_meta: Path, out_dir: Path, *, name: str = "origin = [loop_rect[0] - rect[0], loop_rect[1] - rect[1]]pivot = meta.get("anchor") or [w / 2, h]last = _box(stop_cells[-1])- # Read as filmed, at the keyed frames' own size, as video-loop reads its cut: a part-covered band is a- # number of pixels thick, and scaled down a ghost's band falls under it.- filmed = [Image.open(files[j]).convert("RGBA") for j in shown]- screen = ghost_screen(filmed)- # The stop's frames shown again (docs/loop-repair.md section 7): named, never made between — a stop plays the clip's- # filmed frames, none made between two others.- reading = held_fill_mod.reading(held_fill_mod.same_steps(filmed))- held = {"mode": "off", "why": "a stop plays the clip's filmed frames, none made between two others", "made": [],- "before": reading, **reading}for g in screen.get("ghosts", []):g["clip_frame"] = shown[g["frame"]]delay = round(1000 / fps, 2)@@ -445,7 +469,10 @@ def make_stop(frames_dir: Path, loop_meta: Path, out_dir: Path, *, name: str = ""from_loop": {"strip_sha256": strip_sha, "state": meta.get("state"), "frames": len(cells), "w": w, "h": h,"from_cell": found["entry"]["from_cell"]},"source_cut": {"source": identity, "frames": shown, "entry": found["entry"]["frame"], "rest_end": found["rest"]["end"]},- "speed": speed, "seam_steps": found["seam"]["steps"], "held_fill": held,+ "speed": speed, "seam_steps": found["seam"]["steps"], "held_fill": held_fill_mod.public(held),+ # The holds the motion means, as cells of the strip (one cell a frame shown): what a reader of it —+ # `inspect-holds`, a scene — does not take for a picture shown again by mistake.+ "holds": held_fill_mod.intended(held),}out_dir.mkdir(parents=True, exist_ok=True)strip = Image.new("RGBA", (cw * len(stop_cells), ch), (0, 0, 0, 0))@@ -466,7 +493,7 @@ def make_stop(frames_dir: Path, loop_meta: Path, out_dir: Path, *, name: str = ""drift": {**drift, "ground_in_cell": drift["ground"] - rect[1],"ends_on_ground": last is not None and last[3] - 1 == drift["ground"] - rect[1]},"shown": shown, "frames_shown": len(shown), "seconds": round(len(shown) / fps, 4),- "ghost_screen": screen,+ "ghost_screen": screen, "held_fill": held,"strip": {"path": str(strip_path), **strip_meta}, "gif": gif, "webp": webp,}loop_mod.write_loop_report(target, payload)@@ -479,9 +506,15 @@ def make_stop(frames_dir: Path, loop_meta: Path, out_dir: Path, *, name: str = "f"{100 * g['ghost']:.2f} % of its body — a filmed ghost, kept as filmed", file=sys.stderr)if not screen["reads"]:print(f"{PROG}: warning: the ghost screen does not read this stop — {screen['why']}", file=sys.stderr)- for run in held["held_runs"]:- print(f"{PROG}: warning: cells {run['start']}-{run['start'] + run['length'] - 1} show one picture "- f"({held_fill_mod.said(held)} poses/cells): the clip stalls there, played as filmed", file=sys.stderr)+ # What became of the held cells: those left for want of RIFE, the runs a frame between was refused for, and, with+ # --fill-held off, every run (each played as filmed); a run kept as the motion's own says nothing.+ for line in loop_mod.fill_lines(held):+ print(f"{PROG}: warning: {line}", file=sys.stderr)+ for run in held["before"]["held_runs"]:+ if run.get("why") == "--fill-held off":+ print(f"{PROG}: warning: cells {run['start']}-{run['start'] + run['length'] - 1} show one picture "+ f"({held_fill_mod.said(held)} poses/cells): the clip stalls there, played as filmed (--fill-held off)",+ file=sys.stderr)payload["report"] = str(target)return payload@@ -499,6 +532,12 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:help=f"refuse a seam (the last loop cell into the stop's first frame) over this many of the clip's steps (default {SEAM_MAX}, the jump line)")parser.add_argument("--run-up-max", type=float, default=RUN_UP_MAX_CYCLES,help=f"refuse a stop whose frames between the rest and the loop's frames are longer than this many of the clip's cycles (default {RUN_UP_MAX_CYCLES})")+ parser.add_argument("--fill-held", choices=held_fill_mod.MODES, default="auto",+ help="auto (default): cells of the stop that show the picture before them again (the clip stalls) are "+ "made again with RIFE between the poses beside them, as video-loop makes a cut played once; the "+ f"opening pose, the closing still, a run longer than {held_fill_mod.HOLD_MAX} cells and a clip drawn on "+ "twos or threes are kept, and a frame between that is refused, or no RIFE installed, keeps the cells "+ "as filmed with a warning line (`held_fill`, docs/loop-repair.md section 7); off: as filmed")parser.add_argument("--fps", type=float, help="the frames' rate (default: the loop's source_cut, else 24)")parser.add_argument("--report", type=Path, help="report path (default <out-dir>/<name>.stop.report.json)")@@ -508,11 +547,16 @@ def run(**kwargs: object) -> int:name=str(kwargs.get("name") or "stop"), speed=int(kwargs.get("speed") or 1), # type: ignore[arg-type]max_frames=kwargs.get("max_frames"), fps=kwargs.get("fps"), report_path=kwargs.get("report"), # type: ignore[arg-type]seam_max=float(SEAM_MAX if kwargs.get("seam_max") is None else kwargs["seam_max"]), # type: ignore[arg-type]- run_up_max=float(RUN_UP_MAX_CYCLES if kwargs.get("run_up_max") is None else kwargs["run_up_max"])) # type: ignore[arg-type]+ run_up_max=float(RUN_UP_MAX_CYCLES if kwargs.get("run_up_max") is None else kwargs["run_up_max"]), # type: ignore[arg-type]+ fill_held=str(kwargs.get("fill_held") or "auto"))print(json.dumps({"strip": payload["strip"]["path"], "frames": payload["strip"]["frames"], "seconds": payload["seconds"],"from_cell": payload["entry"]["from_cell"], "entry": payload["entry"]["frame"], "rest_end": payload["rest"]["end"],"seam_steps": payload["seam"]["steps"], "run_up": payload["run_up"], "drift": payload["drift"],- "ghosts": [g["clip_frame"] for g in payload["ghost_screen"].get("ghosts", [])], "report": payload["report"]},+ "ghosts": [g["clip_frame"] for g in payload["ghost_screen"].get("ghosts", [])],+ "held_fill": {"poses_cells": held_fill_mod.said(payload["held_fill"]),+ "before": held_fill_mod.said(payload["held_fill"]["before"]),+ "made": payload["held_fill"]["made"]},+ "report": payload["report"]},ensure_ascii=False, indent=2))return 0diff --git a/tests/gen/test_video_held.py b/tests/gen/test_video_held.pynew file mode 100644index 0000000..7c7debc--- /dev/null+++ b/tests/gen/test_video_held.py@@ -0,0 +1,116 @@+# SPDX-License-Identifier: Apache-2.0+"""`sprite-gen video`, `video-extend`, `video-edit` and `video-resume` read the clip they publish for a picture shown+again (docs/loop-repair.md section 7) and name it, changing nothing: a provider that repeats a frame is warned of, and+its report records the reading (`held`). Synthetic clips, made with ffmpeg; no network — the HTTP layer is a fake."""++from __future__ import annotations++import json+import shutil+import subprocess+from pathlib import Path++import numpy as np+from PIL import Image++from sprite_gen.gen import video+from tests.gen.test_video import _FakeApi, _still, clock # noqa: F401 (the clock fixture)++W = H = 96+GREEN = (20, 240, 30)+++def _frame(k: float, *, background=None) -> Image.Image:+ """A red square sliding across, 3 px a frame, on the green canvas a clip is filmed on (or `background`)."""+ a = np.zeros((H, W, 3), np.uint8)+ a[:] = GREEN if background is None else background+ x = round(10 + 3 * k)+ a[40:56, x:x + 16] = (220, 30, 40)+ return Image.fromarray(a, "RGB")+++def _mp4(path: Path, times: list[float], *, background=None) -> Path:+ """An H.264 clip at 24 fps of the square at `times`: a time given twice in a row is a frame shown again."""+ folder = path.with_suffix("")+ folder.mkdir(parents=True)+ for i, t in enumerate(times):+ _frame(t, background=background).save(folder / f"{i:04d}.png")+ subprocess.run([shutil.which("ffmpeg"), "-v", "error", "-y", "-framerate", "24", "-i", str(folder / "%04d.png"),+ "-c:v", "libx264", "-crf", "18", "-pix_fmt", "yuv420p", str(path)], check=True)+ return path+++def test_a_clip_that_shows_a_frame_again_is_read_so_and_one_that_does_not_is_read_clean(tmp_path):+ steady = video.read_held(_mp4(tmp_path / "steady.mp4", list(range(16))))+ assert steady["read"] is True and steady["frames"] == 16 and steady["held_runs"] == []+ assert steady["background"] is not None and (steady["poses"], steady["cells"]) == (16, 16)+ assert video.held_lines(tmp_path / "steady.mp4", steady) == []+ again = video.read_held(_mp4(tmp_path / "again.mp4", [0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]))+ assert again["held_runs"] == [{"start": 5, "length": 2}] and (again["poses"], again["cells"]) == (15, 16)+ assert video.held_lines(tmp_path / "again.mp4", again) == [+ "again.mp4 shows one picture on frames 5-6 (15/16 poses/frames): the clip repeats a frame there, kept as the "+ "provider made it; video-loop makes such cells again between the poses beside them (docs/loop-repair.md section 7)"]+++def test_a_hold_the_motion_means_and_the_clip_s_opening_and_closing_pose_are_read_and_not_warned_of(tmp_path):+ clip = _mp4(tmp_path / "holds.mp4", [0, 0, 1, 2, 3, 3, 3, 3, 3, 4, 5, 6, 7, 7])+ record = video.read_held(clip)+ assert [(r["start"], r["length"]) for r in record["held_runs"]] == [(0, 2), (4, 5), (12, 2)]+ assert [r["why"] for r in record["held_runs"]] == [+ "the clip's opening pose", "held 5 frames, longer than a drawing on threes (3): a hold the motion means",+ "the clip's closing pose"]+ assert video.held_lines(clip, record) == []+++def test_a_clip_filmed_whole_is_read_on_every_pixel(tmp_path):+ rng = np.random.default_rng(7)+ noise = rng.integers(0, 255, (H, W, 3), dtype=np.uint8) # no flat canvas round it: a scene filmed whole+ folder = tmp_path / "scene"+ folder.mkdir()+ for i, t in enumerate([0, 1, 2, 2, 3, 4]):+ a = np.asarray(_frame(t)).copy()+ square = np.all(a == (220, 30, 40), axis=-1)+ a[~square] = noise[~square]+ Image.fromarray(a).save(folder / f"{i:04d}.png")+ clip = tmp_path / "scene.mp4"+ subprocess.run([shutil.which("ffmpeg"), "-v", "error", "-y", "-framerate", "24", "-i", str(folder / "%04d.png"),+ "-c:v", "libx264", "-crf", "10", "-pix_fmt", "yuv444p", str(clip)], check=True)+ record = video.read_held(clip)+ assert record["background"] is None and record["held_runs"] == [{"start": 2, "length": 2}]+++def test_a_file_ffmpeg_cannot_read_is_named_not_read(tmp_path):+ clip = tmp_path / "fake.mp4"+ clip.write_bytes(b"\x00\x00\x00\x18ftypisom" + b"\x00" * 64)+ record = video.read_held(clip)+ assert record["read"] is False and record["why"].startswith(("ffprobe found no video stream", "ffmpeg could not read"))+ assert video.held_lines(clip, record)[0].startswith("fake.mp4: its frames were not read for a picture shown again — ")+++def _run(tmp_path: Path, monkeypatch, payload: bytes) -> tuple[dict, Path]:+ api = _FakeApi()+ api.payload = payload+ monkeypatch.setattr(video, "resolve_credential", lambda **_: video.Credential("t", video.AUTH_SOURCE_API_KEY))+ monkeypatch.setattr(video, "http_json", api.call)+ monkeypatch.setattr(video, "http_download", api.download)+ out, report = tmp_path / "out" / "clip.mp4", tmp_path / "report.json"+ rc = video.run(image=_still(tmp_path), prompt="sway", prompt_file=None, out=out, duration=6, resolution="720p",+ aspect_ratio=None, model=video.DEFAULT_MODEL, generate_audio=None, report=report)+ assert rc == 0 and out.read_bytes() == payload # the provider's bytes, published as they came+ return json.loads(report.read_text(encoding="utf-8")), out+++def test_the_cli_warns_of_a_frame_the_provider_shows_again_and_records_the_reading(tmp_path, monkeypatch, clock, capsys): # noqa: F811+ payload = _mp4(tmp_path / "made" / "again.mp4", [0, 1, 2, 3, 3, 4, 5, 6, 7, 8]).read_bytes()+ report, _ = _run(tmp_path, monkeypatch, payload)+ assert report["held"]["read"] is True and report["held"]["held_runs"] == [{"start": 3, "length": 2}]+ err = capsys.readouterr().err+ assert "video: warning: clip.mp4 shows one picture on frames 3-4 (9/10 poses/frames)" in err+++def test_the_cli_reads_a_clip_that_shows_no_frame_again_and_says_nothing(tmp_path, monkeypatch, clock, capsys): # noqa: F811+ payload = _mp4(tmp_path / "made" / "steady.mp4", list(range(10))).read_bytes()+ report, _ = _run(tmp_path, monkeypatch, payload)+ assert report["held"]["read"] is True and report["held"]["held_runs"] == []+ assert (report["held"]["poses"], report["held"]["cells"]) == (10, 10)+ assert "warning" not in capsys.readouterr().errdiff --git a/tests/video/test_face_bake_held.py b/tests/video/test_face_bake_held.pynew file mode 100644index 0000000..3b60b94--- /dev/null+++ b/tests/video/test_face_bake_held.py@@ -0,0 +1,51 @@+# SPDX-License-Identifier: Apache-2.0+"""`face-bake` reads the body it bakes for a picture shown again (docs/face-parts.md, "face-bake"): which held runs a+clip means and which it names in a warning. The runs here are given as the steps a bake reads; the bake itself, on a+pack, is tested in tests/video/test_face_layer.py."""++from __future__ import annotations++from sprite_gen.video import face_bake++BODIES = {"idle": {"loop": True, "cells": ["i"] * 6}, "greet": {"loop": False, "cells": ["g"] * 6}}+++def _read(shown, held_steps, bodies=BODIES):+ same = [t in held_steps for t in range(len(shown) - 1)]+ return face_bake.held_reading(shown, same, bodies)+++def test_a_clip_s_opening_and_closing_pose_and_a_long_hold_are_meant_and_said_nothing_of():+ shown = [("greet", k) for k in range(6)] + [("idle", k) for k in range(6)]+ record = _read(shown, {0, 4, 7, 8, 9}) # greet 0-1, greet 4-5, idle 1-4+ assert (record["frames"], record["poses"]) == (12, 7)+ assert [(r["start"], r["length"], r["kind"]) for r in record["held_runs"]] == [+ (0, 2, "opening"), (4, 2, "closing"), (7, 4, "motion-hold")]+ assert [r["why"] for r in record["held_runs"]] == [+ "the clip greet's opening pose", "the clip greet's closing pose",+ "held 4 frames, longer than a drawing on threes (3): a hold the motion means"]+ assert record["held_runs"][0]["body"] == [["greet", 0], ["greet", 1]]+ assert face_bake.held_lines(record) == []+++def test_a_picture_shown_again_mid_clip_across_the_clips_or_across_the_loop_s_wrap_is_named():+ shown = [("greet", k) for k in range(6)] + [("idle", k) for k in range(6)] + [("idle", 0), ("idle", 1)]+ record = _read(shown, {2, 5, 11}) # greet 2-3, greet 5 to idle 0, idle 5 to idle 0 (the wrap)+ assert [(r["start"], r["length"]) for r in record["held_runs"]] == [(2, 2), (5, 2), (11, 2)]+ assert not any("why" in r for r in record["held_runs"])+ lines = face_bake.held_lines(record)+ assert lines[0] == (+ "frames 2-3 show one body picture (greet:2, greet:3; 11/14 poses/frames): the body stands still there "+ "mid-motion, baked as the pack has it — make the pack from frames whose held cells are made again "+ "(video-loop --fill-held auto, docs/loop-repair.md section 7)")+ assert [line.split(";")[0] for line in lines[1:]] == [+ "frames 5-6 show one body picture (greet:5, idle:0", "frames 11-12 show one body picture (idle:5, idle:0"]+++def test_a_hold_the_pack_lists_for_a_clip_is_meant_with_its_own_reason():+ bodies = {**BODIES, "greet": {**BODIES["greet"], "holds": [{"from": 2, "to": 4, "kind": "drawn", "reason": "drawn on threes"}]}}+ shown = [("greet", k) for k in range(6)]+ record = _read(shown, {2, 3}, bodies)+ assert [(r["start"], r["length"], r["kind"], r["why"]) for r in record["held_runs"]] == [(2, 3, "drawn", "drawn on threes")]+ assert face_bake.held_lines(record) == []+ assert face_bake.held_lines(_read(shown, {1, 2}, bodies)) # greet 1-3: past the hold listed, nameddiff --git a/tests/video/test_face_layer.py b/tests/video/test_face_layer.pyindex 0a15891..7dfba42 100644--- a/tests/video/test_face_layer.py+++ b/tests/video/test_face_layer.py@@ -651,6 +651,8 @@ def test_a_baked_line_on_the_loop_puts_in_no_jump_and_changes_nothing_outside(caassert report["outside_changed_px_max"] == 0 and report["over_sum"] == []assert report["talk_frames"] > 0 and report["set"] == "neutral"assert abs(_seconds(tmp_path / "out" / "voice-baked.wav") - frames / 24) < 1 / 48000 * 2+ # the idle loop shows a new picture on every frame, so the bake reads no held run+ assert report["held"]["held_runs"] == [] and report["held"]["poses"] == report["held"]["frames"] == frames@needs_node@@ -675,3 +677,48 @@ def test_a_pack_that_changed_after_it_was_made_is_refused(case, tmp_path):fh.write(b"\0")with pytest.raises(SystemExit, match="not the file the pack was made with"):face_bake.load_pack(tmp_path / "pack")+++def _greet_held(root, tmp_path, dup, holds=None):+ """The pack with greet's cell `dup[1]` its cell `dup[0]` again, byte for byte (a clip that stalls), its digest+ written anew, and `holds` listed on greet's row."""+ shutil.copytree(root / "pack", tmp_path / "pack")+ manifest = json.loads((tmp_path / "pack" / "face-pack.json").read_text(encoding="utf-8"))+ greet = body(manifest, "greet")+ src, dst = (tmp_path / "pack" / greet["cells"][k] for k in dup)+ dst.write_bytes(src.read_bytes())+ manifest["files"][greet["cells"][dup[1]]] = hashlib.sha256(dst.read_bytes()).hexdigest()+ if holds is not None:+ greet["holds"] = holds+ (tmp_path / "pack" / "face-pack.json").write_text(json.dumps(manifest), encoding="utf-8")+ return tmp_path / "pack"+++@needs_node+def test_a_bake_names_a_body_picture_shown_again_mid_clip_and_bakes_it_as_the_pack_has_it(case, tmp_path, capsys):+ root, _ = case+ _wav(tmp_path / "line.wav", tf.voice())+ pack = _greet_held(root, tmp_path, (4, 5))+ report = face_bake.bake(pack, tmp_path / "line.wav", tmp_path / "out", play="greet", lead=0.2)+ assert report["held"]["held_runs"] == [{"start": 4, "length": 2, "body": [["greet", 4], ["greet", 5]]}]+ assert report["held"]["poses"] == report["frames"] - 1+ assert json.loads((tmp_path / "out" / "bake.json").read_text(encoding="utf-8"))["held"] == report["held"]+ held = [np.asarray(Image.open(tmp_path / "out" / "frames" / f"frame-{t:05d}.png")) for t in (4, 5)]+ assert np.array_equal(*held) # baked as the pack has it: no frame made+ assert (f"face-bake: warning: frames 4-5 show one body picture (greet:4, greet:5; {report['frames'] - 1}/"+ f"{report['frames']} poses/frames): the body stands still there mid-motion") in capsys.readouterr().err+++@needs_node[email protected]("dup, holds, kind", [((0, 1), None, "opening"),+ ((4, 5), [{"from": 4, "to": 5, "kind": "drawn", "reason": "drawn on twos"}], "drawn")])+def test_a_bake_says_nothing_of_a_hold_the_clip_means(case, tmp_path, capsys, dup, holds, kind):+ root, _ = case+ _wav(tmp_path / "line.wav", tf.voice())+ pack = _greet_held(root, tmp_path, dup, holds)+ report = face_bake.bake(pack, tmp_path / "line.wav", tmp_path / "out", play="greet", lead=0.2)+ [run] = report["held"]["held_runs"]+ assert (run["start"], run["length"], run["kind"]) == (dup[0], 2, kind)+ assert "face-bake: warning" not in capsys.readouterr().errdiff --git a/tests/video/test_stop.py b/tests/video/test_stop.pyindex bf71cdd..2e86e8a 100644--- a/tests/video/test_stop.py+++ b/tests/video/test_stop.py@@ -145,8 +145,8 @@ def test_stop_plays_the_start_backwards_from_the_loop_to_the_first_frame(tmp_patassert smeta["from_loop"]["from_cell"] == out["entry"]["from_cell"] and smeta["body_h"] == lmeta["body_h"]assert smeta["source_cut"]["source"]["sha256"] == lmeta["source_cut"]["source"]["sha256"]assert out["source"]["same_as_loop"] is True- # Read for a picture shown again, as every cut is; a stop plays its filmed frames, none made between.- assert smeta["held_fill"]["mode"] == "off" and smeta["held_fill"]["made"] == []+ # Read for a picture shown again, as every cut is; none is, so none is made between.+ assert smeta["held_fill"]["mode"] == "auto" and smeta["held_fill"]["made"] == []assert (smeta["held_fill"]["cells"], smeta["held_fill"]["poses"], smeta["held_fill"]["held_runs"]) == (len(shown), len(shown), [])with Image.open(tmp_path / "stop" / "stop.gif") as gif:assert gif.n_frames == len(shown) and gif.info.get("loop") is None@@ -321,3 +321,147 @@ def test_stop_source_identity_is_the_loop_cut_from(tmp_path):meta = cut(tmp_path, keyed, run_from + PERIOD)files = sorted(keyed.glob("*.png"))assert json.loads(meta.read_text())["source_cut"]["source"] == evidence.source_identity(files, 24.0)+++# --- Held cells (docs/loop-repair.md section 7): a clip that stalls in its setting-off ---------------------------------++# Pinned on the engine before the stop filled its held cells (4f5ccd5), as pictures (tests/picture_digest.py): the stop+# of `clip()` cut a cycle on, and of the same clip whose frame STALL + 1 shows frame STALL again (cells 3 and 4 one+# picture), as that engine played them.+STALL = REST + 3+BEFORE = {+ "plain": {"strip": "5dfc0343acb98991481aa8e9036ebc8ddbeafb61cd4d4011f5cbdbaa0bae4ee7",+ "gif": "7859e66d30ace8837f5da19317182e9a465c3f6f22162e7881a3d305ccb4e3b6",+ "webp": "93aec374211792679b1dcdde4fba446005a92e771596466feb12e08e2acd0137"},+ "held": {"strip": "756c3d1c33194ad27605f610d9b38c3bd95476daa32f97a0760c7ffaf0a4843a",+ "gif": "8517e8fdeaa02a7c45acdfae38b17e1c43912968e1477cd2b23964796f905e08",+ "webp": "8f1d51cf173f2e3ff20d117751b4189faf5c01b8b76d5e164f721a1d43e878df"},+}+++def clip_at(i: float) -> Image.Image:+ """`clip()`'s frame `i` (its defaults), at any time: standing, setting off, then running — what an interpolator+ that follows the motion would draw between two of its frames."""+ if i < REST:+ return runner(run=0.0, phase=0.0)+ k = i - REST+ if k < SET_OFF:+ return runner(run=(k + 1) / (SET_OFF + 1), phase=2 * math.pi * k / PERIOD)+ return runner(run=1.0, phase=2 * math.pi * k / PERIOD)+++def stalled(tmp_path: Path) -> tuple[Path, int]:+ """`clip()` with frame STALL shown twice: frame STALL + 1 is it again, byte for byte (a video model that stalls)."""+ keyed, run_from = clip(tmp_path)+ files = sorted(keyed.glob("*.png"))+ files[STALL + 1].write_bytes(files[STALL].read_bytes())+ return keyed, run_from+++def pictures(out: Path, name: str = "stop") -> dict[str, str]:+ from tests.picture_digest import picture_digest+ return {k: picture_digest([out / f"{name}.{k}" if k != "strip" else out / f"{name}.strip.png"]) for k in ("strip", "gif", "webp")}+++def no_rife(monkeypatch, tmp_path: Path) -> None:+ """No RIFE anywhere the engine looks: no SPRITE_GEN_RIFE, no directory on PATH holding one, an empty data directory."""+ import os+ 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 test_a_stop_whose_clip_stalls_has_its_held_cell_made_between_the_poses_beside_it(tmp_path, capsys):+ from sprite_gen.video import held_fill+ from tests.video.held_fill_inputs import Between++ keyed, run_from = stalled(tmp_path)+ meta = cut(tmp_path, keyed, run_from + PERIOD)+ between = Between(clip_at, range(len(sorted(keyed.glob("*.png")))))+ out = make(tmp_path, keyed, meta, interpolate=between)+ shown = out["shown"]+ assert shown[3:5] == [STALL + 1, STALL] # played backwards: the stalled pair, one picture+ held = out["held_fill"]+ # Before: cells 3 and 4 one picture; the second made again between the first and the pose after it, at its time.+ assert held["before"]["held_runs"] == [{"start": 3, "length": 2, "filled": True, "made": [4]}]+ assert held["made"] == [4] and between.calls == [(STALL, STALL - 1, 0.5)]+ assert (held["before"]["poses"], held["before"]["cells"]) == (len(shown) - 1, len(shown))+ # Delivered: no cell shows the picture of the cell before it.+ smeta, cells = cells_of(tmp_path / "stop" / "stop.strip.json")+ assert held_fill.same_steps(cells) == [False] * (len(cells) - 1)+ assert (smeta["held_fill"]["poses"], smeta["held_fill"]["cells"], smeta["held_fill"]["held_runs"]) == (len(shown), len(shown), [])+ assert smeta["holds"] == [] # no hold the motion means is left+ assert smeta["held_fill"]["made"] == [4] and smeta["frames"] == len(shown)+ # The closing still is the clip's first frame as filmed, held: the stop ends as it did.+ lmeta = json.loads(meta.read_text())+ first = Image.open(sorted(keyed.glob("*.png"))[0]).convert("RGBA")+ first = resize_cell(first, (round(first.width * lmeta["scale"]), round(first.height * lmeta["scale"])))+ assert cells[-1].crop(cells[-1].getbbox()).tobytes() == first.crop(first.getbbox()).tobytes()+ assert (smeta["hold_last"], smeta["end_frame"]) == (True, len(shown) - 1)+ assert "video-stop: warning" not in capsys.readouterr().err+ # The pictures are no longer the engine before's (which played cell 4 as cell 3 again).+ assert pictures(tmp_path / "stop") != BEFORE["held"]+++def test_a_stop_with_no_held_cell_is_the_pictures_it_was_and_asks_for_no_frame(tmp_path):+ def never(a, b, t):+ raise AssertionError("a stop with no held cell asks for no frame between")++ keyed, run_from = clip(tmp_path)+ meta = cut(tmp_path, keyed, run_from + PERIOD)+ out = make(tmp_path, keyed, meta, interpolate=never)+ assert out["held_fill"]["made"] == [] and out["held_fill"]["before"]["held_runs"] == []+ assert pictures(tmp_path / "stop") == BEFORE["plain"]+++def test_fill_held_off_plays_the_stalled_stop_as_before_and_names_the_run(tmp_path, capsys):+ keyed, run_from = stalled(tmp_path)+ meta = cut(tmp_path, keyed, run_from + PERIOD)+ out = make(tmp_path, keyed, meta, fill_held="off", interpolate=lambda a, b, t: pytest.fail("off makes no frame"))+ assert pictures(tmp_path / "stop") == BEFORE["held"]+ held = out["held_fill"]+ assert held["mode"] == "off" and held["made"] == [] and held["held_runs"] == [{"start": 3, "length": 2}]+ assert held["before"]["held_runs"][0]["why"] == "--fill-held off"+ err = capsys.readouterr().err+ assert "video-stop: warning: cells 3-4 show one picture (7/8 poses/cells)" in err and "--fill-held off" in err+ with pytest.raises(SystemExit):+ stop.main(["--frames-dir", str(keyed), "--loop", str(meta), "--out-dir", str(tmp_path / "x"), "--fill-held", "on"])+++def test_a_frame_between_the_judge_refuses_keeps_the_stop_s_held_cells_as_filmed_and_says_so(tmp_path, capsys):+ keyed, run_from = stalled(tmp_path)+ meta = cut(tmp_path, keyed, run_from + PERIOD)+ out = make(tmp_path, keyed, meta, interpolate=lambda a, b, t: a.copy()) # gives the pose back: a held cell again+ run = out["held_fill"]["before"]["held_runs"][0]+ assert run["filled"] is False and "held" in run["faults"] and out["held_fill"]["made"] == []+ assert pictures(tmp_path / "stop") == BEFORE["held"]+ assert "video-stop: warning: held cells 3-4 kept as filmed: a frame between was refused (held" in capsys.readouterr().err+++def test_no_rife_plays_the_stop_s_held_cells_as_filmed_and_says_how_to_install_it(tmp_path, monkeypatch, capsys):+ no_rife(monkeypatch, tmp_path)+ keyed, run_from = stalled(tmp_path)+ meta = cut(tmp_path, keyed, run_from + PERIOD)+ out = make(tmp_path, keyed, meta)+ assert out["status"] == "passed" and out["held_fill"]["made"] == []+ assert out["held_fill"]["unmade"]["cells"] == [4] and out["held_fill"]["unmade"]["why"] == "RIFE is not installed"+ smeta = json.loads((tmp_path / "stop" / "stop.strip.json").read_text())+ assert smeta["held_fill"]["unmade"]["cells"] == [4] and "install" in smeta["held_fill"]["unmade"]+ assert pictures(tmp_path / "stop") == BEFORE["held"]+ err = capsys.readouterr().err+ assert "video-stop: warning: 1 held cell (4) shown as filmed — RIFE is not installed" in err and "rife install" in err+++def test_a_stop_s_opening_pose_shown_twice_is_kept_as_filmed_and_listed_as_a_hold_meant(tmp_path, capsys):+ keyed, run_from = clip(tmp_path)+ files = sorted(keyed.glob("*.png"))+ files[12].write_bytes(files[13].read_bytes()) # the stop's first two frames (played backwards: 13, 12) one picture+ meta = cut(tmp_path, keyed, run_from + PERIOD)+ out = make(tmp_path, keyed, meta, interpolate=lambda a, b, t: pytest.fail("the opening pose is kept: no frame between"))+ assert out["shown"][:2] == [13, 12]+ run = out["held_fill"]["before"]["held_runs"][0]+ assert (run["start"], run["length"], run["filled"], run["keep"]) == (0, 2, False, "opening")+ smeta = json.loads((tmp_path / "stop" / "stop.strip.json").read_text())+ assert smeta["holds"] == [{"from": 0, "to": 1, "kind": "opening", "reason": "the cut's opening pose, kept as filmed"}]+ assert "video-stop: warning" not in capsys.readouterr().err