Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
fix(inspect-holds): a figure drawn in a few pixels is read, and a reading that reads no frame against the frame before is an error, never a gate passed
Soohong Kimd2e15740ac5b
diff --git a/sprite_gen/qa/holds.py b/sprite_gen/qa/holds.pyindex 8941b04..d6bdb54 100644--- a/sprite_gen/qa/holds.py+++ b/sprite_gen/qa/holds.py@@ -9,10 +9,11 @@ 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), eachfigure 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.+its body) and each followed from frame to frame by where it stands. A part much smaller than the largest part of its+frame is a speck, not a figure (`_parts`); the largest part is a figure however small. 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'spixels change by more than PIXEL_SAME, on its thumbnail and as drawn), read on the figure alone, each pair placed where@@ -23,7 +24,10 @@ The report is the one a renderer's holds check gives (each figure's `frames`, `h`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 outwhere 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."""+section 7) are listed with it. Each figure also gives its `steps`, its frames read against the frame before, and the+report `inspected`, the figures read on a step or more. A reading that reads no frame against the frame before (no+frame, no figure on any frame, or none on two frames in a row) knows nothing of a picture shown again: it is no reading+but an error (`NothingRead`, its report `inspected` 0), never a reading that found none."""from __future__ import annotations@@ -47,11 +51,23 @@ 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 bestALPHA_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+FIGURE_MIN_PX = 64 # a figure holds at least this many solid pixels, or FIGURE_MIN_PX_CAP of the frame's largest part ...+FIGURE_MIN_PX_CAP = 0.5 # ... where that is fewer: the largest part of a frame is a figure however small ...+FIGURE_MIN_SHARE = 0.02 # ... and this share of the largest part in its frame: less is a speckKEYS = ("auto", "green", "magenta", "white") # video-frames' --keyVIDEO_SUFFIXES = (".mp4", ".mov", ".webm", ".mkv", ".m4v")LIST_SUFFIX = ".holds.json"+NOTHING = "no frame was read against the frame before" # the error of a reading that read nothing (NothingRead)+++class NothingRead(ValueError):+ """A reading that read no frame against the frame before: no frame, no figure on any frame, or none on two frames+ in a row. It found no picture shown again because it read none; `report` is its report (`inspected` 0), where one+ was made."""++ def __init__(self, why: str, report: dict[str, Any] | None = None) -> None:+ super().__init__(why)+ self.report = report# --- pictures ---------------------------------------------------------------------------------------------------------@@ -90,7 +106,10 @@ def _same_in_place(a: Image.Image, b: Image.Image) -> bool: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."""+ (left, top, right, bottom) and its pixels inside that box; specks left out. A speck is a part under FIGURE_MIN_SHARE+ of the frame's largest part, or under FIGURE_MIN_PX, a floor never above FIGURE_MIN_PX_CAP of the largest part:+ a part's size tells a speck from a figure only beside a larger part, so the largest part of a frame is a figure+ however small (the only figure of a frame drawn in a few pixels is read), and so is one half its size or more."""from sprite_gen.video.frames import _components, _nearif not solid.any():@@ -112,7 +131,8 @@ def _parts(solid: np.ndarray) -> list[tuple[int, int, int, int, np.ndarray]]: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))+ largest = max(f[5] for f in found)+ floor = max(FIGURE_MIN_SHARE * largest, min(FIGURE_MIN_PX, FIGURE_MIN_PX_CAP * largest))return [f[:5] for f in found if f[5] >= floor]@@ -152,9 +172,12 @@ def alpha_figures(frames: Sequence[Image.Image], *, name: str = "figure") -> dicdef 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."""+ """The box x, y, w, h of each frame: the figure over a still background, read in place. A frame whose box holds no+ pixel with alpha over ALPHA_MIN (clear there, or the box past its edge) shows no figure: two such frames are no+ picture shown again."""x, y, w, h = box- return {name: {k: f.convert("RGBA").crop((x, y, x + w, y + h)) for k, f in enumerate(frames)}}+ crops = {k: f.convert("RGBA").crop((x, y, x + w, y + h)) for k, f in enumerate(frames)}+ return {name: {k: c for k, c in crops.items() if c.getchannel("A").getextrema()[1] > ALPHA_MIN}}# --- logs -------------------------------------------------------------------------------------------------------------@@ -174,14 +197,23 @@ def _ident(value: Any) -> str | None:return json.dumps(value, sort_keys=True)+def _log_rows(path: Path) -> list[dict[str, Any]]:+ """A log's lines, one a frame from 0; a log of none is nothing to read (`NothingRead`)."""+ 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 NothingRead(f"{path}: no frame logged")+ return rows++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 placein 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")+ return _log_cells(_log_rows(path), keys, path)+++def _log_cells(rows: Sequence[dict[str, Any]], keys: Sequence[str], path: Path) -> dict[str, dict[int, str]]: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]))})")@@ -265,7 +297,9 @@ def inspect(figures: dict[str, dict[int, Any]], *, first: int = 0, start: int |before and both show one picture (`same`: `same_figure` on crops, equal names on a log's cells); with `wrap`, thefirst frame against the last, as a loop plays. Frames before `start` are read only as the frame before. Each holdis 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."""+ check's: each figure's frames, holds, listed, unlisted and their runs, and the unlisted of all of them; and each+ figure's steps (its frames read against the frame before) and the figures `inspected` (read on a step or more).+ None inspected is no reading: `NothingRead`, with the report."""start = first if start is None else starttable: dict[str, Any] = {}unlisted = 0@@ -274,15 +308,22 @@ def inspect(figures: dict[str, dict[int, Any]], *, first: int = 0, start: int |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]] = []+ steps = 0for k in order:began[k] = k- if k - 1 in shown and compare(shown[k - 1], shown[k]):+ if k - 1 not in shown:+ continue+ n = first + k+ if n >= start:+ steps += 1+ if compare(shown[k - 1], shown[k]):began[k] = began[k - 1]- n = first + kif 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]])})+ if wrap and len(order) > 1 and order[0] == 0:+ steps += 1+ if 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)@@ -296,11 +337,15 @@ def inspect(figures: dict[str, dict[int, Any]], *, first: int = 0, start: int |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),+ "frames": sum(1 for k in order if first + k >= start), "steps": steps, "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}+ report = {"unlisted": unlisted, "inspected": sum(1 for row in table.values() if row["steps"]), "table": table}+ if not report["inspected"]:+ raise NothingRead("no figure is shown on two frames in a row" if any(row["frames"] for row in table.values())+ else "no figure is shown on any frame read", report)+ return reportdef _drawing(item: Any, began: int) -> str:@@ -357,13 +402,14 @@ def _keyed(files: list[Path], folder: Path, key: str) -> list[Path]: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."""+ frames read (`frames` FROM-TO and the one before it), the number of the first, and what was read. A source with no+ frame, or none from FROM on, is nothing to read (`NothingRead`)."""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")+ raise NothingRead(f"{source}: no *.png frames")kind = "frames"elif source.name.endswith(".strip.json"):meta = json.loads(source.read_text(encoding="utf-8"))@@ -374,24 +420,32 @@ def load(source: Path, *, key: str | None, work: Path, frames: tuple[int, int |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)+ first = _window(len(cells), frames, source, "cells")+ hi = frames[1] if frames else Nonereturn 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)+ first = _window(len(files), frames, source, "frames")+ hi = frames[1] if frames else Nonefiles = 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 _window(total: int, frames: tuple[int, int | None] | None, source: Path, unit: str) -> int:+ """The first frame read of `total` (the one before FROM), where a frame from FROM on is there to read; none is+ nothing to read (`NothingRead`)."""+ lo, hi = frames or (0, None)+ if lo >= total:+ raise NothingRead(f"{source}: no frame in --frames {lo}-{'' if hi is None else hi}: it has {total} {unit}"+ f"{f' (0-{total - 1})' if total else ''}")+ return max(0, lo - 1)++def _opaque(frames: Sequence[Image.Image]) -> bool:return all(f.getchannel("A").getextrema()[0] == 255 for f in frames)@@ -399,7 +453,8 @@ def _opaque(frames: Sequence[Image.Image]) -> bool: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."""+ """The report of `inspect-holds` (see the module): the source read one of the four ways, its holds listed or not.+ A reading that reads no frame against the frame before raises `NothingRead`, its report `inspected` 0, saying why."""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")@@ -408,43 +463,79 @@ def read(*, source: Path | None = None, key: str | None = None, box: str | Noneif key is not None and key not in KEYS:raise ValueError(f"--key {key!r}: one of {', '.join(KEYS)}")span = _frames_range(frames)+ in_box = _box(box)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})}+ "lists": sorted({e["file"] for e in entries}),+ "source": str(Path(log if log is not None else source).expanduser().resolve()), # type: ignore[arg-type]+ "read_by": "log" if log is not None else "box" if box is not None else "key" if key else "alpha"}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]+ size = None+ try:+ if log is not None:+ path = Path(log).expanduser().resolve()+ rows = _log_rows(path)+ first = _window(len(rows), span, path, "lines")+ last = len(rows) - 1 if span is None or span[1] is None else min(span[1], len(rows) - 1)+ figures: dict[str, dict[int, Any]] = {+ name: {k - first: v for k, v in shown.items() if first <= k <= last}+ for name, shown in _log_cells(rows, log_figures_, path).items()}+ same = None+ count = last - first + 1else:- 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"+ 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, size = len(loaded), loaded[0].size+ if what["kind"] == "strip":+ entries = entries + strip_holds(what["meta"], Path(source))+ wrap = bool(what["meta"].get("loop", True)) and span is None+ if in_box is not None:+ figures, same = box_figure(loaded, in_box, name=figure), _same_in_place+ 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 = alpha_figures(loaded, name=figure), None+ except NothingRead as exc:+ report.update(first_frame=span[0] if span else 0, frames=0, wrap=False, unlisted=0, inspected=0, table={})+ raise NothingRead(f"{NOTHING}: {exc}", report) from Nonestart = span[0] if span else firstreport.update(first_frame=start, frames=count - (start - first), wrap=wrap)- report.update(inspect(figures, first=first, start=start, listed=entries, wrap=wrap, same=same))+ try:+ report.update(inspect(figures, first=first, start=start, listed=entries, wrap=wrap, same=same))+ except NothingRead as exc:+ report.update(exc.report or {})+ why = _why_none(report, first, first + count - 1, key=key, box=in_box, size=size, keys=log_figures_)+ raise NothingRead(f"{NOTHING}: {why}", report) from Nonereturn report+def _why_none(report: dict[str, Any], first: int, last: int, *, key: str | None, box: tuple[int, int, int, int] | None,+ size: tuple[int, int] | None, keys: Sequence[str]) -> str:+ """Why a reading of frames `first`..`last` read no frame against the frame before, in its way's words."""+ start = report["first_frame"]+ asked = f"frame {start}" if start == last else f"frames {start}-{last}"+ if first == last:+ return f"one frame read ({asked}), and no frame before it to read it against"+ if any(row["frames"] for row in report["table"].values()):+ if report["read_by"] == "log":+ return f"the log names a figure's cell on no two lines in a row of {asked}"+ return (f"no figure is shown on two frames in a row of {asked} (a figure is followed from a frame to the next by "+ "where it stands, within its own size)")+ solid = f"pixel with alpha over {ALPHA_MIN}"+ if report["read_by"] == "log":+ return f"the log names no cell for {', '.join(keys)} on {asked}"+ if box is not None:+ w, h = size or (0, 0)+ return f"the box {','.join(map(str, box))} holds no {solid} on {asked} (the frames are {w}x{h})"+ if key is not None:+ return f"no figure on {asked} once keyed with --key {key} (no {solid})"+ return f"no figure on {asked} (no {solid})"++# --- the command ------------------------------------------------------------------------------------------------------def add_arguments(parser: argparse.ArgumentParser) -> None:@@ -470,13 +561,20 @@ def add_arguments(parser: argparse.ArgumentParser) -> None: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."""+ """Read once; print the report. 0, or 1 under --gate with a hold on no list; 2 on an error, a reading that read+ nothing among them (its report printed and written, `inspected` 0, with or without --gate)."""parser = argparse.ArgumentParser(add_help=False)add_arguments(parser)args = namespace_from_kwargs(parser, kwargs)+ nothing: NothingRead | None = Nonetry:- 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)+ 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)+ except NothingRead as exc:+ if exc.report is None:+ raise+ report, nothing = exc.report, excpayload = json.dumps(report, ensure_ascii=False, indent=2) + "\n"if args.report is not None:out = Path(args.report).expanduser().resolve()@@ -486,6 +584,9 @@ def run(**kwargs: object) -> int:print(f"inspect-holds: {exc}", file=sys.stderr)return 2print(payload, end="")+ if nothing is not None:+ print(f"inspect-holds: {nothing}", file=sys.stderr)+ return 2if 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"])diff --git a/tests/qa/test_inspect_holds.py b/tests/qa/test_inspect_holds.pyindex 79c1bda..ebe5e6e 100644--- a/tests/qa/test_inspect_holds.py+++ b/tests/qa/test_inspect_holds.py@@ -2,7 +2,9 @@"""`inspect-holds`: the frames on which a figure shows the picture it showed on the frame before, read on drawnfigures. Each case draws a figure whose arms and legs swing a few pixels a frame, with frames shown again put in byhand; 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."""+strip, and hold the list of holds meant (listed or not) and the gate. A figure drawn in a few pixels is read, specks+beside a figure are not, and a reading that reads no frame against the frame before is an error, whatever left it+nothing to read."""import jsonimport shutilimport subprocess@@ -250,3 +252,173 @@ def test_a_report_is_written_where_asked(tmp_path: Path) -> None:code, report, err = read("--source", str(save(scene(POSES), tmp_path / "frames")), "--report", str(out))assert code == 0, errassert json.loads(out.read_text()) == report and report["kind"] == holds.REPORT_KIND+++# --- a figure in a few pixels, specks, and a reading of nothing -------------------------------------------------------++BLUE = (70, 130, 220, 255)+++def block(w: int, h: int, *, size: tuple[int, int] = (24, 24), at: tuple[int, int] = (8, 6)) -> Image.Image:+ """A canvas of `size`, clear but for a solid block w x h at `at`."""+ im = Image.new("RGBA", size)+ im.paste(BLUE, (at[0], at[1], at[0] + w, at[1] + h))+ return im+++def dotted(im: Image.Image, dots: list[tuple[int, int, int]]) -> Image.Image:+ """`im` with a dot of 1, 2 or 3 px (a speck) at each (x, y, px), the same on every frame it is put on."""+ im = im.copy()+ for x, y, px in dots:+ im.paste((200, 50, 50, 255), (x, y, x + px, y + 1))+ return im++[email protected]("w, h", [(7, 9), (8, 8)], ids=["63px", "64px"])+def test_a_figure_drawn_in_a_few_pixels_is_read(tmp_path: Path, w: int, h: int) -> None:+ """One block, 7 x 9 (63 px) or 8 x 8 (64 px), shown three times. Before, a figure under 64 px was a speck: 63 px read+ no figure, an empty table, and the gate passed (exit 0) on two frames shown again; the only figure of a frame is+ read now, however small, and 64 px reads as it did."""+ code, report, err = read("--source", str(save([block(w, h)] * 3, tmp_path / "frames")), "--gate")+ assert code == 1, err+ assert report["unlisted"] == 2 and report["inspected"] == 1 and runs(report) == [(1, 2)]+ assert (report["table"]["figure"]["frames"], report["table"]["figure"]["steps"]) == (3, 2)+ assert "2 frames show the picture of the frame before" in err and "figure 1-2" in err+++def test_specks_beside_a_figure_are_still_left_out(tmp_path: Path) -> None:+ """Dots of 1, 2 and 3 px, far from the figure and the same on every frame (each would show its picture again on+ every frame, were it a figure), beside the striped figure and beside a figure of 63 px: neither reads a dot."""+ dots = [(250, 20, 1), (270, 100, 2), (300, 180, 3)]+ code, report, err = read("--source", str(save([dotted(im, dots) for im in scene(POSES)], tmp_path / "big")))+ assert code == 0, err+ assert sorted(report["table"]) == ["figure"] and runs(report) == [(3, 3), (7, 8)]+ small = dotted(block(7, 9, size=(48, 32)), [(30, 4, 1), (40, 20, 2), (24, 28, 3)])+ code, report, err = read("--source", str(save([small] * 3, tmp_path / "small")), "--gate")+ assert code == 1, err+ assert sorted(report["table"]) == ["figure"] and runs(report) == [(1, 2)]+++def test_two_figures_drawn_in_a_few_pixels_are_both_read(tmp_path: Path) -> None:+ """Two blocks of about 40 px apart: the left one shown four times, the right one a row taller each frame. A part+ half the frame's largest or more is a figure, so both are read: the left holds on 1-3, the right on none."""+ frames = []+ for k in range(4):+ im = block(6, 7, size=(48, 24), at=(4, 6))+ im.paste((220, 130, 70, 255), (30, 6, 36, 11 + k))+ frames.append(im)+ code, report, err = read("--source", str(save(frames, tmp_path / "frames")))+ assert code == 0, err+ assert sorted(report["table"]) == ["figure0", "figure1"] and report["inspected"] == 2+ assert runs(report, "figure0") == [(1, 3)] and runs(report, "figure1") == []+++def test_each_figure_s_steps_and_the_figures_inspected_are_counted(tmp_path: Path) -> None:+ source = str(save(scene(POSES), tmp_path / "frames"))+ _code, report, _err = read("--source", source)+ assert report["inspected"] == 1 and report["table"]["figure"]["steps"] == len(POSES) - 1+ _code, report, _err = read("--source", source, "--frames", "7-11")+ assert report["table"]["figure"]["steps"] == 5 # 7..11, each against the frame before+ 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 report["table"]["figure"]["steps"] == 7 # six steps and the wrap+++def test_frames_that_show_no_figure_are_no_reading(tmp_path: Path) -> None:+ """Three clear frames: no figure, so no frame read against the frame before. Before, an empty table and unlisted 0+ passed the gate (exit 0, nothing on stderr); it is an error now, with or without --gate, its report printed and+ written with `inspected` 0 and one line on stderr."""+ source = str(save([Image.new("RGBA", (24, 24))] * 3, tmp_path / "frames"))+ out = tmp_path / "holds.json"+ for gate in (["--gate"], []):+ code, report, err = read("--source", source, "--report", str(out), *gate)+ assert code == 2+ assert (report["inspected"], report["unlisted"], report["table"]) == (0, 0, {})+ assert json.loads(out.read_text()) == report+ assert err.splitlines() == ["inspect-holds: no frame was read against the frame before: no figure on frames 0-2 "+ "(no pixel with alpha over 8)"]+++def test_a_box_that_holds_nothing_on_a_frame_shows_no_picture_there(tmp_path: Path) -> None:+ """A figure in the box on frames 0-2, then gone: before, two clear crops were one picture shown again (holds at 4+ and 5); a frame whose box holds nothing now shows no figure there."""+ frames = scene([0, 1, 2]) + [Image.new("RGBA", (W, H))] * 3+ code, report, err = read("--source", str(save(frames, tmp_path / "frames")), "--box", "30,40,110,140", "--gate")+ assert code == 0, err+ row = report["table"]["figure"]+ assert (row["frames"], row["steps"], row["holds"]) == (3, 2, 0) and report["inspected"] == 1+++def _nothing(tmp_path: Path, case: str) -> list[str]:+ """The arguments of a reading that is left nothing to read, one way or another."""+ if case == "no frame":+ (tmp_path / "empty").mkdir()+ return ["--source", str(tmp_path / "empty")]+ if case == "one frame":+ return ["--source", str(save([block(8, 8)], tmp_path / "one"))]+ if case == "frames past --frames":+ return ["--source", str(save([block(8, 8)] * 3, tmp_path / "three")), "--frames", "3-5"]+ if case == "alpha under ALPHA_MIN":+ faint = Image.new("RGBA", (24, 24))+ faint.paste((70, 130, 220, holds.ALPHA_MIN), (4, 4, 20, 20))+ return ["--source", str(save([faint] * 3, tmp_path / "faint"))]+ if case == "keyed to nothing":+ return ["--source", str(save([Image.new("RGBA", (64, 64), (*GREEN, 255))] * 3, tmp_path / "green")), "--key", "green"]+ if case == "box over clear frames":+ return ["--source", str(save([Image.new("RGBA", (24, 24))] * 3, tmp_path / "clear")), "--box", "2,2,10,10"]+ if case == "box past the edge":+ return ["--source", str(save([Image.new("RGBA", (24, 24), (128, 128, 128, 255))] * 3, tmp_path / "grey")),+ "--box", "40,40,10,10"]+ log = tmp_path / "cells.jsonl"+ if case == "log of no cell":+ log.write_text("".join(json.dumps({"t": k, "hero": None}) + "\n" for k in range(5)))+ return ["--log", str(log), "--log-figure", "hero"]+ if case == "log past --frames":+ log.write_text("".join(json.dumps({"t": k, "hero": "run 0"}) + "\n" for k in range(5)))+ return ["--log", str(log), "--log-figure", "hero", "--frames", "50-60"]+ path = strip(tmp_path, [figure(p) for p in range(4)], {"loop": False})+ if case == "strip past --frames":+ return ["--source", str(path), "--frames", "10-12"]+ assert case == "strip past --frames, in a box"+ return ["--source", str(path), "--frames", "10-12", "--box", "0,0,10,10"]+++NOTHING_CASES = {+ "no frame": "no *.png frames",+ "one frame": "one frame read (frame 0), and no frame before it to read it against",+ "frames past --frames": "no frame in --frames 3-5: it has 3 frames (0-2)",+ "alpha under ALPHA_MIN": "no figure on frames 0-2 (no pixel with alpha over 8)",+ "keyed to nothing": "no figure on frames 0-2 once keyed with --key green (no pixel with alpha over 8)",+ "box over clear frames": "the box 2,2,10,10 holds no pixel with alpha over 8 on frames 0-2 (the frames are 24x24)",+ "box past the edge": "the box 40,40,10,10 holds no pixel with alpha over 8 on frames 0-2 (the frames are 24x24)",+ "log of no cell": "the log names no cell for hero on frames 0-4",+ "log past --frames": "no frame in --frames 50-60: it has 5 lines (0-4)",+ "strip past --frames": "no frame in --frames 10-12: it has 4 cells (0-3)",+ "strip past --frames, in a box": "no frame in --frames 10-12: it has 4 cells (0-3)",+}++[email protected]("case", list(NOTHING_CASES))+def test_a_reading_left_nothing_to_read_is_an_error_whatever_left_it_so(tmp_path: Path, case: str, capsys) -> None:+ """Every way a reading is left no frame to read against the frame before (the input, the alpha floor, the key, the+ box, the log, the frames asked) ends the same way: exit 2 under --gate, the report with `inspected` 0, and one line+ on stderr saying why. Before, all but the first and the `strip past --frames` (refused as opaque) passed the gate+ with an empty reading (`frames past --frames` read only the frame before 3), and the boxes failed it on frames shown+ again that showed nothing."""+ code = holds.main([*_nothing(tmp_path, case), "--gate"])+ out, err = capsys.readouterr()+ assert code == 2+ report = json.loads(out)+ assert (report["inspected"], report["unlisted"]) == (0, 0)+ assert len(err.splitlines()) == 1 and err.startswith(f"inspect-holds: {holds.NOTHING}: ")+ assert err.rstrip().endswith(NOTHING_CASES[case])+++def test_the_python_reading_raises_where_it_reads_nothing(tmp_path: Path) -> None:+ with pytest.raises(holds.NothingRead) as caught:+ holds.inspect(holds.alpha_figures([Image.new("RGBA", (24, 24))] * 3))+ assert caught.value.report == {"unlisted": 0, "inspected": 0, "table": {}}+ with pytest.raises(holds.NothingRead) as caught:+ holds.read(source=save([Image.new("RGBA", (24, 24))] * 3, tmp_path / "clear"))+ assert caught.value.report["inspected"] == 0 and caught.value.report["read_by"] == "alpha"+ assert str(caught.value).startswith(holds.NOTHING)