Skip to content

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

feat(qa): `sprite-gen inspect-holds` reads a delivery for frames that show a figure's picture again (frames with alpha, a keyed clip with `--key`, a figure's box with `--box`, or a renderer's log of cells with `--log`), by held_fill's rule on the figure's pixels, against hold lists (`--holds`, a strip's `holds`); `--gate` exits 1 where a hold is on no list

Soohong Kim94d918974426
diff --git a/docs/README.md b/docs/README.md
index 7e2f1b5..936ee74 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -29,7 +29,7 @@ flowchart LR
d1[recolor] ~~~ d2["breathe (compose)"] ~~~ d3[export-*]
end
subgraph E["E · asset tools (independent)"]
- e1[background-tile] ~~~ e2[shadow] ~~~ e3[inspect-motion]
+ e1[background-tile] ~~~ e2[shadow] ~~~ e3[inspect-motion] ~~~ e4[inspect-holds]
end
subgraph S["S · scene (optional)"]
s1["existing assets + scene.json"] --> s2[scene-render]
@@ -43,7 +43,7 @@ flowchart LR
| **B · video → loop** — one still becomes transparent motion loops | [video-pipeline.md](video-pipeline.md) | `video-canvas` → `video` (or `video-prompt` and a video MCP on your agent) → `video-frames` → `video-loop`, `video-set`, `video-cycle-align`, `video-sway`, the Sway layer (`video-sway-inspect` shows every cell of it and moves nothing; old names `video-follow`, `video-follow-inspect`), `video-set-sheet` (a set's directions on one sheet, on one ground line), `video-stop` (a walk or run that stops, from the clip's own start played backwards); `handed-check` for an item on one side; obstacle plate painted and erased (`--prop-plate`) |
| **C · utilities** — imported images in, clean cuts out | [sheet-slicing.md](sheet-slicing.md) | `cutout`, `slice-sheet`, `unpack-atlas` |
| **D · post-processing** — finished sheets, refined | [recolor.md](recolor.md) | `recolor`, `recolor-palette`, breathing (compose, or `breathe` on a folder of frames), `export-pngs`, `export-aseprite` |
-| **E · asset tools** — independent background, shadow and motion tools | [asset-tools.md](asset-tools.md) | `background-tile`, `shadow`, `inspect-motion` |
+| **E · asset tools** — independent background, shadow and motion tools | [asset-tools.md](asset-tools.md) | `background-tile`, `shadow`, `inspect-motion`, `inspect-holds` |
| **S · scene** — optional composition of existing assets | [scene.md](scene.md) | `scene-render`, `scene-inspect` |
`sprite-gen --help` prints these separate catalogs and every verb grouped by domain; the
diff --git a/docs/architecture.md b/docs/architecture.md
index 74a0eda..c279ead 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -42,7 +42,7 @@ flowchart TB
compose["compose<br/>atlas · cycle · gif · layers · export-pngs · export-aseprite"]
background["background<br/>repeating RGBA tiles · join inspection"]
effects["effects<br/>breathe · anatomy · recolor · interpolate · projected shadows"]
- qa["qa<br/>inspect-motion · inspect · score · preview · correction-loop"]
+ qa["qa<br/>inspect-motion · inspect-holds · inspect · score · preview · correction-loop"]
scene["scene<br/>placement · planes · camera · light · render · inspect"]
serve["serve<br/>curation webview · composition canvas"]
end
@@ -90,7 +90,7 @@ flowchart TD
ATLAS --> D
UNPACK --> CURATE
subgraph E["E · independent asset tools"]
- TILE[background-tile] ~~~ SHADOW[shadow] ~~~ MOTION[inspect-motion]
+ TILE[background-tile] ~~~ SHADOW[shadow] ~~~ MOTION[inspect-motion] ~~~ HOLDS[inspect-holds]
end
subgraph S["S · optional scene workflow"]
INPUT["existing assets + scene.json"] --> RENDER[scene-render]
diff --git a/docs/asset-tools.md b/docs/asset-tools.md
index 6251458..24f0c51 100644
--- a/docs/asset-tools.md
+++ b/docs/asset-tools.md
@@ -1,6 +1,6 @@
# Independent asset tools
-> Owns: Background recipes, repeating RGBA tiles, projected shadows, shared asset formats and motion/contact measurements · Index: [docs/README.md](README.md)
+> Owns: Background recipes, repeating RGBA tiles, projected shadows, shared asset formats, motion/contact measurements and frames shown again · Index: [docs/README.md](README.md)
These commands accept finished artwork without a sprite-generation run or scene spec. `background` owns repeating tiles, `effects` owns shadow projection, and `qa` owns motion measurements. [Scene creation](scene.md) optionally consumes their outputs. Atlas and character-part assembly remain in `compose`.
@@ -107,3 +107,41 @@ Python API: `analyze_motion(sequence, *, contacts=None, foot_box=None, facing=No
Repeated tracked poses retain their complete elapsed duration. Velocity uses distinct pose onset times; duplicate holds add time but do not add independent votes. The last hold remains part of the clip duration without inventing a later displacement endpoint. Confidence is a conditional heuristic, not a calibrated probability of contact.
Scene consumes only verified measurements for the matching selected asset and requires an explicit direction relative to a declared plane or the world. Measurement does not automatically apply stride to any scene or sprite.
+
+## Frames shown again
+
+```bash
+# A figure layer or keyed frames (RGBA): read by alpha.
+sprite-gen inspect-holds --source figures/ --holds web/assets --scene roof --gate
+
+# A clip filmed on a key colour, a still background, or a renderer's log of the cells.
+sprite-gen inspect-holds --source clip.mp4 --key green
+sprite-gen inspect-holds --source frames/ --box 400,120,300,520
+sprite-gen inspect-holds --log cells.jsonl --log-figure hero --log-figure figures
+
+# A cut, its own intended holds listed.
+sprite-gen inspect-holds --source loop/walk.strip.json --gate
+```
+
+`inspect-holds` counts, figure by figure, the frames on which a figure shows the picture it showed on the frame before: on screen it stands still for a frame and then goes on. It reads a delivery whatever made it: a cut, clips joined into one move, a scene rendered frame by frame. Frames are numbered from 0 in the order they are read (a folder's PNGs in name order, a video's frames, a strip's cells); `--frames FROM-TO` reads those frames and the one before `FROM`, to compare with. Nothing is changed.
+
+The figure is read one of four ways:
+
+| Way | Reads | For |
+|---|---|---|
+| alpha (the default) | the frames' alpha; several figures are told apart by where they stand, followed from frame to frame | a figure layer rendered on a clear background, keyed frames, a strip |
+| `--key auto\|green\|magenta\|white` | each frame keyed as `video-frames` keys a clip, then its alpha | a clip filmed on a key colour (mp4 or frames) |
+| `--box x,y,w,h` | that box of each frame, in place | a figure over a background that does not move |
+| `--log FILE` with `--log-figure KEY` | the cell each figure shows: one JSON object a line, one line a frame from 0; `KEY` holds a cell (a string or a number, an object as its values joined by spaces, null where not shown) or a list of them (`figures` gives `figure0`, `figure1`, ...) | a renderer that logs its cells; exact, no pixel read |
+
+An opaque frame whose background moves is not read: its background changes more pixels from one frame to the next than a figure's step does, so a held picture and a moving one cannot be told apart. Opaque frames given with none of `--key`, `--box` or `--log` are refused (exit 2). Read such a delivery by its figure layer, a key, or a log.
+
+A renderer that draws a figure at a new scale, turn or sub-pixel place on every frame draws a held picture afresh each time: the frame changes more of the figure's pixels than the rule below allows and is not read as a hold. Read such a render by its log.
+
+Two pictures are one picture by the rule a cut's held cells are read by ([loop-repair.md section 7](loop-repair.md)): at most `CHANGED_MAX` of the figure's pixels change by more than `PIXEL_SAME`, on its thumbnail and as drawn. The figure is read alone, each pair placed first where its alpha's boxes meet, then within `SEARCH_PX` (3) pixels of it where the fewest pixels change: a camera that follows a figure moves its held picture across the screen, and it is still the picture shown again. Figures that touch read as one.
+
+`--holds FILE` names the holds a delivery means, in the format a holds list is written in: `{"holds": [{"scene", "figure", "from", "to", "reason"}]}`, frames `from` to `to` inclusive. A folder reads every `*.holds.json` under it, and `--holds` repeats. `scene` and `figure` may be left out, for a list of one video or of every figure; a list that names scenes is read for the one `--scene` names (without `--scene` it is refused). A hold without a reason, or whose `from` is after its `to`, refuses the list. A strip's own `holds` (the holds its cut means, `motion-hold`, `drawn`, `opening`, `closing`) are listed with it, and a strip that loops is read across its wrap too (its first cell against its last: a hold at frame 0).
+
+The report (stdout, and `--report PATH`) gives each figure's `frames`, `holds`, `listed`, `unlisted`, `unlistedRuns` and `listedRuns`, each run `from`, `to` and `drawings` (the cell a log names, or the frame the picture was first shown on), a listed run its `reason`, and `unlisted` over every figure; `read_by`, `first_frame`, `wrap`, the lists read and the rule's numbers. `--gate` exits 1 where any hold is on no list, else 0; without it the command exits 0 whatever it finds, and an unlisted hold is a line on stderr. Errors exit 2.
+
+Python API: `inspect(figures, *, first=0, start=None, listed=(), wrap=False, same=None)`, `alpha_figures(frames)`, `log_figures(path, keys)`, `same_figure(a, b)` and `read(...)` in `sprite_gen.qa.holds`.
diff --git a/sprite_gen/_modules.py b/sprite_gen/_modules.py
index 3f1424c..3b09591 100644
--- a/sprite_gen/_modules.py
+++ b/sprite_gen/_modules.py
@@ -15,6 +15,7 @@ MODULE_DOMAIN = {
'shadow': 'effects',
'motion': 'qa',
'handed': 'qa',
+ 'holds': 'qa',
'render': 'scene',
'inspect_scene': 'scene',
'model': 'scene',
@@ -113,8 +114,8 @@ TOOL_GROUPS: list[dict[str, object]] = [
"chain": "cutout · slice-sheet · unpack-atlas (each stands alone)", "doc": "docs/sheet-slicing.md"},
{"key": "D", "name": "post-processing", "verbs": ["recolor", "recolor-palette", "breathe", "export-pngs", "export-aseprite"],
"chain": "recolor · breathe · export-pngs · export-aseprite", "doc": "docs/recolor.md"},
- {"key": "E", "name": "asset tools", "verbs": ["background-tile", "shadow", "inspect-motion"],
- "chain": "background-tile · shadow · inspect-motion (independent; no generation required)", "doc": "docs/asset-tools.md"},
+ {"key": "E", "name": "asset tools", "verbs": ["background-tile", "shadow", "inspect-motion", "inspect-holds"],
+ "chain": "background-tile · shadow · inspect-motion · inspect-holds (independent; no generation required)", "doc": "docs/asset-tools.md"},
]
WORKFLOWS: list[dict[str, object]] = [
diff --git a/sprite_gen/cli.py b/sprite_gen/cli.py
index d1558d8..d01cb50 100644
--- a/sprite_gen/cli.py
+++ b/sprite_gen/cli.py
@@ -12,6 +12,7 @@ from sprite_gen.background import tile
from sprite_gen.curate import anchor
from sprite_gen.compose import compose_atlas, compose_cycle, compose_gif, export_aseprite, export_pngs
from sprite_gen.qa import correction_loop, inspect, preview, score, motion
+from sprite_gen.qa import holds as inspect_holds
from sprite_gen.qa import handed as handed_check
from sprite_gen.frames import cutout, extract, slice_sheet, unpack_atlas
from sprite_gen.gen import gen_set, logo, pixel_draw, prepare, video
@@ -219,6 +220,7 @@ COMMANDS: dict[str, tuple[str, Callable[[argparse.ArgumentParser], None], Callab
"background-tile": ("Quilt a repeating RGBA background and measure its join.", tile.add_arguments, tile.run),
"shadow": ("Project silhouette shadows from any supported asset.", shadow.add_arguments, shadow.run),
"inspect-motion": ("Measure asset timing and contact evidence without changing animation.", motion.add_arguments, motion.run),
+ "inspect-holds": ("Count the frames on which a figure shows the picture of the frame before, by its alpha, a key, a box or a log of its cells; --gate fails on one no list of holds meant names.", inspect_holds.add_arguments, inspect_holds.run),
"scene-render": ("Render referenced assets using scene placement, camera and lighting.", render.add_arguments, render.run),
"scene-inspect": ("Measure scene loops, viewport clipping and repeated joins.", inspect_scene.add_arguments, inspect_scene.run),
"workflow": ("Resolve image/sprite choices, check access and guide the next conversation step.", guide.add_arguments, guide.run),
diff --git a/sprite_gen/qa/holds.py b/sprite_gen/qa/holds.py
new file mode 100644
index 0000000..8941b04
--- /dev/null
+++ b/sprite_gen/qa/holds.py
@@ -0,0 +1,508 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Holds: the frames on which a figure shows the picture it showed on the frame before, so that on screen it stands
+still for a frame and then goes on (`inspect-holds`, docs/asset-tools.md "Frames shown again").
+
+A user of the engine reads its delivery with it: a cut, a set of clips joined into one move, a scene rendered frame by
+frame. Whatever made the frames, a frame that shows its figure's picture again is counted, frame by frame, figure by
+figure, and named: listed where a list of the holds meant names it with its reason, unlisted where none does. `--gate`
+fails on an unlisted one.
+
+The figure is read four ways. By its alpha (frames that carry one: a figure layer, keyed frames, a strip's cells), each
+figure apart where there are several: the solid pixels gathered into figures (`MERGE_PX` joins a hand drawn apart from
+its body) and each followed from frame to frame by where it stands. By a key (`--key`, the keyer `video-frames` keys a
+clip with). Inside a box of a still background (`--box`). Or by a log of the cell each figure shows on each frame
+(`--log`), which reads the cells themselves and no pixel. An opaque frame whose background moves is not read: its
+background changes more pixels a frame than a figure's step does; give its alpha, a key or a log.
+
+Two pictures are the same picture by `held_fill`'s rule (`held_fill.same_steps`: at most CHANGED_MAX of the figure's
+pixels change by more than PIXEL_SAME, on its thumbnail and as drawn), read on the figure alone, each pair placed where
+it fits best first: its alpha's box, then within SEARCH_PX of it, the place that changes the fewest pixels. A camera that
+follows the figure moves a held picture on the screen; it is still the picture shown again.
+
+The report is the one a renderer's holds check gives (each figure's `frames`, `holds`, `listed`, `unlisted`,
+`unlistedRuns` and `listedRuns`, and the `unlisted` of all of them), and a list of holds meant reads in its format:
+`{"holds": [{"scene", "figure", "from", "to", "reason"}]}`, frames from..to inclusive, `scene` and `figure` left out
+where the list is for one video or every figure. A strip's own `holds` (the holds its cut means, docs/loop-repair.md
+section 7) are listed with it."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+import tempfile
+from collections.abc import Callable, Sequence
+from pathlib import Path
+from typing import Any
+
+from PIL import Image
+
+from sprite_gen._deps import np
+from sprite_gen.spec.runio import atomic_write_text
+from sprite_gen.util.cli_kwargs import namespace_from_kwargs
+from sprite_gen.util.console import utf8_streams
+from sprite_gen.video import held_fill as held_fill_mod
+
+REPORT_KIND = "sprite-gen-holds-report"
+SEARCH_PX = 3 # a pair is placed within this many pixels of its alpha boxes' corner, where it fits best
+ALPHA_MIN = 8 # a pixel of a figure: alpha over this (0..255)
+MERGE_PX = 6 # solid pixels this near each other are one figure (a hand drawn apart from its arm)
+FIGURE_MIN_PX = 64 # a figure holds at least this many solid pixels ...
+FIGURE_MIN_SHARE = 0.02 # ... and this share of the largest figure in its frame: less is a speck
+KEYS = ("auto", "green", "magenta", "white") # video-frames' --key
+VIDEO_SUFFIXES = (".mp4", ".mov", ".webm", ".mkv", ".m4v")
+LIST_SUFFIX = ".holds.json"
+
+
+# --- pictures ---------------------------------------------------------------------------------------------------------
+
+def _premultiplied(image: Image.Image) -> np.ndarray:
+ return held_fill_mod.premultiplied(image)
+
+
+def same_figure(a: Image.Image, b: Image.Image, *, search: int = SEARCH_PX) -> bool:
+ """Whether two crops of one figure show the same picture: placed on one canvas by their corners, then within
+ `search` px of it where the fewest pixels change, and read as `held_fill.same_steps` reads a step."""
+ A, B = _premultiplied(a), _premultiplied(b)
+ h, w = max(A.shape[0], B.shape[0]) + 2 * search, max(A.shape[1], B.shape[1]) + 2 * search
+ base = np.zeros((h, w, 4), dtype=np.float32)
+ base[search:search + A.shape[0], search:search + A.shape[1]] = A
+ best: tuple[int, int, int, int] | None = None
+ for dy in range(-search, search + 1):
+ for dx in range(-search, search + 1):
+ moved = np.zeros_like(base)
+ moved[search + dy:search + dy + B.shape[0], search + dx:search + dx + B.shape[1]] = B
+ changed = int((np.abs(base - moved).max(axis=-1) > held_fill_mod.PIXEL_SAME).sum())
+ if best is None or (changed, abs(dy) + abs(dx)) < best[:2]:
+ best = (changed, abs(dy) + abs(dx), dy, dx)
+ _, _, dy, dx = best # type: ignore[misc]
+ canvas_a = Image.new("RGBA", (w, h), (0, 0, 0, 0))
+ canvas_b = Image.new("RGBA", (w, h), (0, 0, 0, 0))
+ canvas_a.paste(a.convert("RGBA"), (search, search))
+ canvas_b.paste(b.convert("RGBA"), (search + dx, search + dy))
+ return held_fill_mod.same_steps([canvas_a, canvas_b])[0]
+
+
+def _same_in_place(a: Image.Image, b: Image.Image) -> bool:
+ """Two crops of one still box: read in place, as `held_fill.same_steps` reads a step."""
+ return held_fill_mod.same_steps([a, b])[0]
+
+
+def _parts(solid: np.ndarray) -> list[tuple[int, int, int, int, np.ndarray]]:
+ """The figures of a frame's solid pixels: their pixels gathered within MERGE_PX of each other, each as its box
+ (left, top, right, bottom) and its pixels inside that box; specks (FIGURE_MIN_PX, FIGURE_MIN_SHARE) left out."""
+ from sprite_gen.video.frames import _components, _near
+
+ if not solid.any():
+ return []
+ ys, starts, stops, labels, _ = _components(_near(solid, MERGE_PX))
+ found = []
+ for label in np.unique(labels):
+ pick = labels == label
+ top, bottom = int(ys[pick].min()), int(ys[pick].max()) + 1
+ left, right = int(starts[pick].min()), int(stops[pick].max())
+ region = np.zeros((bottom - top, right - left), dtype=bool)
+ for y, x0, x1 in zip(ys[pick], starts[pick], stops[pick]):
+ region[y - top, x0 - left:x1 - left] = True
+ own = region & solid[top:bottom, left:right]
+ count = int(own.sum())
+ if count:
+ rows, cols = np.nonzero(own)
+ t, b_, l, r = int(rows.min()), int(rows.max()) + 1, int(cols.min()), int(cols.max()) + 1
+ found.append((left + l, top + t, left + r, top + b_, own[t:b_, l:r], count))
+ if not found:
+ return []
+ floor = max(FIGURE_MIN_PX, FIGURE_MIN_SHARE * max(f[5] for f in found))
+ return [f[:5] for f in found if f[5] >= floor]
+
+
+def alpha_figures(frames: Sequence[Image.Image], *, name: str = "figure") -> dict[str, dict[int, Image.Image]]:
+ """Each figure the frames' alpha draws, followed from frame to frame by where it stands (the nearest figure of the
+ frame before, within its own size): its crop on each frame it is drawn on, by the frame's place in `frames`. One
+ figure is `name`; several are `name`0, `name`1, ... in the order they are first seen, left to right."""
+ tracks: list[dict[str, Any]] = []
+ for k, frame in enumerate(frames):
+ rgba = frame.convert("RGBA")
+ alpha = np.asarray(rgba.getchannel("A"))
+ parts = sorted(_parts(alpha > ALPHA_MIN), key=lambda p: (p[0], p[1]))
+ taken: set[int] = set()
+ for left, top, right, bottom, own in parts:
+ centre = ((left + right) / 2, (top + bottom) / 2)
+ near = None
+ for i, track in enumerate(tracks):
+ if i in taken or track["seen"] != k - 1:
+ continue
+ reach = max(track["size"])
+ d = ((centre[0] - track["centre"][0]) ** 2 + (centre[1] - track["centre"][1]) ** 2) ** 0.5
+ if d <= reach and (near is None or d < near[1]):
+ near = (i, d)
+ if near is None:
+ tracks.append({"frames": {}})
+ near = (len(tracks) - 1, 0.0)
+ i = near[0]
+ taken.add(i)
+ crop = rgba.crop((left, top, right, bottom))
+ crop.putalpha(Image.fromarray(np.where(own, np.asarray(crop.getchannel("A")), 0).astype(np.uint8)))
+ tracks[i].update(seen=k, centre=centre, size=(right - left, bottom - top))
+ tracks[i]["frames"][k] = crop
+ if len(tracks) == 1:
+ return {name: tracks[0]["frames"]}
+ return {f"{name}{i}": t["frames"] for i, t in enumerate(tracks)}
+
+
+def box_figure(frames: Sequence[Image.Image], box: tuple[int, int, int, int], *,
+ name: str = "figure") -> dict[str, dict[int, Image.Image]]:
+ """The box x, y, w, h of each frame: the figure over a still background, read in place."""
+ x, y, w, h = box
+ return {name: {k: f.convert("RGBA").crop((x, y, x + w, y + h)) for k, f in enumerate(frames)}}
+
+
+# --- logs -------------------------------------------------------------------------------------------------------------
+
+def _ident(value: Any) -> str | None:
+ """A cell as a log names it: a string or a number as written, an object as its values joined by spaces (a sheet
+ and its cell), nothing for null."""
+ if value is None:
+ return None
+ if isinstance(value, str):
+ return value
+ if isinstance(value, bool) or isinstance(value, (int, float)):
+ return json.dumps(value)
+ if isinstance(value, dict):
+ parts = [p for p in (_ident(v) for v in value.values()) if p is not None]
+ return " ".join(parts) if parts else None
+ return json.dumps(value, sort_keys=True)
+
+
+def log_figures(path: Path, keys: Sequence[str]) -> dict[str, dict[int, str]]:
+ """The cell each figure shows on each frame, from a log of one JSON object a line, one line a frame from 0: each of
+ `keys` holds a figure's cell (`_ident`), or a list of figures (named by the key less its plural s, and their place
+ in it: `figures` gives figure0, figure1, ...)."""
+ lines = [line for line in Path(path).read_text(encoding="utf-8").splitlines() if line.strip()]
+ rows = [json.loads(line) for line in lines]
+ if not rows:
+ raise ValueError(f"{path}: no frame logged")
+ if not keys:
+ raise ValueError(f"{path}: name the keys that hold a figure's cell with --log-figure KEY (the first line holds: "
+ f"{', '.join(map(str, rows[0]))})")
+ missing = [key for key in keys if not any(key in row for row in rows)]
+ if missing:
+ raise ValueError(f"{path}: no line holds {', '.join(missing)} (the first line holds: {', '.join(map(str, rows[0]))})")
+ out: dict[str, dict[int, str]] = {}
+ for k, row in enumerate(rows):
+ for key in keys:
+ value = row.get(key)
+ if isinstance(value, list):
+ base = key[:-1] if key.endswith("s") and len(key) > 1 else key
+ for i, item in enumerate(value):
+ ident = _ident(item)
+ if ident is not None:
+ out.setdefault(f"{base}{i}", {})[k] = ident
+ continue
+ ident = _ident(value)
+ if ident is not None:
+ out.setdefault(key, {})[k] = ident
+ return out
+
+
+# --- lists of holds meant ---------------------------------------------------------------------------------------------
+
+def read_lists(paths: Sequence[Path]) -> list[dict[str, Any]]:
+ """Every hold the lists name, each with its file: a file, or every *.holds.json under a folder. A hold without a
+ reason, or whose frames are not from <= to, refuses the list."""
+ files: list[Path] = []
+ for path in paths:
+ path = Path(path)
+ files += sorted(path.rglob(f"*{LIST_SUFFIX}")) if path.is_dir() else [path]
+ out = []
+ for file in files:
+ data = json.loads(file.read_text(encoding="utf-8"))
+ for h in (data or {}).get("holds") or []:
+ if not isinstance(h.get("reason"), str) or not h["reason"].strip():
+ raise ValueError(f"{file}: a hold without a reason")
+ ints = [h.get(k) for k in ("from", "to")]
+ if not all(isinstance(v, int) and not isinstance(v, bool) for v in ints) or ints[0] > ints[1]:
+ raise ValueError(f"{file}: a hold's from..to (two whole frame numbers, from <= to)")
+ out.append({**h, "file": str(file)})
+ return out
+
+
+def for_scene(entries: Sequence[dict[str, Any]], scene: str | None) -> list[dict[str, Any]]:
+ """The holds of `scene`, and those that name none. A list that names scenes is read for one, named."""
+ named = sorted({str(e["scene"]) for e in entries if e.get("scene") is not None})
+ if named and scene is None:
+ raise ValueError(f"the list names scenes ({', '.join(named)}): pass --scene to read the holds of one")
+ return [e for e in entries if e.get("scene") is None or e["scene"] == scene]
+
+
+def strip_holds(meta: dict[str, Any], path: Path) -> list[dict[str, Any]]:
+ """A strip's own holds (the holds its cut means), as a list names them: every figure, its cells inclusive."""
+ out = []
+ for h in meta.get("holds") or []:
+ reason = str(h.get("reason") or h.get("kind") or "").strip()
+ if not reason or not isinstance(h.get("from"), int) or not isinstance(h.get("to"), int):
+ raise ValueError(f"{path}: a hold of the strip without a reason or its cells")
+ out.append({"from": h["from"], "to": h["to"], "reason": reason, "kind": h.get("kind"), "file": str(path)})
+ return out
+
+
+# --- the reading ------------------------------------------------------------------------------------------------------
+
+def _runs(ns: Sequence[int]) -> list[dict[str, int]]:
+ out: list[dict[str, int]] = []
+ for n in ns:
+ if out and out[-1]["to"] == n - 1:
+ out[-1]["to"] = n
+ else:
+ out.append({"from": n, "to": n})
+ return out
+
+
+def inspect(figures: dict[str, dict[int, Any]], *, first: int = 0, start: int | None = None,
+ listed: Sequence[dict[str, Any]] = (), wrap: bool = False,
+ same: Callable[[Any, Any], bool] | None = None) -> dict[str, Any]:
+ """The holds of each figure: frame n (`first` + its place) holds where the figure is shown on it and on the frame
+ before and both show one picture (`same`: `same_figure` on crops, equal names on a log's cells); with `wrap`, the
+ first frame against the last, as a loop plays. Frames before `start` are read only as the frame before. Each hold
+ is listed where a hold of `listed` names its figure (or none) and its frame. The report is a renderer's holds
+ check's: each figure's frames, holds, listed, unlisted and their runs, and the unlisted of all of them."""
+ start = first if start is None else start
+ table: dict[str, Any] = {}
+ unlisted = 0
+ for name, shown in figures.items():
+ order = sorted(shown)
+ compare = same or (lambda a, b: a == b if isinstance(a, str) else same_figure(a, b))
+ began: dict[int, int] = {}
+ held: list[dict[str, Any]] = []
+ for k in order:
+ began[k] = k
+ if k - 1 in shown and compare(shown[k - 1], shown[k]):
+ began[k] = began[k - 1]
+ n = first + k
+ if n >= start:
+ held.append({"n": n, "drawing": _drawing(shown[k], first + began[k])})
+ if wrap and len(order) > 1 and order[0] == 0 and compare(shown[order[-1]], shown[0]):
+ held.insert(0, {"n": first, "drawing": _drawing(shown[0], first + began[order[-1]])})
+ for h in held:
+ why = next((e for e in listed if (e.get("figure") is None or e["figure"] == name) and e["from"] <= h["n"] <= e["to"]),
+ None)
+ h["listed"] = why["reason"] if why else None
+ bad = [h for h in held if not h["listed"]]
+ unlisted += len(bad)
+
+ def group(hs: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ return [{**r, "drawings": list(dict.fromkeys(h["drawing"] for h in hs if r["from"] <= h["n"] <= r["to"]))}
+ for r in _runs([h["n"] for h in hs])]
+
+ good = [h for h in held if h["listed"]]
+ table[name] = {
+ "frames": sum(1 for k in order if first + k >= start), "holds": len(held), "listed": len(good),
+ "unlisted": len(bad), "unlistedRuns": group(bad),
+ "listedRuns": [{**r, "reason": next(h["listed"] for h in good if h["n"] == r["from"])} for r in group(good)],
+ }
+ return {"unlisted": unlisted, "table": table}
+
+
+def _drawing(item: Any, began: int) -> str:
+ """What a hold shows again: the cell a log names, or the frame its picture was first shown on."""
+ return item if isinstance(item, str) else f"frame {began}"
+
+
+# --- sources ----------------------------------------------------------------------------------------------------------
+
+def _frames_range(value: str | None) -> tuple[int, int | None] | None:
+ if value is None:
+ return None
+ lo, sep, hi = value.partition("-")
+ try:
+ a, b = int(lo), (int(hi) if hi else None)
+ except ValueError:
+ raise ValueError(f"--frames {value!r}: FROM-TO, two frame numbers from 0 (TO may be left out)") from None
+ if not sep or a < 0 or (b is not None and b < a):
+ raise ValueError(f"--frames {value!r}: FROM-TO, two frame numbers from 0, FROM <= TO")
+ return a, b
+
+
+def _box(value: str | None) -> tuple[int, int, int, int] | None:
+ if value is None:
+ return None
+ try:
+ x, y, w, h = (int(v) for v in value.split(","))
+ except ValueError:
+ raise ValueError(f"--box {value!r}: x,y,w,h in whole pixels") from None
+ if w <= 0 or h <= 0 or x < 0 or y < 0:
+ raise ValueError(f"--box {value!r}: x,y >= 0 and w,h > 0")
+ return x, y, w, h
+
+
+def _video_frames(clip: Path, folder: Path) -> list[Path]:
+ from sprite_gen.video import frames as frames_mod
+
+ try:
+ return frames_mod.extract(clip, folder, frames_mod.probe(clip)["stream_index"])
+ except SystemExit as exc:
+ raise ValueError(str(exc)) from None
+
+
+def _keyed(files: list[Path], folder: Path, key: str) -> list[Path]:
+ from sprite_gen.video import frames as frames_mod
+
+ try:
+ frames_mod.key_frames(files, folder, key=key, check_edges=False, spill="small", decontam="off")
+ except SystemExit as exc:
+ raise ValueError(str(exc)) from None
+ return [folder / f.name for f in files]
+
+
+def load(source: Path, *, key: str | None, work: Path, frames: tuple[int, int | None] | None
+ ) -> tuple[list[Image.Image], int, dict[str, Any]]:
+ """The frames of `source` (a folder of PNG frames, a video, or a strip sidecar), keyed by `key` where given: the
+ frames read (`frames` FROM-TO and the one before it), the number of the first, and what was read."""
+ source = Path(source).expanduser().resolve()
+ meta: dict[str, Any] = {}
+ if source.is_dir():
+ files = sorted(source.glob("*.png"))
+ if not files:
+ raise ValueError(f"{source}: no *.png frames")
+ kind = "frames"
+ elif source.name.endswith(".strip.json"):
+ meta = json.loads(source.read_text(encoding="utf-8"))
+ sheet = Image.open(source.with_name(source.name[: -len(".json")] + ".png")).convert("RGBA")
+ n, w, h = (int(meta[k]) for k in ("frames", "w", "h"))
+ if sheet.size != (n * w, h):
+ raise ValueError(f"{source}: the strip's size disagrees with its sidecar")
+ if key is not None:
+ raise ValueError("--key: a strip's cells carry their alpha")
+ cells = [sheet.crop((k * w, 0, (k + 1) * w, h)) for k in range(n)]
+ lo, hi = (frames or (0, None))
+ first = max(0, lo - 1)
+ return cells[first:(hi + 1 if hi is not None else None)], first, {"kind": "strip", "meta": meta}
+ elif source.suffix.lower() in VIDEO_SUFFIXES:
+ files = _video_frames(source, work / "raw")
+ kind = "video"
+ else:
+ raise ValueError(f"{source}: a folder of PNG frames, a video ({', '.join(VIDEO_SUFFIXES)}) or a *.strip.json")
+ lo, hi = (frames or (0, None))
+ first = max(0, lo - 1)
+ files = files[first:(hi + 1 if hi is not None else None)]
+ if not files:
+ raise ValueError(f"{source}: no frame in --frames {lo}-{'' if hi is None else hi}")
+ if key is not None:
+ files = _keyed(files, work / "keyed", key)
+ return [Image.open(f).convert("RGBA") for f in files], first, {"kind": kind}
+
+
+def _opaque(frames: Sequence[Image.Image]) -> bool:
+ return all(f.getchannel("A").getextrema()[0] == 255 for f in frames)
+
+
+def read(*, source: Path | None = None, key: str | None = None, box: str | None = None, log: Path | None = None,
+ log_figures_: Sequence[str] = (), lists: Sequence[Path] = (), scene: str | None = None,
+ frames: str | None = None, figure: str = "figure") -> dict[str, Any]:
+ """The report of `inspect-holds` (see the module): the source read one of the four ways, its holds listed or not."""
+ ways = [w for w, given in (("--key", key), ("--box", box), ("--log", log)) if given is not None]
+ if len(ways) > 1:
+ raise ValueError(f"{' and '.join(ways)}: give one way to the figure")
+ if (source is None) == (log is None):
+ raise ValueError("give --source (frames, a video or a strip) or --log (a log of the cells), one of them")
+ if key is not None and key not in KEYS:
+ raise ValueError(f"--key {key!r}: one of {', '.join(KEYS)}")
+ span = _frames_range(frames)
+ entries = for_scene(read_lists(lists), scene)
+ report: dict[str, Any] = {"kind": REPORT_KIND, "scene": scene,
+ "rule": {"pixel_same": held_fill_mod.PIXEL_SAME, "changed_max": held_fill_mod.CHANGED_MAX,
+ "search_px": SEARCH_PX},
+ "lists": sorted({e["file"] for e in entries})}
+ wrap = False
+ if log is not None:
+ figures: dict[str, dict[int, Any]] = log_figures(Path(log).expanduser().resolve(), log_figures_)
+ lo, hi = span or (0, None)
+ first = max(0, lo - 1)
+ figures = {name: {k - first: v for k, v in shown.items() if k >= first and (hi is None or k <= hi)}
+ for name, shown in figures.items()}
+ report.update(source=str(Path(log).expanduser().resolve()), read_by="log")
+ same = None
+ count = max((max(s) + 1 for s in figures.values() if s), default=0)
+ else:
+ with tempfile.TemporaryDirectory(prefix="sprite-gen-holds-") as work:
+ loaded, first, what = load(Path(source), key=key, work=Path(work), frames=span) # type: ignore[arg-type]
+ count = len(loaded)
+ report["source"] = str(Path(source).expanduser().resolve()) # type: ignore[arg-type]
+ if what["kind"] == "strip":
+ entries = entries + strip_holds(what["meta"], Path(source))
+ wrap = bool(what["meta"].get("loop", True)) and span is None
+ if box is not None:
+ figures, same, report["read_by"] = box_figure(loaded, _box(box), name=figure), _same_in_place, "box" # type: ignore[arg-type]
+ else:
+ if key is None and _opaque(loaded):
+ raise ValueError("the frames are opaque: a figure is read by its alpha — give --key (a keyed clip), --box "
+ "x,y,w,h (a still background) or --log (the cells a renderer logged); an opaque frame "
+ "whose background moves is not read")
+ figures, same, report["read_by"] = alpha_figures(loaded, name=figure), None, "key" if key else "alpha"
+ start = span[0] if span else first
+ report.update(first_frame=start, frames=count - (start - first), wrap=wrap)
+ report.update(inspect(figures, first=first, start=start, listed=entries, wrap=wrap, same=same))
+ return report
+
+
+# --- the command ------------------------------------------------------------------------------------------------------
+
+def add_arguments(parser: argparse.ArgumentParser) -> None:
+ parser.add_argument("--source", type=Path, help="a folder of PNG frames (in name order, the first frame 0), a video "
+ "(mp4, mov, webm, mkv) or a video-loop strip sidecar (*.strip.json, its cells the frames)")
+ way = parser.add_mutually_exclusive_group()
+ way.add_argument("--key", choices=KEYS, help="key each frame as video-frames keys a clip, and read the figure by the "
+ "alpha it gives (a clip filmed on a key colour)")
+ way.add_argument("--box", help="x,y,w,h: read the box of each frame in place (a figure over a still background)")
+ way.add_argument("--log", type=Path, help="a log of the cell each figure shows on each frame, one JSON object a "
+ "line, one line a frame from 0 (a renderer's log); read in place of --source")
+ parser.add_argument("--log-figure", action="append", default=[], help="with --log: a key of each line that holds a "
+ "figure's cell (repeat for each figure); a list holds several (figures gives figure0, figure1, ...)")
+ parser.add_argument("--holds", action="append", type=Path, default=[], help="a list of the holds meant, "
+ '{"holds": [{"scene", "figure", "from", "to", "reason"}]}, frames inclusive; or a folder, every '
+ "*.holds.json under it (repeat for more)")
+ parser.add_argument("--scene", help="the scene the video is, for a list whose holds name scenes")
+ parser.add_argument("--figure", default="figure", help="the name of the figure the frames show (several: the name "
+ "and 0, 1, ... in the order they are first seen, left to right); default figure")
+ parser.add_argument("--frames", help="FROM-TO: read these frames only (and the one before FROM, to compare with)")
+ parser.add_argument("--gate", action="store_true", help="exit 1 where any hold is on no list")
+ parser.add_argument("--report", type=Path, help="also write the report here (JSON)")
+
+
+def run(**kwargs: object) -> int:
+ """Read once; print the report. 0, or 1 under --gate with a hold on no list; 2 on an error."""
+ parser = argparse.ArgumentParser(add_help=False)
+ add_arguments(parser)
+ args = namespace_from_kwargs(parser, kwargs)
+ try:
+ report = read(source=args.source, key=args.key, box=args.box, log=args.log, log_figures_=args.log_figure,
+ lists=args.holds, scene=args.scene, frames=args.frames, figure=args.figure)
+ payload = json.dumps(report, ensure_ascii=False, indent=2) + "\n"
+ if args.report is not None:
+ out = Path(args.report).expanduser().resolve()
+ out.parent.mkdir(parents=True, exist_ok=True)
+ atomic_write_text(out, payload)
+ except (ValueError, OSError) as exc:
+ print(f"inspect-holds: {exc}", file=sys.stderr)
+ return 2
+ print(payload, end="")
+ if report["unlisted"]:
+ runs = "; ".join(f"{name} {', '.join(str(r['from']) if r['from'] == r['to'] else f'{r['from']}-{r['to']}' for r in row['unlistedRuns'])}"
+ for name, row in report["table"].items() if row["unlisted"])
+ many = report["unlisted"] > 1
+ print(f"inspect-holds: {report['unlisted']} frame{'s' if many else ''} show{'' if many else 's'} the picture of the "
+ f"frame before and {'are' if many else 'is'} on no list: {runs}", file=sys.stderr)
+ if args.gate:
+ return 1
+ return 0
+
+
+def main(argv: list[str] | None = None) -> int:
+ utf8_streams()
+ parser = argparse.ArgumentParser(prog="inspect-holds", 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/tests/qa/test_inspect_holds.py b/tests/qa/test_inspect_holds.py
new file mode 100644
index 0000000..79c1bda
--- /dev/null
+++ b/tests/qa/test_inspect_holds.py
@@ -0,0 +1,252 @@
+# SPDX-License-Identifier: Apache-2.0
+"""`inspect-holds`: the frames on which a figure shows the picture it showed on the frame before, read on drawn
+figures. Each case draws a figure whose arms and legs swing a few pixels a frame, with frames shown again put in by
+hand; the cases read it by its alpha, by a key, inside a still box, by a log of the cells, from an mp4, and from a
+strip, and hold the list of holds meant (listed or not) and the gate."""
+import json
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+from PIL import Image, ImageDraw
+
+from sprite_gen.qa import holds
+
+GREEN = (0, 255, 0)
+W, H = 320, 200
+
+
+def figure(pose: int) -> Image.Image:
+ """A figure 60 px wide and 110 high, on a clear canvas just its size: a striped body and head, its arms and legs
+ swinging 4 px a pose apart (each pose changes several per cent of its pixels)."""
+ im = Image.new("RGBA", (90, 120), (0, 0, 0, 0))
+ d = ImageDraw.Draw(im)
+ swing = (pose % 7) * 4 - 12
+ d.ellipse((30, 2, 60, 32), fill=(230, 190, 150, 255), outline=(40, 30, 20, 255), width=2)
+ d.rectangle((30, 32, 60, 80), fill=(60, 90, 200, 255), outline=(20, 20, 60, 255), width=2)
+ for y in range(36, 80, 8):
+ d.line((32, y, 58, y), fill=(200, 200, 60, 255), width=2)
+ d.rectangle((20 + swing // 2, 36, 28 + swing // 2, 74), fill=(230, 190, 150, 255))
+ d.rectangle((62 - swing // 2, 36, 70 - swing // 2, 74), fill=(230, 190, 150, 255))
+ d.rectangle((33 + swing, 80, 43 + swing, 118), fill=(40, 40, 40, 255))
+ d.rectangle((47 - swing, 80, 57 - swing, 118), fill=(40, 40, 40, 255))
+ return im
+
+
+def scene(poses: list[int], *, at: list[tuple[int, int]] | None = None, background: tuple[int, ...] | None = None,
+ second: list[int] | None = None) -> list[Image.Image]:
+ """One frame per pose: the figure drawn at `at` (default the same place), on a clear canvas or an opaque
+ `background`; a `second` figure's poses drawn far to its right."""
+ frames = []
+ for k, pose in enumerate(poses):
+ im = Image.new("RGBA", (W, H), (*background, 255) if background else (0, 0, 0, 0))
+ x, y = at[k] if at else (40, 50)
+ im.alpha_composite(figure(pose), (x, y))
+ if second is not None:
+ im.alpha_composite(figure(second[k] + 3), (210, 60))
+ frames.append(im)
+ return frames
+
+
+def save(frames: list[Image.Image], folder: Path) -> Path:
+ folder.mkdir(parents=True, exist_ok=True)
+ for k, im in enumerate(frames):
+ im.save(folder / f"{k:04d}.png")
+ return folder
+
+
+def read(*args: str) -> tuple[int, dict, str]:
+ proc = subprocess.run([sys.executable, "-m", "sprite_gen.cli", "inspect-holds", *args], capture_output=True,
+ encoding="utf-8")
+ report = json.loads(proc.stdout) if proc.stdout.strip() else {}
+ return proc.returncode, report, proc.stderr
+
+
+def runs(report: dict, name: str = "figure", *, listed: bool = False) -> list[tuple[int, int]]:
+ return [(r["from"], r["to"]) for r in report["table"][name]["listedRuns" if listed else "unlistedRuns"]]
+
+
+# A figure that moves on every frame but three: frame 3 shows frame 2's picture, frames 7 and 8 frame 6's.
+POSES = [0, 1, 2, 2, 3, 4, 5, 5, 5, 6, 7, 8]
+
+
+def test_a_figure_shown_again_is_found_frame_by_frame(tmp_path: Path) -> None:
+ code, report, err = read("--source", str(save(scene(POSES), tmp_path / "frames")))
+ assert code == 0, err
+ row = report["table"]["figure"]
+ assert row["frames"] == len(POSES) and row["holds"] == 3 and row["unlisted"] == 3 and row["listed"] == 0
+ assert runs(report) == [(3, 3), (7, 8)]
+ assert report["read_by"] == "alpha" and report["unlisted"] == 3
+
+
+def test_a_figure_that_moves_on_every_frame_holds_none(tmp_path: Path) -> None:
+ code, report, err = read("--source", str(save(scene(list(range(12))), tmp_path / "frames")))
+ assert code == 0, err
+ assert report["table"]["figure"]["holds"] == 0 and report["unlisted"] == 0
+
+
+def test_a_held_picture_the_camera_follows_is_still_a_hold(tmp_path: Path) -> None:
+ """The camera follows the figure: its picture stands somewhere else on every frame, held or not, by up to 37 px."""
+ at = [(10 + 17 * k + (k % 3), 40 + (k % 2) * 3) for k in range(len(POSES))]
+ code, report, err = read("--source", str(save(scene(POSES, at=at), tmp_path / "frames")))
+ assert code == 0, err
+ assert runs(report) == [(3, 3), (7, 8)]
+
+
+def test_two_figures_are_read_apart(tmp_path: Path) -> None:
+ other = [0, 1, 2, 3, 4, 5, 6, 6, 7, 8, 8, 9]
+ code, report, err = read("--source", str(save(scene(POSES, second=other), tmp_path / "frames")))
+ assert code == 0, err
+ assert sorted(report["table"]) == ["figure0", "figure1"]
+ assert runs(report, "figure0") == [(3, 3), (7, 8)]
+ assert runs(report, "figure1") == [(7, 7), (10, 10)]
+
+
+def test_a_keyed_clip_is_read_by_its_key(tmp_path: Path) -> None:
+ code, report, err = read("--source", str(save(scene(POSES, background=GREEN), tmp_path / "frames")), "--key", "green")
+ assert code == 0, err
+ assert report["read_by"] == "key" and runs(report) == [(3, 3), (7, 8)]
+
+
+def test_opaque_frames_are_not_read_without_a_way_to_the_figure(tmp_path: Path) -> None:
+ code, report, err = read("--source", str(save(scene(POSES, background=(128, 128, 128)), tmp_path / "frames")))
+ assert code == 2 and not report
+ assert "opaque" in err and "--key" in err and "--box" in err and "--log" in err
+
+
+def test_a_box_reads_a_figure_over_a_still_background(tmp_path: Path) -> None:
+ frames = scene(POSES, background=(128, 128, 128))
+ code, report, err = read("--source", str(save(frames, tmp_path / "frames")), "--box", "30,40,110,140")
+ assert code == 0, err
+ assert report["read_by"] == "box" and runs(report) == [(3, 3), (7, 8)]
+
+
+def test_a_log_reads_the_cells_by_name(tmp_path: Path) -> None:
+ lines = [{"t": k / 60, "hero": f"run {p}", "figures": [f"stand {k // 4}", None], "kind": "run"}
+ for k, p in enumerate(POSES)]
+ log = tmp_path / "cells.jsonl"
+ log.write_text("".join(json.dumps(line) + "\n" for line in lines))
+ code, report, err = read("--log", str(log), "--log-figure", "hero", "--log-figure", "figures")
+ assert code == 0, err
+ assert report["read_by"] == "log" and sorted(report["table"]) == ["figure0", "hero"]
+ assert runs(report, "hero") == [(3, 3), (7, 8)]
+ assert runs(report, "figure0") == [(1, 3), (5, 7), (9, 11)]
+ assert report["table"]["hero"]["unlistedRuns"][1]["drawings"] == ["run 5"]
+
+
+def test_a_log_names_the_keys_that_hold_figures(tmp_path: Path) -> None:
+ log = tmp_path / "cells.jsonl"
+ log.write_text(json.dumps({"t": 0, "hero": "run 0"}) + "\n")
+ code, _report, err = read("--log", str(log))
+ assert code == 2 and "--log-figure" in err and "hero" in err
+
+
+def test_a_listed_hold_is_listed_and_an_unlisted_one_fails_the_gate(tmp_path: Path) -> None:
+ source = str(save(scene(POSES), tmp_path / "frames"))
+ listed = tmp_path / "meant.holds.json"
+ listed.write_text(json.dumps({"holds": [
+ {"scene": "roof", "figure": "figure", "from": 7, "to": 8, "reason": "a stop the move means"},
+ {"scene": "other", "figure": "figure", "from": 3, "to": 3, "reason": "another scene's"},
+ ]}))
+ code, report, err = read("--source", source, "--holds", str(listed), "--scene", "roof")
+ assert code == 0, err
+ row = report["table"]["figure"]
+ assert (row["holds"], row["listed"], row["unlisted"]) == (3, 2, 1)
+ assert runs(report) == [(3, 3)] and runs(report, listed=True) == [(7, 8)]
+ assert row["listedRuns"][0]["reason"] == "a stop the move means"
+ code, _report, err = read("--source", source, "--holds", str(listed), "--scene", "roof", "--gate")
+ assert code == 1 and "1 frame" in err
+ listed.write_text(json.dumps({"holds": [{"from": 3, "to": 8, "reason": "all of them meant"}]}))
+ code, report, err = read("--source", source, "--holds", str(listed), "--gate")
+ assert code == 0, err
+ assert report["unlisted"] == 0 and report["table"]["figure"]["listed"] == 3
+
+
+def test_a_list_is_read_as_its_writer_wrote_it(tmp_path: Path) -> None:
+ """A list that names scenes is read for the scene named; a hold without a reason, or with its frames the wrong way
+ round, refuses the list (as holds lists are read elsewhere)."""
+ source = str(save(scene(POSES), tmp_path / "frames"))
+ listed = tmp_path / "meant.holds.json"
+ listed.write_text(json.dumps({"holds": [{"scene": "roof", "figure": "figure", "from": 3, "to": 3, "reason": "meant"}]}))
+ code, _report, err = read("--source", source, "--holds", str(listed))
+ assert code == 2 and "--scene" in err and "roof" in err
+ listed.write_text(json.dumps({"holds": [{"from": 3, "to": 3, "reason": " "}]}))
+ code, _report, err = read("--source", source, "--holds", str(listed))
+ assert code == 2 and "reason" in err
+ listed.write_text(json.dumps({"holds": [{"from": 4, "to": 3, "reason": "meant"}]}))
+ code, _report, err = read("--source", source, "--holds", str(listed))
+ assert code == 2 and "from" in err
+ # A folder: every *.holds.json under it.
+ (tmp_path / "lists" / "deep").mkdir(parents=True)
+ (tmp_path / "lists" / "deep" / "a.holds.json").write_text(json.dumps({"holds": [{"from": 3, "to": 3, "reason": "meant"}]}))
+ (tmp_path / "lists" / "b.holds.json").write_text(json.dumps({"holds": [{"from": 7, "to": 8, "reason": "meant too"}]}))
+ code, report, err = read("--source", source, "--holds", str(tmp_path / "lists"), "--gate")
+ assert code == 0, err
+ assert report["table"]["figure"]["listed"] == 3
+
+
+def strip(tmp_path: Path, cells: list[Image.Image], meta: dict) -> Path:
+ w, h = cells[0].size
+ sheet = Image.new("RGBA", (w * len(cells), h), (0, 0, 0, 0))
+ for k, cell in enumerate(cells):
+ sheet.alpha_composite(cell, (k * w, 0))
+ sheet.save(tmp_path / "walk.strip.png")
+ path = tmp_path / "walk.strip.json"
+ path.write_text(json.dumps({"frames": len(cells), "w": w, "h": h, "delay_ms": 41.67, **meta}))
+ return path
+
+
+def test_a_strip_reads_its_own_holds_as_listed(tmp_path: Path) -> None:
+ cells = [figure(p) for p in [0, 1, 2, 3, 3, 3, 3, 4, 5, 5, 6, 7]]
+ path = strip(tmp_path, cells, {"loop": False, "holds": [
+ {"from": 3, "to": 6, "kind": "motion-hold", "reason": "held 4 cells, longer than a drawing on threes"}]})
+ code, report, err = read("--source", str(path), "--gate")
+ assert code == 1, err
+ row = report["table"]["figure"]
+ assert runs(report, listed=True) == [(4, 6)] and runs(report) == [(9, 9)]
+ assert row["listedRuns"][0]["reason"].startswith("held 4 cells")
+
+
+def test_a_looping_strip_is_read_across_its_wrap(tmp_path: Path) -> None:
+ """A loop plays its last cell then its first: a first cell that shows the last cell's picture is shown again."""
+ cells = [figure(p) for p in [0, 1, 2, 3, 4, 5, 0]]
+ code, report, err = read("--source", str(strip(tmp_path, cells, {"loop": True})))
+ assert code == 0, err
+ assert runs(report) == [(0, 0)] and report["wrap"] is True
+ code, report, err = read("--source", str(strip(tmp_path, cells, {"loop": False})))
+ assert code == 0, err
+ assert runs(report) == [] and report["wrap"] is False
+
+
+def test_a_range_reads_its_frames_and_the_one_before(tmp_path: Path) -> None:
+ code, report, err = read("--source", str(save(scene(POSES), tmp_path / "frames")), "--frames", "7-11")
+ assert code == 0, err
+ assert runs(report) == [(7, 8)] and report["table"]["figure"]["frames"] == 5
+ assert report["first_frame"] == 7
+
+
[email protected](not shutil.which("ffmpeg"), reason="ffmpeg required")
+def test_an_mp4_is_read_by_its_key(tmp_path: Path) -> None:
+ """A keyed clip encoded as a video model's is (libx264, crf 18): the frames shown again are found through it."""
+ folder = save([im.convert("RGB").convert("RGBA") for im in scene(POSES, background=GREEN)], tmp_path / "frames")
+ clip = tmp_path / "clip.mp4"
+ subprocess.run(["ffmpeg", "-v", "error", "-framerate", "24", "-i", str(folder / "%04d.png"), "-c:v", "libx264",
+ "-crf", "18", "-pix_fmt", "yuv420p", str(clip)], check=True)
+ code, report, err = read("--source", str(clip), "--key", "green")
+ assert code == 0, err
+ assert runs(report) == [(3, 3), (7, 8)] and report["table"]["figure"]["frames"] == len(POSES)
+
+
+def test_the_python_reading_matches_the_command(tmp_path: Path) -> None:
+ frames = scene(POSES)
+ report = holds.inspect(holds.alpha_figures(frames), first=0)
+ assert [(r["from"], r["to"]) for r in report["table"]["figure"]["unlistedRuns"]] == [(3, 3), (7, 8)]
+
+
+def test_a_report_is_written_where_asked(tmp_path: Path) -> None:
+ out = tmp_path / "out" / "holds.json"
+ code, report, err = read("--source", str(save(scene(POSES), tmp_path / "frames")), "--report", str(out))
+ assert code == 0, err
+ assert json.loads(out.read_text()) == report and report["kind"] == holds.REPORT_KIND