Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
feat(video): video-follow-inspect writes where a follow-through carries each region in every cell, and moves nothing
Soohong Kim61109c04e2fa
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 06f24af..96ef374 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,11 @@All notable public changes to `sprite-gen` are recorded here. Versions track the `version:` field in `SKILL.md` and `pyproject.toml`.+## Unreleased++- **New `sprite-gen video-follow-inspect`: where a follow-through carries each region in every cell, with nothing moved.** `video-follow` is given an ellipse in the strip's first cell and carries it with the body into every other; inside the carried ellipse every pixel moves, whatever it is a picture of. For the first cell somebody looked. For the others nobody did: an arm that swings across a chest is inside the chest's ellipse there and moves with it, and so does a sleeve of the chest's own colour, which no count of colours finds. Where the ellipse lies in those cells was written nowhere — the record keeps the body's bob and the strip's rounded offsets, from which the carry cannot be worked back for a strip of more than thirteen cells, and `--board` draws two cells. `video-follow-inspect` takes `video-follow`'s arguments (all but `--board`), reads the strip as cut and solves it with the same code, and writes into `--out-dir` `follow-inspect.json` and two boards of every cell. The record has, per cell, how far the regions are carried (`carry_px`, whole pixels) and per region the carried ellipse, its own offset and reach, how near that is to folding it, the least area of the source a pixel of the moved cell takes (`jacobian_min`: 0 where the picture stops and one line of the source is drawn across many — a region lowered by `--on-fold lower` is drawn nearly stopped where it moves most, not folded and stretched), the pixels the ellipse covers and how many are body, and the pixels the move changes; per region its gain and whether it is held; and the follow-through as `video-follow` records it. It names what it was read from: the strip's and the meta's sha256, the regions, the settings, the way the motion is read (`follow.POLICY`) and the engine's version, and `input_id`, one sha256 over those — the same before and after `video-follow` is run on the loop, another after a new cut, an alignment, a changed region or setting. It holds no path and no time: the same loop asked the same way writes the same record byte for byte. `follow-inspect.source.png` has the cells as cut and `follow-inspect.moved.png` the cells as `video-follow` would write them, each region's carried ellipse ringed just outside it; they are two files so that whoever says what is inside an ellipse can read the cells as cut alone, and each has a `pixels_sha256` over its pixels beside its file's. **The engine does not read what is inside an ellipse and does not guess it**: every region is `ownership: "unknown"` in every cell, from its centre to its rim, and `video-follow` still moves every cell. The loop directory is only read — not the strip, not its meta, not the `follow.source.png` that `video-follow` keeps — and an `--out-dir` at or under it is refused; what `video-follow` refuses, the inspection refuses in the same words under its own name. `video-follow` writes what 2.38.0 writes: strip, GIF, WebP, record, printed summary, messages and `--help`, byte for byte. Its body is now `follow.read_request` (the request, read and checked), `follow.solve` (an `Answer`: the motion, each region's gain, every cell's move) and the writing, and the inspection reads the first two; `follow.move_field` and `follow.region_weight` are the move and the weight `move_regions` draws with. [docs/video-pipeline.md](docs/video-pipeline.md#inspecting-a-follow-through--video-follow-inspect).+- **`tests/video/test_follow_inspect.py`** draws a figure whose head and torso sway by whole pixels, across once a cycle and down twice: the carry of every cell is the sway as drawn, and the ellipse is carried by it. The record's `follow` is what `video-follow` then writes to the strip's meta; every pixel `video-follow` changed is inside the carried ellipse the record gave, counted alike; each cell is on both boards at its box, as cut and as written, with the ring only on the board pixels just outside the ellipse. Three regions take a gain each, and the one held is carried and ringed and moves nothing; regions given in the other order keep their numbers and swap their places. The loop directory is the same before and after, byte and time, as cut and after a follow-through, and a loop inspected first is followed byte for byte as one that was not. The same loop asked twice writes the same three files; after `video-follow` the id is the same; a cycle turned by one cell, one more pixel in one cell, another delay or another key in the cut's record is another id; so is each of gain, freq, zeta, on-fold and every number of a region, and not the boards' scale or columns. What `video-follow` refuses is refused in the same words and writes nothing. The least area is the steepest of the weight along the move, to 0.05, and under 0.15 for a region lowered to its limit. A forearm of the torso's own colour across the chest in five cells leaves the carry and the record's `follow` as the bare figure's, is on the board of the cells as cut inside the ring, moves with the chest on the other board, and is marked in no cell.+## v2.38.0 - A body that is not one person stands square from behind and walks from behind without turning- **Output change: a body that is not one person stands square from behind, and walks or runs from behind without turning.** With `--body-plan` (a quadruped, a body without legs, a scene of several figures), the back still's view sentence (`STILL_VIEW_TEXT_ANY_BODY["back"]`, read by `still_view_text` and `gen --direction back`) now also says the body is square to the viewer and symmetric left to right: the back of the head centred above the body, neither side showing more than the other, any tail rising from the middle. A walk or run seen from behind says, after what the body stands on, that it stays level, square and straight the whole time, never turning or angling to either side so neither side comes into view, and does not sway from side to side, any tail held raised where it is with only its tip swaying (`BACK_GAIT_TEXT_ANY_BODY`; for a scene, every figure), in the built-in sentence and after a caller's `--motion` alike. A four-legged back still drawn from a three-quarter reference had come out turned, its head to one side and its tail to the other, and the walk filmed from it turned further until a flank showed and swayed; with both sentences the still was drawn straight behind and the walk held square. A person's prompts are unchanged, byte for byte; the front, side and diagonal views and every other state are unchanged.diff --git a/SKILL.md b/SKILL.mdindex 4060b25..a9e529c 100644--- a/SKILL.md+++ b/SKILL.md@@ -102,6 +102,7 @@ hold the arms still, and check the loop with `handed-check --state walk`.| Continue or edit an existing clip | `video-extend`, `video-edit` | [video](docs/video.md) || Grok video sprites | `video-set` | [video-pipeline](docs/video-pipeline.md) || A soft part of a walk loop follows the body (a chest, a belly): an ellipse in the first cell, after `video-cycle-align` | `video-follow` | [video-pipeline](docs/video-pipeline.md#6-follow-through--video-follow) |+| Where that ellipse is carried in every other cell, and what the move changes there (an arm crossing a chest moves with it): a record and boards of every cell, nothing moved | `video-follow-inspect` | [video-pipeline](docs/video-pipeline.md#inspecting-a-follow-through--video-follow-inspect) || Video sprites from a clip your agent makes with a connected video MCP (ZCRE, 지크) | `video-canvas`, `video-prompt --no-last-frame`, the agent's own MCP tools (quote, user approval, generate, save the mp4), then `video-frames` and `video-loop` (a walk or run with `--anchor motion-auto`, which holds its size), and for a walk or run cut in two or more directions `video-cycle-align --view …` over their loop directories (a set it stops on a loop that may hold two cycles: look at that loop, count its strides, and pass `--cycles <loop>=<k>`; a loop the report lists under `unnamed_feet` — its view could not tell the feet apart, or only by too small a margin (`low-margin`): look at its first candidate frame, say which own foot lands there, and align again with `--foot <loop>=left|right`). `video-set` is not run on this route, so the set stage it runs by default (`--align-cycles auto`) is yours to run. sprite-gen never calls the MCP. Walk, run and jump only: ZCRE's `grok-imagine-video-1.5` has no end frame, so idle, attack and diagonal walks are refused unless `--unpinned` | [video-pipeline](docs/video-pipeline.md#a-clip-from-a-video-mcp-on-your-agent--zcre) || Ordinary image or edit | `gen --provider codex` or `gen --provider grok` (subscription routes) | [gen](docs/gen.md) || Image generation with no login available (server, container, SaaS) | `gen --provider openai` — server/SaaS route on `OPENAI_API_KEY`, **billed per call**, never a default or a fallback | [gen](docs/gen.md#subscription-first--openai-is-named-or-it-does-not-run) |diff --git a/docs/README.md b/docs/README.mdindex ef87793..4acde46 100644--- a/docs/README.md+++ b/docs/README.md@@ -38,7 +38,7 @@ flowchart LR| Pipeline / tool group / workflow | Entry doc | Verbs ||---|---|---|| **A · atlas rows** — one still becomes a runtime sprite sheet | [run-contract.md](run-contract.md) | `prepare` → `gen` / `gen-set` → `extract` → `compose-atlas`; optional `curation` and recompose |-| **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-follow`; `handed-check` for an item on one side |+| **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-follow` (`video-follow-inspect` shows every cell of it and moves nothing); `handed-check` for an item on one side || **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`, `compose-layers`, breathing (compose), `export-pngs`, `export-aseprite` || **E · asset tools** — independent background, shadow and motion tools | [asset-tools.md](asset-tools.md) | `background-tile`, `shadow`, `inspect-motion` |diff --git a/docs/video-pipeline.md b/docs/video-pipeline.mdindex 9a330a7..69d4f56 100644--- a/docs/video-pipeline.md+++ b/docs/video-pipeline.md@@ -25,6 +25,7 @@ still ──video-canvas──▶ canvas.png ──video──▶ clip.mp4 ─| `sprite-gen video-set` | `sprite_gen/video/batch.py` | bases × states → one folder per item, `set.report.json`, `table.md` || `sprite-gen video-cycle-align` | `sprite_gen/video/align.py` | the loop directories of one walk or run, one per direction → one cycle length, each loop turned to start on a foot strike, + report ([loop repair](loop-repair.md) section 4) || `sprite-gen video-follow` | `sprite_gen/video/follow.py` | a loop directory + an ellipse → the strip, GIF and WebP with that region following the body ([section 6](#6-follow-through--video-follow)) |+| `sprite-gen video-follow-inspect` | `sprite_gen/video/follow_inspect.py` | a loop directory + the ellipses `video-follow` takes → a record of where each is carried in every cell and what the move changes there, and two boards of every cell; the loop directory is only read ([section 6](#inspecting-a-follow-through--video-follow-inspect)) |Wrappers: `scripts/video_canvas.py`, `scripts/video_frames.py`, `scripts/video_loop.py`,`scripts/video_set.py`. Binaries: `ffmpeg`/`ffprobe` (frames), `img2webp` from libwebp@@ -1175,6 +1176,84 @@ sprite-gen video-follow --loop-dir set/front-walk/loop --region 136,164,60,50 [-new cut with `video-loop` removes them too. Run `video-follow` again after either.- A one-shot (`kind: one-shot`) is refused: the follow-through is a loop's steady state.+### Inspecting a follow-through — `video-follow-inspect`++The ellipse is given in the first cell, where somebody looked. Into every other cell it is carried+by the body's motion, and there nobody looked: an arm that swings across a chest is inside the+chest's ellipse in those cells and moves with it, and so does a sleeve of the chest's own colour,+which no count of colours finds. The engine does not read what a pixel belongs to.+`video-follow-inspect` writes what somebody needs in order to look, and moves nothing:++```bash+sprite-gen video-follow-inspect --loop-dir set/front-run/loop --region 136,164,60,50 [--region …] \+ [--gain 2.5] [--on-fold refuse|lower] [--freq 2.4] [--zeta 0.6] \+ --out-dir inspect/front-run [--scale 2] [--columns 8]+```++- **Asked as `video-follow` is, answered by the same code.** It takes `video-follow`'s arguments+ (all but `--board`), reads the strip as cut — `follow.source.png` where a follow-through was+ already written, the strip itself where none was — and solves it where `video-follow` does+ (`follow.read_request`, `follow.solve`): the carry, each region's gain, the offsets and the+ moved cells are computed in one place, and both commands read them there. What `video-follow`+ refuses it refuses in the same words under its own name, and then writes nothing.+- **The loop directory is read and never written**: not the strip, not its meta, and not the+ `follow.source.png` that `video-follow` keeps on its first run. An `--out-dir` at or under the+ loop directory is refused. Run before `video-follow`, it changes nothing `video-follow` writes.+- **What is inside an ellipse is not read.** Every region is written `ownership: "unknown"` in+ every cell, the first included, from its centre to its rim; no cell is marked or held on a+ guess. `solid_px` counts the body's silhouette under the ellipse (alpha ≥ 128), not whose+ pixels they are. Saying which cells hold the part alone is for a person or a model that looks+ at the board of the cells as cut, and for a second reader apart from the first.+ `video-follow` takes no such list: it moves every cell.+- **`follow-inspect.json`** (`kind: video-follow-inspection`, `schema_version: 1`):++ | key | what it holds |+ |---|---|+ | `input_id` | one sha256 over what the answer is read from: the strip's sha256, the meta's `cut_sha256`, the regions, the settings, the policy and the engine's version |+ | `inputs.strip` | `file`, `sha256`, `bytes`: the strip as cut that was read |+ | `inputs.meta` | `file`, `sha256`, `bytes`: `<name>.strip.json` as read; `cut_sha256`: its sha256 without the `follow` record `video-follow` adds (keys sorted, no spaces); `follow_recorded` |+ | `inputs.cut` | `frames`, `w`, `h`, `delay_ms`, as read from the meta |+ | `inputs.regions`, `inputs.settings` | the ellipses in the order given; `gain`, `on_fold`, `freq_hz`, `zeta` |+ | `inputs.policy`, `inputs.engine` | the way the motion is read and a region moved, by name (`follow.POLICY`) with the constants it is fixed by; the engine's `name` and `version` |+ | `follow` | the follow-through as `video-follow` records it in the strip's meta, without `gif` and `webp` |+ | `regions[i]` | `index`, `ellipse` as given, `radius_px`, `gain` (0 when held), `held`, `gain_limit`; over all cells the largest `reach_px` and `fold_ratio`, the least `jacobian_min`, the sum of `changed_px`; `ring`, its colour on the boards |+ | `cells[k]` | `index`, `carry_px` (across, down), `changed_px`, `jacobian_min`, `box` (x0, y0, x1, y1: the cell's picture on both boards) and `regions[i]` |+ | `cells[k].regions[i]` | `ellipse`: the region carried (centre plus `carry_px`, the radii as given); `offset_px` (across, down) and `reach_px`: the region's own move in that cell, 0 when held; `fold_ratio`; `jacobian_min` and `jacobian_min_at` (x, y); `ellipse_px`, `solid_px`; `changed_px`; `ownership` |+ | `boards` | `scale`, `columns`, `size`, `ground`; `source` and `moved`, each `file`, `sha256` (the PNG file) and `pixels_sha256` (its pixels) |++- **`carry_px`** is how far the cell's body lies from the first cell's, in whole pixels: what+ every region's ellipse is carried by in that cell, and what `video-follow` carries it by. It+ was written nowhere before; from the record's rounded offsets it cannot be worked back for a+ strip of more than thirteen cells (the answer keeps six harmonics of the cycle).+- **`jacobian_min`** is the least area of the source that one pixel of the moved cell takes, over+ the pixels of the region's ellipse: 1 where nothing moves, 0 where the picture stops — one line+ of the source drawn across many — and under 0 where it would run backwards, which is what the+ fold check refuses. It is read on the pixels, between each pixel's neighbours on either side+ across and down, so for a region a few pixels across it reads a little over the steepest point+ of the weight. A region that `--on-fold lower` lowered moves at the largest gain that does not+ fold it, so in the cell where it moves most it is drawn nearly stopped: not folded, and+ stretched. `jacobian_min_at` is the pixel.+ Where regions overlap the move is the larger one's, so a region's numbers there are what is+ drawn in its ellipse, not its own move alone. `changed_px` counts the pixels whose RGBA the+ move changes; outside every carried ellipse it changes none.+- **The record names what it was read from.** It holds no path, no time and nothing of the+ machine: the same loop asked the same way writes the same record, byte for byte, anywhere.+ `input_id` is the same before and after `video-follow` is run on the loop, and another after a+ new cut, an alignment, a changed region or setting, or another engine version — what somebody+ saw on one cut's boards is not evidence for another cut. `--scale` and `--columns` change the+ boards and their sha256, not `input_id` and not a number of the record but the `box`es.+ `pixels_sha256` is over a board's pixels (RGB, row by row), so another PNG writer gives the same+ one; `sha256` is the file's. The offsets, ratios and areas are rounded to 4 places.+- **The boards** hold every cell of the strip in order, `--columns` to a row, each under its+ number (the first cell is 0), over a flat grey, `--scale` board pixels to a cell pixel. Each+ region's carried ellipse is ringed in its colour, dashed with black. The ring is on the board+ pixels just outside the ellipse — the first the move does not touch — so inside an ellipse the+ cell shows whole (but for another region's ring crossing it), and at `--scale 2` or more no+ cell pixel is covered whole. `follow-inspect.source.png` has the cells as cut;+ `follow-inspect.moved.png` has them as `video-follow` would write them, laid and ringed alike.+ They are two files so that whoever says what is inside an ellipse can be given the cells as cut+ alone, without the answer beside them.+## What the rules were measured onEvery threshold above (the 15 % period tolerance, the 2.0 seam gate, the 0.15diff --git a/sprite_gen/_modules.py b/sprite_gen/_modules.pyindex c0320f1..cc00297 100644--- a/sprite_gen/_modules.py+++ b/sprite_gen/_modules.py@@ -28,6 +28,7 @@ MODULE_DOMAIN = {'batch': 'video','align': 'video','follow': 'video',+ 'follow_inspect': 'video','rife_install': 'video','clip_prompt': 'video','prepare': 'gen',@@ -91,8 +92,8 @@ DOMAIN_TITLE = dict(DOMAINS)PIPELINES: list[dict[str, object]] = [{"key": "A", "name": "atlas rows", "verbs": ["prepare", "gen", "gen-set", "extract", "compose-atlas", "curation"],"chain": "prepare → gen (or gen-set) → extract → compose-atlas; optional curation and recompose", "doc": "docs/run-contract.md"},- {"key": "B", "name": "video → loop", "verbs": ["video-canvas", "video", "video-prompt", "video-frames", "video-loop", "video-set", "video-cycle-align", "video-follow", "handed-check"],- "chain": "video-canvas → video (or video-prompt + a video MCP) → video-frames → video-loop, or video-set; video-cycle-align across a set; video-follow for a soft part's follow-through; handed-check for an item on one side", "doc": "docs/video-pipeline.md"},+ {"key": "B", "name": "video → loop", "verbs": ["video-canvas", "video", "video-prompt", "video-frames", "video-loop", "video-set", "video-cycle-align", "video-follow", "video-follow-inspect", "handed-check"],+ "chain": "video-canvas → video (or video-prompt + a video MCP) → video-frames → video-loop, or video-set; video-cycle-align across a set; video-follow for a soft part's follow-through (video-follow-inspect shows every cell of it and moves nothing); handed-check for an item on one side", "doc": "docs/video-pipeline.md"},]TOOL_GROUPS: list[dict[str, object]] = [diff --git a/sprite_gen/cli.py b/sprite_gen/cli.pyindex 5fd6d4d..86a9424 100644--- a/sprite_gen/cli.py+++ b/sprite_gen/cli.py@@ -22,6 +22,7 @@ from sprite_gen.video import loop as video_loopfrom sprite_gen.video import clip_prompt as video_promptfrom sprite_gen.video import align as video_alignfrom sprite_gen.video import follow as video_follow+from sprite_gen.video import follow_inspect as video_follow_inspectfrom sprite_gen.video import rife_installfrom sprite_gen.effects import recolor, shadowfrom sprite_gen.scene import render, inspect_scene@@ -375,6 +376,12 @@ COMMANDS: dict[str, tuple[str, Callable[[argparse.ArgumentParser], None], Callabvideo_follow.add_arguments,video_follow.run,),+ # The same request as video-follow, answered by the same code, written down instead of over the loop.+ "video-follow-inspect": (+ "Where video-follow carries each region in every cell and what it would change there, with nothing moved: a record and two boards of every cell, for whoever says what is inside an ellipse.",+ video_follow_inspect.add_arguments,+ video_follow_inspect.run,+ ),"rife": ("install: download the pinned RIFE (rife-ncnn-vulkan, sha256-checked) into the user data directory, where the loop repair finds it.",rife_install.add_arguments,diff --git a/sprite_gen/video/follow.py b/sprite_gen/video/follow.pyindex ece0770..510cca4 100644--- a/sprite_gen/video/follow.py+++ b/sprite_gen/video/follow.py@@ -47,6 +47,7 @@ import osimport shutilimport sysimport tempfile+from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any@@ -57,6 +58,11 @@ from sprite_gen.spec.runio import atomic_write_textfrom sprite_gen.util.gif_utils import save_clean_giffrom sprite_gen.video import loop as loop_mod+VERB = "video-follow"+# How the motion is read and a region moved, by name. `video-follow-inspect` writes it beside what it read, so+# what somebody saw under one way of reading is not taken for another's: a change that gives the same strip,+# regions and settings another carry, offset or picture takes a new name.+POLICY = "common-lay/damped-mass/cos2-bilinear/1"FREQ_DEFAULT = 2.4 # Hz: a slow, soft partZETA_DEFAULT = 0.6 # damping ratio: it lags and settles, with no ringingGAIN_DEFAULT = 2.5 # times the physical answer@@ -280,6 +286,34 @@ def _sample(premultiplied: np.ndarray, sx: np.ndarray, sy: np.ndarray) -> np.ndareturn (a * (1 - fx) + b * fx) * (1 - fy) + (c * (1 - fx) + d * fx) * fy+def region_weight(xx: np.ndarray, yy: np.ndarray, region: tuple[float, float, float, float],+ shift: tuple[float, float]) -> np.ndarray:+ """Per pixel of a cell, how much of a region's move it takes: 1 at the centre of the ellipse carried by+ `shift`, 0 at its rim (cos²) and outside it. The pixels a region covers are those where this is over 0."""+ cx, cy, rx, ry = region+ r = np.sqrt(((xx - cx - shift[0]) / rx) ** 2 + ((yy - cy - shift[1]) / ry) ** 2)+ return np.where(r < 1, np.cos(r * math.pi / 2) ** 2, 0)+++def move_field(xx: np.ndarray, yy: np.ndarray, moves: list[tuple[list[tuple[float, float, float, float]], tuple[float, float]]],+ shift: tuple[float, float]) -> tuple[np.ndarray, np.ndarray, np.ndarray] | None:+ """Per pixel of a cell: whether a region of `moves`, carried by `shift`, covers it, and how far it is moved+ across and down. None when no region covers a pixel of the cell."""+ weights = []+ for regions, _ in moves:+ weight = np.zeros(xx.shape, np.float32)+ for region in regions:+ weight = np.maximum(weight, region_weight(xx, yy, region, shift))+ weights.append(weight)+ inside = np.logical_or.reduce([weight > 0 for weight in weights])+ if not inside.any():+ return None+ largest = np.argmax(np.stack([math.hypot(*offset) * weight for (_, offset), weight in zip(moves, weights)]), axis=0)[None]+ move_x = np.take_along_axis(np.stack([offset[0] * weight for (_, offset), weight in zip(moves, weights)]), largest, 0)[0]+ move_y = np.take_along_axis(np.stack([offset[1] * weight for (_, offset), weight in zip(moves, weights)]), largest, 0)[0]+ return inside, move_x, move_y++def move_regions(cell: Image.Image, moves: list[tuple[list[tuple[float, float, float, float]], tuple[float, float]]],shift: tuple[float, float]) -> Image.Image:"""`cell` with each group of regions moved by its own offset (dx, dy), their centres carried by `shift`.@@ -290,19 +324,10 @@ def move_regions(cell: Image.Image, moves: list[tuple[list[tuple[float, float, fsrc = np.asarray(cell.convert("RGBA"), dtype=np.float32)h, w = src.shape[:2]yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)- weights = []- for regions, _ in moves:- weight = np.zeros((h, w), np.float32)- for cx, cy, rx, ry in regions:- r = np.sqrt(((xx - cx - shift[0]) / rx) ** 2 + ((yy - cy - shift[1]) / ry) ** 2)- weight = np.maximum(weight, np.where(r < 1, np.cos(r * math.pi / 2) ** 2, 0))- weights.append(weight)- inside = np.logical_or.reduce([weight > 0 for weight in weights])- if not inside.any():+ field = move_field(xx, yy, moves, shift)+ if field is None:return cell.copy()- largest = np.argmax(np.stack([math.hypot(*offset) * weight for (_, offset), weight in zip(moves, weights)]), axis=0)[None]- move_x = np.take_along_axis(np.stack([offset[0] * weight for (_, offset), weight in zip(moves, weights)]), largest, 0)[0]- move_y = np.take_along_axis(np.stack([offset[1] * weight for (_, offset), weight in zip(moves, weights)]), largest, 0)[0]+ inside, move_x, move_y = fieldpm = src.copy()pm[..., :3] *= pm[..., 3:4] / 255moved = _sample(pm, xx - move_x, yy - move_y)@@ -315,9 +340,32 @@ def move_regions(cell: Image.Image, moves: list[tuple[list[tuple[float, float, freturn Image.fromarray(out, "RGBA")-def follow_loop(loop_dir: Path, regions: list[tuple[float, float, float, float]], *, gain: float = GAIN_DEFAULT,- freq: float = FREQ_DEFAULT, zeta: float = ZETA_DEFAULT, board: Path | None = None,- on_fold: str = "refuse") -> dict[str, Any]:+@dataclass(frozen=True, eq=False)+class Request:+ """A follow-through asked of a loop directory, read and checked; nothing is written by reading it."""++ loop_dir: Path+ name: str+ meta_path: Path+ meta_bytes: bytes+ meta: dict[str, Any]+ regions: list[tuple[float, float, float, float]]+ gain: float+ freq: float+ zeta: float+ on_fold: str++ @property+ def strip_path(self) -> Path:+ return self.loop_dir / f"{self.name}.strip.png"++ @property+ def source_path(self) -> Path:+ return self.loop_dir / SOURCE+++def read_request(loop_dir: Path, regions: list[tuple[float, float, float, float]], *, gain: float = GAIN_DEFAULT,+ freq: float = FREQ_DEFAULT, zeta: float = ZETA_DEFAULT, on_fold: str = "refuse", verb: str = VERB) -> Request:loop_dir = loop_dir.expanduser().resolve()# The numbers go into the record, which is JSON, and into the cells' arithmetic: a numpy number from a# caller (an int64 has no JSON form) is read as the float the command line gives, so every caller of the@@ -326,36 +374,103 @@ def follow_loop(loop_dir: Path, regions: list[tuple[float, float, float, float]]gain, freq, zeta = float(gain), float(freq), float(zeta)metas = sorted(loop_dir.glob("*.strip.json"))if len(metas) != 1:- raise SystemExit(f"video-follow: {loop_dir}: expected one <name>.strip.json from video-loop, found {len(metas)}")+ raise SystemExit(f"{verb}: {loop_dir}: expected one <name>.strip.json from video-loop, found {len(metas)}")meta_path = metas[0]name = meta_path.name[: -len(".strip.json")]- meta = json.loads(meta_path.read_text(encoding="utf-8"))+ meta_bytes = meta_path.read_bytes()+ meta = json.loads(meta_bytes.decode("utf-8"))if meta.get("kind") == "one-shot" or meta.get("loop") is False:- raise SystemExit("video-follow: a one-shot plays once; the follow-through is a loop's steady state")+ raise SystemExit(f"{verb}: a one-shot plays once; the follow-through is a loop's steady state")if not regions:- raise SystemExit("video-follow: at least one --region cx,cy,rx,ry")+ raise SystemExit(f"{verb}: at least one --region cx,cy,rx,ry")if gain < 0 or freq <= 0 or not 0 < zeta:- raise SystemExit("video-follow: --gain must be 0 or more, --freq and --zeta above 0")+ raise SystemExit(f"{verb}: --gain must be 0 or more, --freq and --zeta above 0")if on_fold not in ON_FOLD_MODES:- raise SystemExit(f"video-follow: unknown --on-fold {on_fold!r}; expected one of {', '.join(ON_FOLD_MODES)}")- strip_path = loop_dir / f"{name}.strip.png"- source = loop_dir / SOURCE- if not source.exists():- shutil.copyfile(strip_path, source)- strip = Image.open(source).convert("RGBA")+ raise SystemExit(f"{verb}: unknown --on-fold {on_fold!r}; expected one of {', '.join(ON_FOLD_MODES)}")+ return Request(loop_dir, name, meta_path, meta_bytes, meta, regions, gain, freq, zeta, on_fold)+++@dataclass(frozen=True, eq=False)+class Answer:+ """What a request comes to on a strip: the body's motion, each region's gain, and every cell's move.++ `video-follow` writes it over the loop; `video-follow-inspect` writes it down and changes nothing. Both+ read the carry, the offsets and the moved cells here, and nowhere else."""++ request: Request+ cells: list[Image.Image]+ cols: np.ndarray # per cell, how far its body lies from cell 0's: across+ rows: np.ndarray # and down+ height0: int+ worn: list[int]+ requested: float+ reach_requested: float+ reach_per_gain: float+ radii: list[float]+ gains: list[float] # per region; 0 where it is held+ held: list[bool]+ ratios: list[float]+ moves: dict[float, tuple[np.ndarray, np.ndarray]] # per gain a region moves by, the offset per cell: across, down+ reaches: dict[float, float]+ gain: float # the largest any region moves by; dx, dy and reach are that gain's+ dx: np.ndarray+ dy: np.ndarray+ reach: float+ groups: list[tuple[list[tuple[float, float, float, float]], tuple[np.ndarray, np.ndarray]]]++ def carry(self, k: int) -> tuple[float, float]:+ """How far cell k's body lies from cell 0's, across and down: every region's ellipse is carried by it."""+ return self.cols[k] - self.cols[0], self.rows[k] - self.rows[0]++ def moves_in(self, k: int) -> list[tuple[list[tuple[float, float, float, float]], tuple[float, float]]]:+ """Cell k's groups of regions, each with its offset in that cell."""+ return [(group, (mx[k], my[k])) for group, (mx, my) in self.groups]++ def moved(self, k: int) -> Image.Image:+ return move_regions(self.cells[k], self.moves_in(k), self.carry(k))++ def record(self) -> dict[str, Any]:+ """The follow-through as the strip's meta records it; `video-follow` adds its animations' checks."""+ request, requested = self.request, self.requested+ return {+ "regions": [list(r) for r in request.regions], "gain": self.gain, "freq_hz": request.freq, "zeta": request.zeta,+ "harmonics": HARMONICS,+ "source": SOURCE, "body_px": self.height0, "body_worn_px": self.worn,+ "body_bob_px": [round(float(np.ptp(self.cols)), 2), round(float(np.ptp(self.rows)), 2)],+ "dx_px": np.round(self.dx, 2).tolist(), "dy_px": np.round(self.dy, 2).tolist(),+ "reach_px": round(self.reach, 2),+ "gain_requested": requested, "on_fold": request.on_fold,+ "fold": {+ "lowered": any(g != requested for g in self.gains), "ratio": round(max(self.ratios), 3),+ "reach_requested_px": round(self.reach_requested, 2), "reach_per_gain_px": round(self.reach_per_gain, 3),+ # Where the regions took gains of their own, each says the gain it moved by and whether it+ # was held still (gain 0); where they all took one, the strip's `gain` is every region's.+ "regions": [{"radius_px": radius, "ratio": round(ratio, 3),+ "gain_limit": None if (limit := gain_limit(self.reach_per_gain, radius)) is None else round(limit, 3)}+ | ({} if len(set(self.gains)) == 1 else {"gain": g, "held": hold})+ for radius, ratio, g, hold in zip(self.radii, self.ratios, self.gains, self.held)],+ },+ }+++def solve(request: Request, strip: Image.Image, *, strip_name: str, verb: str = VERB) -> Answer:+ """The answer to `request` on `strip`, the loop's strip as cut (an RGBA picture; `strip_name` names its file+ in a refusal). Reads nothing else and writes nothing."""+ meta, regions = request.meta, request.regions+ gain, freq, zeta, on_fold = request.gain, request.freq, request.zeta, request.on_foldn, w, h = int(meta["frames"]), int(meta["w"]), int(meta["h"])if strip.size != (w * n, h):- raise SystemExit(f"video-follow: {source.name} is {strip.size[0]}x{strip.size[1]}, the strip meta says {w * n}x{h}; "+ raise SystemExit(f"{verb}: {strip_name} is {strip.size[0]}x{strip.size[1]}, the strip meta says {w * n}x{h}; ""cut the loop again (video-loop)")for cx, cy, rx, ry in regions:if not (0 <= cx < w and 0 <= cy < h):- raise SystemExit(f"video-follow: --region centre {cx:g},{cy:g} is outside the {w}x{h} cell")+ raise SystemExit(f"{verb}: --region centre {cx:g},{cy:g} is outside the {w}x{h} cell")cells = [strip.crop((k * w, 0, (k + 1) * w, h)) for k in range(n)]fps = 1000.0 / float(meta["delay_ms"])try:rows, cols, height0, worn = body_motion(cells)except ValueError as exc:- raise SystemExit(f"video-follow: {exc}") from exc+ raise SystemExit(f"{verb}: {exc}") from excdy = follow_offsets(rows, fps, freq=freq, zeta=zeta, gain=gain)dx = follow_offsets(cols, fps, freq=freq, zeta=zeta, gain=gain)reach = float(np.max(np.hypot(dx, dy)))@@ -368,7 +483,7 @@ def follow_loop(loop_dir: Path, regions: list[tuple[float, float, float, float]]gains, held = [requested] * len(regions), [False] * len(regions)if fold_ratio(reach, smallest) >= 1:if on_fold == "refuse":- raise SystemExit(f"video-follow: a move of {reach:.1f} px folds a region of radius {smallest:g} px over itself; "+ raise SystemExit(f"{verb}: a move of {reach:.1f} px folds a region of radius {smallest:g} px over itself; ""lower --gain or give the region larger radii")# A gain for each region: every part hangs on the same body and answers the same motion, but# how far it moves before it folds is its own size, so a small part (an ear) does not hold a@@ -381,7 +496,7 @@ def follow_loop(loop_dir: Path, regions: list[tuple[float, float, float, float]]if all(held):k = radii.index(max(radii)) # the largest folds at the largest gain: if it is held, every region isevery = f" (the largest of {len(regions)} regions: every one folds)" if len(regions) > 1 else ""- raise SystemExit(f"video-follow: a move of {reach:.1f} px folds a region of radius {radii[k]:g} px over itself{every}, and "+ raise SystemExit(f"{verb}: a move of {reach:.1f} px folds a region of radius {radii[k]:g} px over itself{every}, and "f"--on-fold lower would have to go under --gain {GAIN_MEASURED:g} (the mass as measured moves "f"{reach_per_gain:.1f} px; the largest gain that does not fold is {gains[k]:g}); give the region larger radii")gains = [0.0 if hold else g for g, hold in zip(gains, held)]@@ -395,8 +510,23 @@ def follow_loop(loop_dir: Path, regions: list[tuple[float, float, float, float]]reach = reaches[gain]ratios = [0.0 if hold else fold_ratio(reaches[g], radius) for radius, g, hold in zip(radii, gains, held)]groups = [([r for r, rg, hold in zip(regions, gains, held) if rg == g and not hold], move) for g, move in moves.items()]- out = [move_regions(c, [(group, (mx[k], my[k])) for group, (mx, my) in groups], (cols[k] - cols[0], rows[k] - rows[0]))- for k, c in enumerate(cells)]+ return Answer(request, cells, cols, rows, height0, worn, requested, reach_requested, reach_per_gain, radii, gains, held,+ ratios, moves, reaches, gain, dx, dy, reach, groups)+++def follow_loop(loop_dir: Path, regions: list[tuple[float, float, float, float]], *, gain: float = GAIN_DEFAULT,+ freq: float = FREQ_DEFAULT, zeta: float = ZETA_DEFAULT, board: Path | None = None,+ on_fold: str = "refuse") -> dict[str, Any]:+ request = read_request(loop_dir, regions, gain=gain, freq=freq, zeta=zeta, on_fold=on_fold)+ loop_dir, name, meta_path, meta = request.loop_dir, request.name, request.meta_path, request.meta+ strip_path = request.strip_path+ source = request.source_path+ if not source.exists():+ shutil.copyfile(strip_path, source)+ answer = solve(request, Image.open(source).convert("RGBA"), strip_name=source.name)+ cells = answer.cells+ n, (w, h) = len(cells), cells[0].size+ out = [answer.moved(k) for k in range(n)]joined = Image.new("RGBA", (w * n, h), (0, 0, 0, 0))for k, c in enumerate(out):joined.alpha_composite(c, (k * w, 0))@@ -413,22 +543,7 @@ def follow_loop(loop_dir: Path, regions: list[tuple[float, float, float, float]]save_clean_gif(out, staged[gif_path], duration_ms=delay_ms, loop=0, alpha_threshold=128)loop_mod.write_webp(out, staged[webp_path], delay_ms=delay_ms, workdir=stage / ".webp-frames")record = {- "regions": [list(r) for r in regions], "gain": gain, "freq_hz": freq, "zeta": zeta, "harmonics": HARMONICS,- "source": SOURCE, "body_px": height0, "body_worn_px": worn,- "body_bob_px": [round(float(np.ptp(cols)), 2), round(float(np.ptp(rows)), 2)],- "dx_px": np.round(dx, 2).tolist(), "dy_px": np.round(dy, 2).tolist(),- "reach_px": round(reach, 2),- "gain_requested": requested, "on_fold": on_fold,- "fold": {- "lowered": any(g != requested for g in gains), "ratio": round(max(ratios), 3),- "reach_requested_px": round(reach_requested, 2), "reach_per_gain_px": round(reach_per_gain, 3),- # Where the regions took gains of their own, each says the gain it moved by and whether it- # was held still (gain 0); where they all took one, the strip's `gain` is every region's.- "regions": [{"radius_px": radius, "ratio": round(ratio, 3),- "gain_limit": None if (limit := gain_limit(reach_per_gain, radius)) is None else round(limit, 3)}- | ({} if len(set(gains)) == 1 else {"gain": g, "held": hold})- for radius, ratio, g, hold in zip(radii, ratios, gains, held)],- },+ **answer.record(),"gif": loop_mod.verify_animation(staged[gif_path], expect_frames=n, check_stale=False),"webp": loop_mod.verify_animation(staged[webp_path], expect_frames=n, check_stale=True),}@@ -438,7 +553,7 @@ def follow_loop(loop_dir: Path, regions: list[tuple[float, float, float, float]]finally:shutil.rmtree(stage, ignore_errors=True)if board is not None:- _board(cells, out, dy, board)+ _board(cells, out, answer.dy, board)record["board"] = str(board)return {"strip": str(strip_path), **record}@@ -459,7 +574,8 @@ def _board(before: list[Image.Image], after: list[Image.Image], dy: np.ndarray,board.save(path)-def add_arguments(parser: argparse.ArgumentParser) -> None:+def add_request_arguments(parser: argparse.ArgumentParser) -> None:+ """What a follow-through is asked with; `video-follow-inspect` takes the same and is asked alike."""parser.add_argument("--loop-dir", required=True, type=Path, help="a video-loop output directory (after video-cycle-align, if the set is aligned)")parser.add_argument("--region", action="append", type=parse_region, required=True,help="cx,cy,rx,ry: an ellipse over the soft part in the strip's first cell, in cell pixels (repeatable)")@@ -470,9 +586,31 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:"named in the record, and the strip is refused only when every region is")parser.add_argument("--freq", type=float, default=FREQ_DEFAULT, help=f"the part's own frequency in Hz (default {FREQ_DEFAULT:g})")parser.add_argument("--zeta", type=float, default=ZETA_DEFAULT, help=f"damping ratio (default {ZETA_DEFAULT:g}: lags and settles, no ringing)")+++def add_arguments(parser: argparse.ArgumentParser) -> None:+ add_request_arguments(parser)parser.add_argument("--board", type=Path, help="write a before/after picture at the frames where the part sits lowest and highest")+def fold_notes(record: dict[str, Any], verb: str = VERB) -> list[str]:+ """What to say of a record whose gain was lowered or whose regions were held, a line each."""+ fold, notes = record["fold"], []+ if "held" in fold["regions"][0]: # the regions took gains of their own+ for (cx, cy, rx, ry), entry in zip(record["regions"], fold["regions"]):+ name = f"--region {cx:g},{cy:g},{rx:g},{ry:g}"+ if entry["held"]:+ notes.append(f"{verb}: {name} folds at --gain {entry['gain_limit']:g}, under {GAIN_MEASURED:g} (the mass as measured): "+ "it is held, and does not move")+ elif entry["gain"] != record["gain_requested"]:+ notes.append(f"{verb}: --gain {record['gain_requested']:g} folds {name} (a move of {fold['reach_requested_px']:g} px); "+ f"lowered to --gain {entry['gain']:g} for it")+ elif fold["lowered"]:+ notes.append(f"{verb}: --gain {record['gain_requested']:g} folds a region (a move of {fold['reach_requested_px']:g} px); "+ f"lowered to --gain {record['gain']:g}")+ return notes++def run(**kwargs: object) -> int:result = follow_loop(Path(str(kwargs["loop_dir"])), list(kwargs["region"]), # type: ignore[arg-type]gain=float(kwargs.get("gain", GAIN_DEFAULT)), freq=float(kwargs.get("freq", FREQ_DEFAULT)), # type: ignore[arg-type]@@ -480,18 +618,8 @@ def run(**kwargs: object) -> int:on_fold=str(kwargs.get("on_fold") or "refuse"))fold = result["fold"]own = "held" in fold["regions"][0] # the regions took gains of their own- if own:- for (cx, cy, rx, ry), entry in zip(result["regions"], fold["regions"]):- name = f"--region {cx:g},{cy:g},{rx:g},{ry:g}"- if entry["held"]:- print(f"video-follow: {name} folds at --gain {entry['gain_limit']:g}, under {GAIN_MEASURED:g} (the mass as measured): "- "it is held, and does not move", file=sys.stderr)- elif entry["gain"] != result["gain_requested"]:- print(f"video-follow: --gain {result['gain_requested']:g} folds {name} (a move of {fold['reach_requested_px']:g} px); "- f"lowered to --gain {entry['gain']:g} for it", file=sys.stderr)- elif fold["lowered"]:- print(f"video-follow: --gain {result['gain_requested']:g} folds a region (a move of {fold['reach_requested_px']:g} px); "- f"lowered to --gain {result['gain']:g}", file=sys.stderr)+ for note in fold_notes(result):+ print(note, file=sys.stderr)print(json.dumps({k: result[k] for k in ("strip", "regions", "gain", "gain_requested", "on_fold", "body_bob_px", "reach_px")}| ({"region_gains": [entry["gain"] for entry in fold["regions"]]} if own else {})| ({"board": result["board"]} if "board" in result else {}), ensure_ascii=False, indent=2))diff --git a/sprite_gen/video/follow_inspect.py b/sprite_gen/video/follow_inspect.pynew file mode 100644index 0000000..1e39a3a--- /dev/null+++ b/sprite_gen/video/follow_inspect.py@@ -0,0 +1,320 @@+# SPDX-License-Identifier: Apache-2.0+"""`sprite-gen video-follow-inspect` — where a follow-through carries its regions in every cell, with nothing moved.++`video-follow` is given an ellipse over a soft part in the strip's first cell and carries it with the body+into every other cell; inside the carried ellipse every pixel moves, whatever it is a picture of. For the+first cell somebody looked and said where the part is. For the others nobody did: an arm that swings across+a chest is inside the chest's ellipse in those cells, and moves with it. The engine does not read what a+pixel belongs to, and it does not guess it here either: every region is written `ownership: unknown` in+every cell, from its centre to its rim, the first cell included.++This command writes what somebody needs in order to look, and changes nothing. It takes what `video-follow`+takes, reads the loop as `video-follow` would (the strip as cut: `follow.source.png` where a follow-through+was already written, the strip itself where none was) and solves it with the same code (`follow.read_request`,+`follow.solve`). Into `--out-dir`, which is never the loop directory, it writes:++- `follow-inspect.json`, the record: what was read (the strip's and the meta's sha256, the regions, the+ settings, the engine and the way it reads, and `input_id`, one sha256 over those); the follow-through as+ `video-follow` would record it (`follow`); per cell how far the regions are carried (`carry_px`) and, per+ region, the carried ellipse, its offset, how near that is to folding it, the least area of the source a+ pixel of the moved cell takes (`jacobian_min`: 1 where nothing moves, 0 where the picture stops and one+ pixel of the source is drawn across many, under 0 where it would run backwards), how many pixels the+ ellipse covers and how many of them are body, and how many the move changes;+- `follow-inspect.source.png`, every cell of the strip as cut with each region's carried ellipse ringed;+- `follow-inspect.moved.png`, the same cells as `video-follow` would write them, ringed alike.++The two boards are apart so that whoever says what is inside an ellipse can read the cells as cut alone,+without the answer beside them. The record holds no path, no time and nothing of the machine: the same loop+asked the same way writes the same record. `input_id` does not change when `video-follow` is run on the loop+(it reads the strip as cut, and the meta without the `follow` record `video-follow` adds) and changes with+anything the answer is read from — a new cut, an alignment, a region, a setting, the engine. The boards'+`pixels_sha256` is over their pixels, so another PNG writer gives the same one; how the boards are drawn+(`--scale`, `--columns`) is no part of `input_id`. docs/video-pipeline.md section 6.+"""++from __future__ import annotations++import argparse+import hashlib+import io+import json+import math+import sys+from importlib.metadata import PackageNotFoundError, version as package_version+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_set+from sprite_gen.video import follow++VERB = "video-follow-inspect"+KIND = "video-follow-inspection"+SCHEMA_VERSION = 1+RECORD, SOURCE_BOARD, MOVED_BOARD = "follow-inspect.json", "follow-inspect.source.png", "follow-inspect.moved.png"+UNKNOWN = "unknown" # what is inside a carried ellipse: the engine does not read it+SCALE_DEFAULT = 2 # board pixels per cell pixel: at 2 or more a ring covers no cell pixel whole+COLUMNS_DEFAULT = 8+PLACES = 4 # decimals of the offsets, ratios and areas: under what two machines' FFTs differ by+GROUND = (128, 128, 128) # under a cell's clear pixels+BETWEEN = (32, 32, 32) # between the cells, and under their numbers+INK = (255, 255, 255) # a cell's number+DARK = (0, 0, 0) # every other dash of a ring, so it shows on any colour+RINGS = ((255, 235, 0), (0, 255, 255), (255, 96, 0), (0, 255, 96), (255, 0, 200), (120, 160, 255)) # by region; they repeat+DASH = 2 # board pixels of a ring in its colour, then as many dark+GAP = 6 # board pixels between cells+DOT = 3 # board pixels per dot of a digit+PAD = 3 # above and under a cell's number+DIGITS = {+ "0": ("###", "# #", "# #", "# #", "###"), "1": (" # ", "## ", " # ", " # ", "###"), "2": ("###", " #", "###", "# ", "###"),+ "3": ("###", " #", "###", " #", "###"), "4": ("# #", "# #", "###", " #", " #"), "5": ("###", "# ", "###", " #", "###"),+ "6": ("###", "# ", "###", "# #", "###"), "7": ("###", " #", " #", " #", " #"), "8": ("###", "# #", "###", "# #", "###"),+ "9": ("###", "# #", "###", " #", "###"),+}+++def _sha256(data: bytes) -> str:+ return hashlib.sha256(data).hexdigest()+++def _canonical(value: Any) -> bytes:+ """One spelling of a JSON value: keys sorted, no spaces, ASCII."""+ return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode("ascii")+++def _engine_version() -> str:+ try:+ return package_version("sprite-gen")+ except PackageNotFoundError: # pragma: no cover - bare checkout+ return "unknown"+++def policy() -> dict[str, Any]:+ """The way the motion is read and a region moved: its name and the numbers it is fixed by."""+ return {"name": follow.POLICY, "harmonics": follow.HARMONICS, "alpha_solid": follow.ALPHA_SOLID,+ "worn": [follow.WORN_FROM, follow.WORN_TO], "gain_measured": follow.GAIN_MEASURED, "gain_step": follow.GAIN_STEP,+ "weight": "cos2"}+++def jacobian(move_x: np.ndarray, move_y: np.ndarray) -> np.ndarray:+ """Per pixel of a moved cell, but for those on its edge, the area of the source it takes. The moved cell's+ pixel p is read from the source at p less its move, so the area is read between p's neighbours on either+ side, across and down, as half of how far apart those are read: 1 where nothing moves, 0 where the picture+ stops, under 0 where it runs backwards. Between the neighbours on either side, not from p to the next pixel+ one way: read one way, a round region a few pixels across reads steeper on the side it bulges to than its+ weight is anywhere. One row and one column shorter than the cell at each edge."""+ across_x, across_y = (move_x[1:-1, 2:] - move_x[1:-1, :-2]) / 2, (move_y[1:-1, 2:] - move_y[1:-1, :-2]) / 2+ down_x, down_y = (move_x[2:, 1:-1] - move_x[:-2, 1:-1]) / 2, (move_y[2:, 1:-1] - move_y[:-2, 1:-1]) / 2+ return (1 - across_x) * (1 - down_y) - down_x * across_y+++def _least(area: np.ndarray | None, mask: np.ndarray) -> tuple[float, list[int] | None]:+ """The least of `area` over the pixels of `mask`, and that pixel (x, y); 1 and no pixel where nothing moves+ there."""+ if area is None:+ return 1.0, None+ inner = mask[1:-1, 1:-1]+ if not inner.any():+ return 1.0, None+ values = np.where(inner, area, np.inf)+ y, x = divmod(int(np.argmin(values)), values.shape[1])+ return float(values[y, x]), [x + 1, y + 1]+++def _grown(mask: np.ndarray) -> np.ndarray:+ """`mask` and the pixels beside it: above, under, left and right."""+ grown = mask.copy()+ grown[1:] |= mask[:-1]+ grown[:-1] |= mask[1:]+ grown[:, 1:] |= mask[:, :-1]+ grown[:, :-1] |= mask[:, 1:]+ return grown+++def _tile(cell: Image.Image, masks: list[np.ndarray], scale: int) -> np.ndarray:+ """A cell on the board: over the ground, `scale` board pixels to a cell pixel, each region's ring drawn on the+ board pixels just outside its ellipse — inside an ellipse nothing is drawn but another region's ring."""+ ground = Image.new("RGBA", cell.size, (*GROUND, 255))+ ground.alpha_composite(cell)+ tile = np.repeat(np.repeat(np.asarray(ground.convert("RGB")), scale, axis=0), scale, axis=1)+ yy, xx = np.mgrid[0:tile.shape[0], 0:tile.shape[1]]+ lit = (xx + yy) // DASH % 2 == 0+ for i, mask in enumerate(masks):+ covered = np.repeat(np.repeat(mask, scale, axis=0), scale, axis=1)+ ring = _grown(covered) & ~covered+ tile[ring & lit] = RINGS[i % len(RINGS)]+ tile[ring & ~lit] = DARK+ return tile+++def _number(board: np.ndarray, text: str, x: int, y: int) -> None:+ for char in text:+ for row, dots in enumerate(DIGITS[char]):+ for col, dot in enumerate(dots):+ if dot == "#":+ board[y + row * DOT: y + (row + 1) * DOT, x + col * DOT: x + (col + 1) * DOT] = INK+ x += 4 * DOT+++def _boards(tiles: list[list[np.ndarray]], columns: int) -> tuple[list[np.ndarray], list[list[int]]]:+ """One board per list of tiles, all laid alike: the cells in order, `columns` to a row, each under its number+ (cell 0 first). With them, per cell, the box (x0, y0, x1, y1) its picture takes on every board."""+ n = len(tiles[0])+ tile_h, tile_w = tiles[0][0].shape[:2]+ label = 5 * DOT + 2 * PAD+ across, down = min(n, columns), math.ceil(n / columns)+ size = (GAP + down * (label + tile_h + GAP), GAP + across * (tile_w + GAP), 3)+ boards = [np.full(size, BETWEEN, np.uint8) for _ in tiles]+ boxes = []+ for k in range(n):+ x0 = GAP + (k % columns) * (tile_w + GAP)+ y0 = GAP + (k // columns) * (label + tile_h + GAP) + label+ boxes.append([x0, y0, x0 + tile_w, y0 + tile_h])+ for board, cells in zip(boards, tiles):+ _number(board, str(k), x0, y0 - label + PAD)+ board[y0: y0 + tile_h, x0: x0 + tile_w] = cells[k]+ return boards, boxes+++def _png(board: np.ndarray) -> bytes:+ data = io.BytesIO()+ Image.fromarray(board).save(data, format="PNG")+ return data.getvalue()+++def inspect_loop(loop_dir: Path, regions: list[tuple[float, float, float, float]], out_dir: Path, *,+ gain: float = follow.GAIN_DEFAULT, freq: float = follow.FREQ_DEFAULT, zeta: float = follow.ZETA_DEFAULT,+ on_fold: str = "refuse", scale: int = SCALE_DEFAULT, columns: int = COLUMNS_DEFAULT) -> dict[str, Any]:+ """The record of what `video-follow` asked the same way does to the loop, written with its two boards into+ `out_dir`. The loop directory is read and not written."""+ request = follow.read_request(loop_dir, regions, gain=gain, freq=freq, zeta=zeta, on_fold=on_fold, verb=VERB)+ out_dir = out_dir.expanduser().resolve()+ if out_dir == request.loop_dir or request.loop_dir in out_dir.parents:+ raise SystemExit(f"{VERB}: --out-dir {out_dir} is in the loop directory; an inspection writes nothing there")+ scale, columns = int(scale), int(columns)+ if scale < 1 or columns < 1:+ raise SystemExit(f"{VERB}: --scale and --columns must be 1 or more")+ # The strip as cut, as `video-follow` reads it; it keeps one beside the loop on its first run, and this does not.+ strip_path = request.source_path if request.source_path.exists() else request.strip_path+ strip_bytes = strip_path.read_bytes()+ answer = follow.solve(request, Image.open(io.BytesIO(strip_bytes)).convert("RGBA"), strip_name=strip_path.name, verb=VERB)+ n, (w, h) = len(answer.cells), answer.cells[0].size+ yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)+ cells, source_tiles, moved_tiles = [], [], []+ for k in range(n):+ carry = answer.carry(k)+ before, moved = np.asarray(answer.cells[k]), answer.moved(k)+ changed = (before != np.asarray(moved)).any(axis=-1)+ solid = before[..., 3] >= follow.ALPHA_SOLID+ field = follow.move_field(xx, yy, answer.moves_in(k), carry)+ area = None if field is None else jacobian(field[1], field[2])+ masks = [follow.region_weight(xx, yy, region, carry) > 0 for region in request.regions]+ entries = []+ for i, ((cx, cy, rx, ry), radius, g, hold, mask) in enumerate(zip(request.regions, answer.radii, answer.gains,+ answer.held, masks)):+ dx, dy = (0.0, 0.0) if hold else (float(answer.moves[g][0][k]), float(answer.moves[g][1][k]))+ least, at = _least(area, mask)+ entries.append({+ "index": i, "ellipse": [round(cx + float(carry[0]), 6), round(cy + float(carry[1]), 6), rx, ry],+ "offset_px": [round(dx, PLACES) + 0.0, round(dy, PLACES) + 0.0], "reach_px": round(math.hypot(dx, dy), PLACES),+ "fold_ratio": round(follow.fold_ratio(math.hypot(dx, dy), radius), PLACES),+ "jacobian_min": round(least, PLACES), "jacobian_min_at": at,+ "ellipse_px": int(mask.sum()), "solid_px": int((mask & solid).sum()), "changed_px": int((mask & changed).sum()),+ "ownership": UNKNOWN,+ })+ cells.append({+ "index": k, "carry_px": [float(carry[0]), float(carry[1])], "changed_px": int(changed.sum()),+ "jacobian_min": 1.0 if area is None or not area.size else round(float(area.min()), PLACES), "regions": entries,+ })+ source_tiles.append(_tile(answer.cells[k], masks, scale))+ moved_tiles.append(_tile(moved, masks, scale))+ (source_board, moved_board), boxes = _boards([source_tiles, moved_tiles], columns)+ for cell, box in zip(cells, boxes):+ cell["box"] = box+ source_png, moved_png = _png(source_board), _png(moved_board)++ meta = request.meta+ cut_sha256 = _sha256(_canonical({key: value for key, value in meta.items() if key != "follow"}))+ inputs = {+ "strip": {"file": strip_path.name, "sha256": _sha256(strip_bytes), "bytes": len(strip_bytes)},+ # `sha256` is the file's as read; `cut_sha256` is the meta's without the `follow` record `video-follow`+ # adds (one spelling: keys sorted, no spaces), so it is the same before and after a follow-through.+ "meta": {"file": request.meta_path.name, "sha256": _sha256(request.meta_bytes), "bytes": len(request.meta_bytes),+ "cut_sha256": cut_sha256, "follow_recorded": "follow" in meta},+ "cut": {"frames": n, "w": w, "h": h, "delay_ms": float(meta["delay_ms"])},+ "regions": [list(region) for region in request.regions],+ "settings": {"gain": request.gain, "on_fold": request.on_fold, "freq_hz": request.freq, "zeta": request.zeta},+ "policy": policy(),+ "engine": {"name": "sprite-gen", "version": _engine_version()},+ }+ input_id = _sha256(_canonical({+ "schema_version": SCHEMA_VERSION, "engine": inputs["engine"], "policy": inputs["policy"],+ "strip_sha256": inputs["strip"]["sha256"], "cut_sha256": cut_sha256,+ "regions": inputs["regions"], "settings": inputs["settings"],+ }))+ record = {+ "kind": KIND, "schema_version": SCHEMA_VERSION, "input_id": input_id, "inputs": inputs,+ "follow": answer.record(),+ "regions": [{+ "index": i, "ellipse": list(region), "radius_px": radius, "gain": g, "held": hold,+ "gain_limit": None if (limit := follow.gain_limit(answer.reach_per_gain, radius)) is None else round(limit, 3),+ "reach_px": max(cell["regions"][i]["reach_px"] for cell in cells),+ "fold_ratio": max(cell["regions"][i]["fold_ratio"] for cell in cells),+ "jacobian_min": min(cell["regions"][i]["jacobian_min"] for cell in cells),+ "changed_px": sum(cell["regions"][i]["changed_px"] for cell in cells),+ "ring": list(RINGS[i % len(RINGS)]),+ } for i, (region, radius, g, hold) in enumerate(zip(request.regions, answer.radii, answer.gains, answer.held))],+ "cells": cells,+ "boards": {+ "scale": scale, "columns": columns, "size": [int(source_board.shape[1]), int(source_board.shape[0])],+ "ground": list(GROUND),+ "source": {"file": SOURCE_BOARD, "sha256": _sha256(source_png), "pixels_sha256": _sha256(source_board.tobytes())},+ "moved": {"file": MOVED_BOARD, "sha256": _sha256(moved_png), "pixels_sha256": _sha256(moved_board.tobytes())},+ },+ }+ out_dir.mkdir(parents=True, exist_ok=True)+ # The boards and the record that names them, together: a run that fails on the way leaves `out_dir` as it was.+ atomic_write_set({out_dir / SOURCE_BOARD: source_png, out_dir / MOVED_BOARD: moved_png,+ out_dir / RECORD: json.dumps(record, ensure_ascii=False, indent=2) + "\n"})+ return record+++def add_arguments(parser: argparse.ArgumentParser) -> None:+ follow.add_request_arguments(parser)+ parser.add_argument("--out-dir", required=True, type=Path,+ help=f"where {RECORD}, {SOURCE_BOARD} and {MOVED_BOARD} are written; not the loop directory, which is only read")+ parser.add_argument("--scale", type=int, default=SCALE_DEFAULT,+ help=f"board pixels per cell pixel (default {SCALE_DEFAULT}; at 2 or more a ring covers no cell pixel whole)")+ parser.add_argument("--columns", type=int, default=COLUMNS_DEFAULT, help=f"cells per row of a board (default {COLUMNS_DEFAULT})")+++def run(**kwargs: object) -> int:+ out_dir = Path(str(kwargs["out_dir"]))+ record = inspect_loop(Path(str(kwargs["loop_dir"])), list(kwargs["region"]), out_dir, # type: ignore[arg-type]+ gain=float(kwargs.get("gain", follow.GAIN_DEFAULT)), freq=float(kwargs.get("freq", follow.FREQ_DEFAULT)), # type: ignore[arg-type]+ zeta=float(kwargs.get("zeta", follow.ZETA_DEFAULT)), on_fold=str(kwargs.get("on_fold") or "refuse"), # type: ignore[arg-type]+ scale=int(kwargs.get("scale", SCALE_DEFAULT)), columns=int(kwargs.get("columns", COLUMNS_DEFAULT))) # type: ignore[call-overload]+ for note in follow.fold_notes(record["follow"], VERB):+ print(note, file=sys.stderr)+ out_dir = out_dir.expanduser().resolve()+ print(json.dumps({+ "record": str(out_dir / RECORD), "input_id": record["input_id"], "cells": len(record["cells"]),+ "region_gains": [region["gain"] for region in record["regions"]],+ "held": [region["index"] for region in record["regions"] if region["held"]],+ "ownership": UNKNOWN,+ "boards": {name: {"path": str(out_dir / record["boards"][name]["file"]), "pixels_sha256": record["boards"][name]["pixels_sha256"]}+ for name in ("source", "moved")},+ }, ensure_ascii=False, indent=2))+ return 0+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(prog="sprite-gen video-follow-inspect", description=__doc__)+ add_arguments(parser)+ return run(**vars(parser.parse_args(argv)))+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/video/test_follow_inspect.py b/tests/video/test_follow_inspect.pynew file mode 100644index 0000000..6422fb8--- /dev/null+++ b/tests/video/test_follow_inspect.py@@ -0,0 +1,448 @@+"""`video-follow-inspect`: where a follow-through carries its regions in every cell, on a synthetic figure."""+import argparse+import hashlib+import json+import math++import numpy as np+import pytest+from PIL import Image, ImageDraw+from sprite_gen import cli+from sprite_gen.video import follow, follow_inspect++W, H, N = 120, 160, 24+HEAD, TORSO, PART, LEG = (210, 150, 60, 255), (20, 90, 180, 255), (230, 90, 120, 255), (240, 200, 40, 255)+CHEST = (60.0, 72.0, 18.0, 16.0) # over the soft part, as `figure` draws it in cell 0+GROUND = (128, 128, 128, 255)+FILES = ('follow-inspect.json', 'follow-inspect.source.png', 'follow-inspect.moved.png')+++def sway(k, n=N):+ """How far cell k's body is drawn from cell 0's, across and down, in whole pixels: once a cycle from side to+ side, twice up and down."""+ return round(3*math.sin(2*math.pi*k/n)), round(4*math.sin(4*math.pi*k/n))+++def figure(k, n=N, arm=None, speck=None):+ """A body from the front: a head and a torso that sway as one, a soft part on the chest, thin legs to the+ ground. In the cells `arm` (first, last) a forearm of the torso's own colour lies across the chest, out past+ both sides. `speck` is a cell that has one more pixel in its corner."""+ sx, sy = sway(k, n)+ im = Image.new('RGBA', (W, H))+ d = ImageDraw.Draw(im)+ d.rectangle((45+sx, 20+sy, 75+sx, 45+sy), fill=HEAD)+ d.rectangle((35+sx, 46+sy, 85+sx, 110+sy), fill=TORSO)+ d.ellipse((46+sx, 60+sy, 74+sx, 84+sy), fill=PART)+ d.rectangle((44+sx, 111+sy, 50+sx, 150), fill=LEG)+ d.rectangle((70+sx, 111+sy, 76+sx, 150), fill=LEG)+ if arm and arm[0] <= k <= arm[1]:+ d.rectangle((25+sx, 68+sy, 95+sx, 74+sy), fill=TORSO)+ if k == speck:+ d.point((2, 2), fill=(255, 255, 255, 255))+ return im+++def strip_dir(path, draw=figure, n=N, **meta):+ """A loop directory holding one cycle of `draw(k)` as a strip, as video-loop leaves one."""+ strip = Image.new('RGBA', (W*n, H))+ for k in range(n):+ strip.paste(draw(k), (k*W, 0))+ path.mkdir()+ strip.save(path/'walk.strip.png')+ (path/'walk.strip.json').write_text(json.dumps({'kind': 'periodic', 'frames': n, 'w': W, 'h': H, 'delay_ms': 1000/24} | meta))+ return path+++def snapshot(path):+ """Everything in a directory: each name with its bytes and the time it was last written, and the directory's own."""+ inside = {str(p.relative_to(path)): (p.read_bytes() if p.is_file() else None, p.stat().st_mtime_ns) for p in sorted(path.rglob('*'))}+ return inside | {'.': (None, path.stat().st_mtime_ns)}+++def inspect(loop_dir, regions, out, **kw):+ """The record of an inspection, as written."""+ returned = follow_inspect.inspect_loop(loop_dir, regions, out, **kw)+ assert sorted(p.name for p in out.iterdir()) == sorted(FILES)+ record = json.loads((out/FILES[0]).read_text())+ assert record == returned+ return record+++def cells(path):+ strip = np.asarray(Image.open(path).convert('RGBA'))+ return [np.ascontiguousarray(strip[:, k*W:(k+1)*W]) for k in range(strip.shape[1]//W)]+++def picture(path):+ return np.asarray(Image.open(path).convert('RGB'))+++def tiles(out, record, name):+ """A board's cells, each cut out at the box the record gives it."""+ board = picture(out/record['boards'][name]['file'])+ assert hashlib.sha256(board.tobytes()).hexdigest() == record['boards'][name]['pixels_sha256']+ assert hashlib.sha256((out/record['boards'][name]['file']).read_bytes()).hexdigest() == record['boards'][name]['sha256']+ assert [board.shape[1], board.shape[0]] == record['boards']['size']+ return [board[y0:y1, x0:x1] for x0, y0, x1, y1 in (cell['box'] for cell in record['cells'])]+++def covered(ellipse):+ """The cell's pixels inside an ellipse cx, cy, rx, ry."""+ cx, cy, rx, ry = ellipse+ yy, xx = np.mgrid[0:H, 0:W]+ return np.sqrt(((xx-cx)/rx)**2+((yy-cy)/ry)**2) < 1+++def grown(mask):+ out = mask.copy()+ out[1:] |= mask[:-1]+ out[:-1] |= mask[1:]+ out[:, 1:] |= mask[:, :-1]+ out[:, :-1] |= mask[:, 1:]+ return out+++def enlarged(a, scale):+ return np.repeat(np.repeat(a, scale, axis=0), scale, axis=1)+++def on_ground(cell):+ ground = Image.new('RGBA', (W, H), GROUND)+ ground.alpha_composite(Image.fromarray(cell))+ return np.asarray(ground.convert('RGB'))+++def unit(tmp_path):+ """How far the figure's soft part moves at gain 1, px."""+ return inspect(strip_dir(tmp_path/'unit'), [CHEST], tmp_path/'unit-out')['follow']['fold']['reach_per_gain_px']+++def folding_at(limit, reach_per_gain):+ """The radius of a region that folds at the gain `limit`."""+ return limit*reach_per_gain*math.pi/2+++def test_the_loop_directory_is_read_and_not_written(tmp_path):+ loop_dir = strip_dir(tmp_path/'loop')+ as_cut = snapshot(loop_dir)+ record = inspect(loop_dir, [CHEST], tmp_path/'out')+ # Not the strip, not its meta, and not the copy of the strip video-follow keeps beside the loop on its first run.+ assert snapshot(loop_dir) == as_cut and not (loop_dir/follow.SOURCE).exists()+ assert record['inputs']['strip']['file'] == 'walk.strip.png' and record['inputs']['meta']['follow_recorded'] is False+ follow.follow_loop(loop_dir, [CHEST])+ followed = snapshot(loop_dir)+ again = inspect(loop_dir, [CHEST], tmp_path/'again')+ assert snapshot(loop_dir) == followed+ assert again['inputs']['strip']['file'] == follow.SOURCE and again['inputs']['meta']['follow_recorded'] is True+ # Nothing of an inspection goes into the loop directory, or under it.+ for inside in (loop_dir, loop_dir/'inspect'/'deep'):+ with pytest.raises(SystemExit, match=r'^video-follow-inspect: --out-dir .* is in the loop directory; an inspection writes nothing there$'):+ follow_inspect.inspect_loop(loop_dir, [CHEST], inside)+ assert snapshot(loop_dir) == followed+++def test_inspecting_first_changes_nothing_video_follow_writes(tmp_path):+ inspected, plain = strip_dir(tmp_path/'inspected'), strip_dir(tmp_path/'plain')+ inspect(inspected, [CHEST], tmp_path/'out', on_fold='lower')+ for loop_dir in (inspected, plain):+ follow.follow_loop(loop_dir, [CHEST], on_fold='lower')+ names = ['follow.source.png', 'walk.gif', 'walk.strip.json', 'walk.strip.png', 'walk.webp']+ assert sorted(p.name for p in inspected.iterdir()) == sorted(p.name for p in plain.iterdir()) == names+ for name in names:+ assert (inspected/name).read_bytes() == (plain/name).read_bytes(), name+++def test_carry_is_the_bodys_own_motion_in_every_cell(tmp_path):+ record = inspect(strip_dir(tmp_path/'loop'), [CHEST], tmp_path/'out')+ assert [cell['index'] for cell in record['cells']] == list(range(N))+ assert record['inputs']['cut'] == {'frames': N, 'w': W, 'h': H, 'delay_ms': 1000/24}+ across, down = zip(*(sway(k) for k in range(N)))+ assert max(across) > 0 > min(across) and max(down) > 0 > min(down) and across != down+ for k, cell in enumerate(record['cells']):+ # Across and down, as drawn: the two are different motions, so one read as the other fails here.+ assert cell['carry_px'] == [across[k], down[k]], k+ (entry,) = cell['regions']+ assert entry['index'] == 0 and entry['ellipse'] == [CHEST[0]+across[k], CHEST[1]+down[k], CHEST[2], CHEST[3]], k+ assert record['follow']['body_bob_px'] == [max(across)-min(across), max(down)-min(down)]+ # The offsets are the strip's own, to more places than its record keeps.+ assert [cell['regions'][0]['offset_px'][0] for cell in record['cells']] == pytest.approx(record['follow']['dx_px'], abs=0.0051)+ assert [cell['regions'][0]['offset_px'][1] for cell in record['cells']] == pytest.approx(record['follow']['dy_px'], abs=0.0051)+ assert record['regions'][0]['reach_px'] == pytest.approx(record['follow']['reach_px'], abs=0.006)+++def test_the_record_is_what_video_follow_then_writes(tmp_path):+ loop_dir, out = strip_dir(tmp_path/'loop'), tmp_path/'out'+ record = inspect(loop_dir, [CHEST], out, on_fold='lower')+ follow.follow_loop(loop_dir, [CHEST], on_fold='lower')+ written = json.loads((loop_dir/'walk.strip.json').read_text())['follow']+ assert record['follow'] == {key: value for key, value in written.items() if key not in ('gif', 'webp')}+ source, moved = cells(loop_dir/follow.SOURCE), cells(loop_dir/'walk.strip.png')+ changed = [(a != b).any(axis=-1) for a, b in zip(source, moved)]+ assert sum(int(c.sum()) for c in changed) == record['regions'][0]['changed_px'] > 0+ scale = record['boards']['scale']+ boards = [(tiles(out, record, 'source'), source), (tiles(out, record, 'moved'), moved)]+ for k, cell in enumerate(record['cells']):+ (entry,) = cell['regions']+ inside = covered(entry['ellipse'])+ # The carried ellipse the record gives holds every pixel video-follow changed in the cell.+ assert not (changed[k] & ~inside).any(), k+ assert cell['changed_px'] == entry['changed_px'] == int(changed[k].sum()), k+ assert entry['ellipse_px'] == int(inside.sum()) and entry['solid_px'] == int((inside & (source[k][..., 3] >= 128)).sum()), k+ for shown, strip in boards:+ # The cell at its box, over the ground, as cut on one board and as video-follow wrote it on the other;+ # the ring is on the board pixels just outside the ellipse, and inside it the cell shows whole.+ assert shown[k].shape[:2] == (H*scale, W*scale)+ ring = (shown[k] != enlarged(on_ground(strip[k]), scale)).any(axis=-1)+ within = enlarged(inside, scale)+ assert ring.any() and not (ring & ~(grown(within) & ~within)).any(), k+ assert {tuple(int(v) for v in colour) for colour in shown[k][ring]} <= {tuple(record['regions'][0]['ring']), (0, 0, 0)}, k+++def test_each_region_has_its_gain_and_one_held_is_still_carried(tmp_path):+ reach = unit(tmp_path)+ crown = (66.0, 20.0, folding_at(1.755, reach), folding_at(1.755, reach)) # on the head's top edge; folds under the default gain+ ear = (45.0, 32.0, folding_at(0.755, reach), folding_at(0.755, reach)) # folds under gain 1: too small to move+ regions = [CHEST, crown, ear]+ loop_dir, out = strip_dir(tmp_path/'loop'), tmp_path/'out'+ record = inspect(loop_dir, regions, out, on_fold='lower')+ large, small, held = record['regions']+ assert [region['index'] for region in record['regions']] == [0, 1, 2]+ assert [region['ellipse'] for region in record['regions']] == [list(region) for region in regions]+ assert large['gain'] == follow.GAIN_DEFAULT > small['gain'] >= follow.GAIN_MEASURED and large['held'] is small['held'] is False+ assert 0.99 <= small['fold_ratio'] < 1 and 0 < small['jacobian_min'] < large['jacobian_min'] < 1+ assert held['held'] is True and (held['gain'], held['reach_px'], held['fold_ratio'], held['changed_px']) == (0, 0, 0, 0)+ assert held['gain_limit'] < follow.GAIN_MEASURED <= small['gain'] < small['gain_limit'] < follow.GAIN_DEFAULT < large['gain_limit']+ assert small['changed_px'] > 0 and large['changed_px'] > 0+ assert len({tuple(region['ring']) for region in record['regions']}) == 3+ source = tiles(out, record, 'source')+ for k, cell in enumerate(record['cells']):+ sx, sy = sway(k)+ assert [entry['index'] for entry in cell['regions']] == [0, 1, 2]+ for entry, (cx, cy, rx, ry) in zip(cell['regions'], regions):+ assert entry['ellipse'] == [cx+sx, cy+sy, rx, ry], k+ chest, top, still = cell['regions']+ # One motion, each region by its own gain; the held one by none, and ringed where it is carried all the same.+ assert top['offset_px'] == pytest.approx([v*small['gain']/large['gain'] for v in chest['offset_px']], abs=2e-4)+ assert still['offset_px'] == [0, 0] and still['changed_px'] == 0 and still['jacobian_min'] == 1+ assert cell['changed_px'] == chest['changed_px']+top['changed_px']+ assert cell['jacobian_min'] == min(chest['jacobian_min'], top['jacobian_min'])+ assert (source[k] == held['ring']).all(axis=-1).any(), k+ follow.follow_loop(loop_dir, regions, on_fold='lower')+ written = json.loads((loop_dir/'walk.strip.json').read_text())['follow']+ assert record['follow'] == {key: value for key, value in written.items() if key not in ('gif', 'webp')}+ assert [entry['held'] for entry in written['fold']['regions']] == [False, False, True]+ changed = [(a != b).any(axis=-1) for a, b in zip(cells(loop_dir/follow.SOURCE), cells(loop_dir/'walk.strip.png'))]+ assert [int(c.sum()) for c in changed] == [cell['changed_px'] for cell in record['cells']]+++def test_regions_are_recorded_in_the_order_given_and_cells_in_the_strips(tmp_path):+ reach = unit(tmp_path)+ crown = (66.0, 20.0, folding_at(1.755, reach), folding_at(1.755, reach))+ loop_dir = strip_dir(tmp_path/'loop')+ one = inspect(loop_dir, [CHEST, crown], tmp_path/'one', on_fold='lower')+ other = inspect(loop_dir, [crown, CHEST], tmp_path/'other', on_fold='lower')+ assert one['input_id'] != other['input_id']+ without = lambda entry: {key: value for key, value in entry.items() if key not in ('index', 'ring')}+ # A region's numbers are its own wherever it is given; its index and its ring's colour are its place.+ assert [without(region) for region in one['regions']] == [without(region) for region in reversed(other['regions'])]+ assert [region['ring'] for region in one['regions']] == [region['ring'] for region in other['regions']]+ for a, b in zip(one['cells'], other['cells']):+ assert [without(entry) for entry in a['regions']] == [without(entry) for entry in reversed(b['regions'])]+ assert (a['index'], a['carry_px'], a['changed_px'], a['box']) == (b['index'], b['carry_px'], b['changed_px'], b['box'])+ # Each box holds its own cell of the strip and no other's: every cell is drawn differently here.+ strip = [on_ground(cell) for cell in cells(loop_dir/'walk.strip.png')]+ scale = one['boards']['scale']+ for k, shown in enumerate(tiles(tmp_path/'one', one, 'source')):+ match = [float((shown == enlarged(cell, scale)).all(axis=-1).mean()) for cell in strip]+ assert match[k] > 0.97 and all(m < match[k] for j, m in enumerate(match) if sway(j) != sway(k)), k+ boxes = [cell['box'] for cell in one['cells']]+ assert len({tuple(box) for box in boxes}) == N and boxes[0][0] < boxes[1][0] and boxes[0][1] == boxes[1][1] < boxes[one['boards']['columns']][1]+++def test_what_was_read_names_the_evidence_and_another_cut_is_another(tmp_path):+ loop_dir = strip_dir(tmp_path/'loop')+ first = inspect(loop_dir, [CHEST], tmp_path/'a')+ # No path, no time: the same loop asked the same way writes the same three files anywhere.+ inspect(loop_dir, [CHEST], tmp_path/'b')+ for name in FILES:+ assert (tmp_path/'a'/name).read_bytes() == (tmp_path/'b'/name).read_bytes(), name+ assert str(tmp_path) not in (tmp_path/'a'/FILES[0]).read_text()+ assert first['inputs']['strip']['sha256'] == hashlib.sha256((loop_dir/'walk.strip.png').read_bytes()).hexdigest()+ assert first['inputs']['meta']['sha256'] == hashlib.sha256((loop_dir/'walk.strip.json').read_bytes()).hexdigest()+ # video-follow moves the strip and records itself in the meta; what it was read from is the same cut.+ follow.follow_loop(loop_dir, [CHEST])+ followed = inspect(loop_dir, [CHEST], tmp_path/'c')+ assert followed['input_id'] == first['input_id']+ assert followed['inputs']['strip']['sha256'] == first['inputs']['strip']['sha256']+ assert followed['inputs']['meta']['sha256'] != first['inputs']['meta']['sha256']+ assert followed['inputs']['meta']['cut_sha256'] == first['inputs']['meta']['cut_sha256']+ assert (followed['cells'], followed['regions'], followed['follow'], followed['boards']) == (first['cells'], first['regions'], first['follow'], first['boards'])+ # Another cut, another id: the cycle turned to start one cell on (an alignment); one pixel of one cell;+ # the cut's own record with another delay, or with any other key changed.+ turned = inspect(strip_dir(tmp_path/'turned', lambda k: figure((k+1) % N)), [CHEST], tmp_path/'d')+ specked = inspect(strip_dir(tmp_path/'specked', lambda k: figure(k, speck=5)), [CHEST], tmp_path/'e')+ slower = inspect(strip_dir(tmp_path/'slower', delay_ms=50), [CHEST], tmp_path/'f')+ noted = inspect(strip_dir(tmp_path/'noted', cycle_frames=N), [CHEST], tmp_path/'g')+ assert len({r['input_id'] for r in (first, turned, specked, slower, noted)}) == 5+ assert len({r['inputs']['strip']['sha256'] for r in (first, turned, specked)}) == 3+ # One pixel in a corner moves no body: the same carry and offsets, and still not the cut the evidence was read on.+ assert [cell['carry_px'] for cell in specked['cells']] == [cell['carry_px'] for cell in first['cells']]+ assert specked['follow'] == first['follow'] and specked['boards']['source']['pixels_sha256'] != first['boards']['source']['pixels_sha256']+ for meta_only in (slower, noted):+ assert meta_only['inputs']['strip']['sha256'] == first['inputs']['strip']['sha256']+ assert meta_only['inputs']['meta']['cut_sha256'] != first['inputs']['meta']['cut_sha256']+ assert noted['cells'] == first['cells'] and slower['follow']['dy_px'] != first['follow']['dy_px']+++def test_what_the_answer_is_asked_with_is_in_the_id_and_how_the_boards_are_drawn_is_not(tmp_path):+ loop_dir = strip_dir(tmp_path/'loop')+ base = inspect(loop_dir, [CHEST], tmp_path/'base')+ asked = [dict(gain=2.0), dict(freq=2.5), dict(zeta=0.5), dict(on_fold='lower')]+ regions = [(61.0, 72.0, 18.0, 16.0), (60.0, 71.0, 18.0, 16.0), (60.0, 72.0, 17.0, 16.0), (60.0, 72.0, 18.0, 15.0), CHEST+CHEST]+ others = [inspect(loop_dir, [CHEST], tmp_path/f'asked-{i}', **kw) for i, kw in enumerate(asked)]+ others += [inspect(loop_dir, [r[:4], r[4:]] if len(r) == 8 else [r], tmp_path/f'region-{i}') for i, r in enumerate(regions)]+ assert len({record['input_id'] for record in (base, *others)}) == 1+len(asked)+len(regions)+ # Asked to lower where nothing folds: every number and both boards as before, under another id.+ lower = others[3]+ assert (lower['cells'], lower['regions'], lower['boards']) == (base['cells'], base['regions'], base['boards'])+ assert lower['inputs']['settings'] == base['inputs']['settings'] | {'on_fold': 'lower'}+ assert base['inputs']['settings'] == {'gain': 2.5, 'on_fold': 'refuse', 'freq_hz': 2.4, 'zeta': 0.6}+ assert base['inputs']['policy'] == {'name': follow.POLICY, 'harmonics': 6, 'alpha_solid': 128, 'worn': [0.25, 0.5],+ 'gain_measured': 1.0, 'gain_step': 0.01, 'weight': 'cos2'}+ # Numbers from a caller are read as the command line's.+ for kind in (np.int64, np.float32, int):+ given = follow_inspect.inspect_loop(loop_dir, np.asarray([CHEST], dtype=kind), tmp_path/f'kind-{kind.__name__}', gain=kind(2.5) if kind is np.float32 else 2.5)+ assert given == base, kind+ # Drawn larger and five to a row: other boards and boxes, the same id and the same numbers.+ drawn = inspect(loop_dir, [CHEST], tmp_path/'drawn', scale=3, columns=5)+ unboxed = lambda record: [{key: value for key, value in cell.items() if key != 'box'} for cell in record['cells']]+ assert (drawn['input_id'], drawn['inputs'], drawn['follow'], drawn['regions'], unboxed(drawn)) == (+ base['input_id'], base['inputs'], base['follow'], base['regions'], unboxed(base))+ assert (drawn['boards']['scale'], drawn['boards']['columns']) == (3, 5) != (base['boards']['scale'], base['boards']['columns'])+ assert drawn['boards']['source']['pixels_sha256'] != base['boards']['source']['pixels_sha256']+ assert all(shown.shape[:2] == (H*3, W*3) for shown in tiles(tmp_path/'drawn', drawn, 'source'))+ assert drawn['cells'][5]['box'][1] > drawn['cells'][4]['box'][1] == drawn['cells'][0]['box'][1]+ for bad in (dict(scale=0), dict(columns=0)):+ with pytest.raises(SystemExit, match=r'^video-follow-inspect: --scale and --columns must be 1 or more$'):+ follow_inspect.inspect_loop(loop_dir, [CHEST], tmp_path/'bad', **bad)+ assert not (tmp_path/'bad').exists()+++def test_what_video_follow_refuses_the_inspection_refuses_and_writes_nothing(tmp_path):+ loop_dir, out = strip_dir(tmp_path/'loop'), tmp_path/'out'+ as_cut = snapshot(loop_dir)+ reach = unit(tmp_path)+ tiny = (60.0, 72.0, folding_at(0.755, reach), folding_at(0.755, reach))+ refusals = [+ (dict(regions=[(60.0, 72.0, 2.0, 2.0)], gain=50), r'a move of \d+\.\d px folds a region of radius 2 px over itself; lower --gain or give the region larger radii'),+ (dict(regions=[tiny], on_fold='lower'), r'a move of \d+\.\d px folds a region of radius [\d.]+ px over itself, and --on-fold lower would have to go under --gain 1 .*'),+ (dict(regions=[(999.0, 72.0, 5.0, 5.0)]), r'--region centre 999,72 is outside the 120x160 cell'),+ (dict(regions=[]), r'at least one --region cx,cy,rx,ry'),+ (dict(regions=[CHEST], on_fold='quietly'), r"unknown --on-fold 'quietly'; expected one of refuse, lower"),+ ]+ for i, (kw, why) in enumerate(refusals):+ regions = kw.pop('regions')+ with pytest.raises(SystemExit, match=rf'^video-follow-inspect: {why}$') as refused:+ follow_inspect.inspect_loop(loop_dir, regions, out, **kw)+ assert not out.exists() and snapshot(loop_dir) == as_cut+ # video-follow refuses the same request in the same words, under its own name.+ with pytest.raises(SystemExit) as followed:+ follow.follow_loop(strip_dir(tmp_path/f'follow-{i}'), regions, **kw)+ assert str(followed.value) == str(refused.value).replace('video-follow-inspect:', 'video-follow:', 1)+ with pytest.raises(SystemExit, match=r"^video-follow-inspect: a one-shot plays once; the follow-through is a loop's steady state$"):+ follow_inspect.inspect_loop(strip_dir(tmp_path/'once', kind='one-shot'), [CHEST], out)+ with pytest.raises(SystemExit, match=r'^video-follow-inspect: walk\.strip\.png is 2880x160, the strip meta says 2760x160; cut the loop again \(video-loop\)$'):+ follow_inspect.inspect_loop(strip_dir(tmp_path/'short', frames=N-1), [CHEST], out)+ with pytest.raises(SystemExit, match=r'^video-follow-inspect: .*: expected one <name>\.strip\.json from video-loop, found 0$'):+ follow_inspect.inspect_loop(tmp_path, [CHEST], out)+ assert not out.exists()+++def test_the_least_area_says_how_near_the_picture_is_to_stopping(tmp_path):+ loop_dir = strip_dir(tmp_path/'loop')+ record = inspect(loop_dir, [CHEST], tmp_path/'out')+ assert record['follow']['fold']['lowered'] is False and 0 < record['regions'][0]['jacobian_min'] < 1+ moving = 0+ for cell in record['cells']:+ (entry,) = cell['regions']+ dx, dy = entry['offset_px']+ # On an ellipse the weight falls fastest half way out, along the move: there a pixel of the moved cell+ # takes this much of the source, and no less anywhere.+ steepest = 1-math.pi/2*math.hypot(dx/CHEST[2], dy/CHEST[3])+ assert entry['jacobian_min'] == pytest.approx(steepest, abs=0.05) and cell['jacobian_min'] == entry['jacobian_min']+ assert entry['jacobian_min'] >= 1-entry['fold_ratio']-1e-4 and entry['fold_ratio'] == pytest.approx(entry['reach_px']*math.pi/(2*16), abs=1e-4)+ if entry['reach_px'] >= 1:+ moving += 1+ x, y = entry['jacobian_min_at']+ cx, cy, rx, ry = entry['ellipse']+ assert 0.3 < math.hypot((x-cx)/rx, (y-cy)/ry) < 0.7, cell['index']+ assert moving > N/2+ assert record['regions'][0]['jacobian_min'] == min(cell['jacobian_min'] for cell in record['cells'])+ assert record['regions'][0]['fold_ratio'] == max(cell['regions'][0]['fold_ratio'] for cell in record['cells'])+ # Lowered to the largest gain that does not fold it, a region is drawn nearly stopped where it moves most:+ # not folded, and stretched.+ lowered = inspect(loop_dir, [CHEST], tmp_path/'lowered', gain=50, on_fold='lower')+ region = lowered['regions'][0]+ assert lowered['follow']['fold']['lowered'] is True and follow.GAIN_MEASURED <= region['gain'] < 50+ assert 0.99 <= region['fold_ratio'] < 1 and 0 < region['jacobian_min'] < 0.15+ # At gain 0 nothing moves and nothing is stretched.+ still = inspect(loop_dir, [CHEST], tmp_path/'still', gain=0)+ assert {(cell['changed_px'], cell['jacobian_min'], *cell['regions'][0]['offset_px']) for cell in still['cells']} == {(0, 1, 0, 0)}+ assert still['boards']['source']['pixels_sha256'] == still['boards']['moved']['pixels_sha256'] == record['boards']['source']['pixels_sha256']+ assert record['boards']['moved']['pixels_sha256'] != record['boards']['source']['pixels_sha256']+++def test_a_part_that_crosses_an_ellipse_is_shown_and_not_judged(tmp_path):+ crossing = range(9, 14)+ bare = inspect(strip_dir(tmp_path/'bare'), [CHEST], tmp_path/'bare-out')+ crossed = inspect(strip_dir(tmp_path/'crossed', lambda k: figure(k, arm=(crossing[0], crossing[-1]))), [CHEST], tmp_path/'crossed-out')+ # A forearm of the torso's own colour, thinner than the body: the motion read off the cells is the bare figure's,+ # so the ellipse is carried over the forearm as it is over the chest.+ assert [cell['carry_px'] for cell in crossed['cells']] == [cell['carry_px'] for cell in bare['cells']]+ assert crossed['follow'] == bare['follow'] and crossed['input_id'] != bare['input_id']+ # The engine says of no cell what is inside its ellipse: the cells the forearm crosses are written as every other.+ entries = [entry for cell in crossed['cells'] for entry in cell['regions']]+ assert {entry['ownership'] for entry in entries} == {'unknown'} and len({tuple(sorted(entry)) for entry in entries}) == 1+ assert 'ownership' not in crossed['follow'] and all('ownership' not in cell for cell in crossed['cells'])+ scale = crossed['boards']['scale']+ seen = [tiles(tmp_path/name, record, 'source') for name, record in (('bare-out', bare), ('crossed-out', crossed))]+ moved = tiles(tmp_path/'crossed-out', crossed, 'moved')+ taken = 0+ for k, cell in enumerate(crossed['cells']):+ differs = (seen[0][k] != seen[1][k]).any(axis=-1)+ within = enlarged(covered(cell['regions'][0]['ellipse']), scale)+ if k in crossing:+ # It is on the board of the cells as cut, inside the ring, for whoever reads that board;+ forearm = differs & within+ assert forearm.any(), k+ # and on the other board it has moved with the chest.+ taken += int(((seen[1][k] != moved[k]).any(axis=-1) & forearm).sum())+ else:+ assert not differs.any(), k+ assert taken > 0+++def test_the_command_takes_what_video_follow_takes(tmp_path, capsys):+ description, add_arguments, run = cli.COMMANDS['video-follow-inspect']+ assert run is follow_inspect.run and 'nothing moved' in description+ loop_dir, out = strip_dir(tmp_path/'loop'), tmp_path/'out'+ asked = ['--loop-dir', str(loop_dir), '--region', '60,72,18,16', '--region', '66,20,9,9', '--gain', '50', '--on-fold', 'lower',+ '--freq', '2.5', '--zeta', '0.5']+ parsers = [argparse.ArgumentParser(), argparse.ArgumentParser()]+ cli.COMMANDS['video-follow'][1](parsers[0])+ add_arguments(parsers[1])+ followed, inspected = vars(parsers[0].parse_args(asked)), vars(parsers[1].parse_args([*asked, '--out-dir', str(out)]))+ assert set(inspected)-set(followed) == {'out_dir', 'scale', 'columns'} and set(followed)-set(inspected) == {'board'}+ assert {key: inspected[key] for key in followed if key != 'board'} == {key: value for key, value in followed.items() if key != 'board'}+ capsys.readouterr()+ assert cli.main(['video-follow-inspect', *asked, '--out-dir', str(out), '--columns', '6']) == 0+ printed, said = capsys.readouterr()+ printed, record = json.loads(printed), json.loads((out/FILES[0]).read_text())+ assert (out/FILES[0]).samefile(printed['record']) and printed['input_id'] == record['input_id'] and printed['cells'] == N+ assert printed['ownership'] == 'unknown' and printed['held'] == [] and printed['region_gains'] == [region['gain'] for region in record['regions']]+ assert [(out/record['boards'][name]['file']).samefile(printed['boards'][name]['path']) for name in ('source', 'moved')] == [True, True]+ assert record['boards']['columns'] == 6 and record['inputs']['settings'] == {'gain': 50.0, 'on_fold': 'lower', 'freq_hz': 2.5, 'zeta': 0.5}+ lines = said.strip().splitlines()+ assert lines and all(line.startswith('video-follow-inspect: --gain 50 folds ') and 'lowered to --gain ' in line for line in lines)+ assert follow_inspect.main([*asked, '--out-dir', str(tmp_path/'direct')]) == 0+ assert json.loads((tmp_path/'direct'/FILES[0]).read_text())['input_id'] == record['input_id']