Skip to content

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

feat(video-loop): the flow reading — the frames that leave a walk's way, by direction and speed, not by step size

Soohong Kimdfb76f94b0a9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d83f6a4..f838e19 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,8 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the
## Unreleased
+- **New: the flow reading of a walk loop (`repair.flow_scores`, `repair.flow_targets`) — the frames that leave the way a part is going, by direction and speed, not by the size of a step.** Each frame is a point of the loop's path, its coverage and shading blurred by 3 % of the body height, read in nine windows of the union box: how far it lies off the straight line between its neighbours (the second difference, the acceleration), in that window's usual steps. A clip filmed on twos or threes is read on its drawings, the hold `held.measure`'s. `flow_targets` takes the worst frame at or over 3.0 first and names the fewest frames around it — one, then two — whose straight in-between brings every frame it touches under 3.0, never made from a frame taken before; what two cannot bring under is `unfixed`. On the synthetic walks an ordinary loop reads at most 1.65 where the jump score names 8 to 18 steps, and a tail flung 5 % of the body height against its sway reads 2.8 to 4.1. Measured, not yet acted on: `--repair auto` still chooses by the jump score. The methods weighed beside it — interpolation error with RIFE, optical flow, a periodic fit, a Kalman predictor, Savitzky–Golay, a Hampel test — and their sources are in docs/loop-repair.md section 2, "The flow reading".
+- **Tests** — `tests/video/test_loop_flow.py` (an ordinary walk whose quick swing the jump score names has no frame taken; a frame flung against the sway is the one frame taken, read behind the body and turning back; a tail that snaps back at a wrap that does not close takes a frame at the wrap; the same whichever way the body faces; a walk on twos read on its drawings, a drawing flung the two frames that show it; two frames flung in a row one group of two; three flung frames three groups, none made from a frame taken before; a span too short named `unfixed`; a loop of three drawings left alone; a loop with no body refused).
- **Behavior change: `pixel-draw` runs on your Claude subscription first, and on `ANTHROPIC_API_KEY` only without one** — the order `codex` and `grok` keep. When `claude auth status` says Claude Code is signed in with a subscription (`claude.ai` or `oauth_token`), every call — the drawings, the row repairs, the pick — goes through the unmodified `claude` binary in print mode, from an empty directory, with no tool, no session written and no CLAUDE.md, hook, skill, plugin or MCP server loaded, and costs nothing per call: `report.json` says `auth_source: claude-login`, each call's `mode` is `subscription` and its `cost_usd` `0`, its usage kept. The child never sees `ANTHROPIC_API_KEY`, which print mode would use instead of the login. Without a subscription login the run uses the key as before, billed per call and said on stderr; with neither it is refused naming both, before the run folder is made. A login that refuses a call, has expired or has reached its usage limit fails the call; the run never switches to the key on its own. `--batch` is the API's Message Batches and runs on the key even when signed in. An answer the binary continues past the output cap is read whole from every message, not from its `result`, which holds only the last part; one it cannot finish is read as `stop_reason: max_tokens`, so the one redraw one effort lower happens on either route. One call may take up to `SPRITE_GEN_CLAUDE_CALL_TIMEOUT_SECONDS` (1800). When candidates ask at once, none of their requests leaves before the billing line has been printed. `report.json`'s `auth_source` is what the calls ran on by their records, `mixed` (with `auth_sources`) for a run resumed under the other credential. A `--resume` that reads every call back no longer prints the billing line ([pixel-draw](docs/pixel-draw.md#which-credential-a-call-runs-on)).
- **Behavior change: every metered call says so on the terminal, and every report names what a call ran on.** How codex is signed in is one reading, `codex_provider.codex_login` (`codex login status`), for the default provider resolution, `gen --provider codex`, the codex facing check and `workflow`: a codex signed in with an API key used to run with no word about it and the workflow called it a subscription; it now prints the per-call charge line before `codex exec` runs, its report records `extra.auth_source: codex-api-key` (`codex-login` on ChatGPT), and `workflow` asks to confirm the API credit. A codex that is not signed in is refused with the reason before it runs. `gen-set` and `video-set` keep each item's output in its log, but a child's billing line and a default provider switch now also print on the terminal as they happen (`base.run_logged`), each `gen-set` row records `auth_source`, and each `video-set` clip result too. `sound` prints the same billing line as every other metered route (it printed its own) and its receipt records `auth_source`. One function reads a provider key from the environment (`base.env_api_key`: a key, none, or a refusal of an empty one) for Anthropic, OpenAI, xAI and ElevenLabs; one function says what to do when xAI rejects a credential (`xai.rejected_fix`), so `gen --provider grok` now gives the same `grok models` refresh as `video`. `workflow` probes a provider once for its images and videos (they share one credential) and asks the API-credit question by that provider's name rather than always about Grok video. Docs: the credential table in the README, grok's `XAI_API_KEY` route in the help and SKILL.md, the sound billing line, `SPRITE_GEN_GEN_TIMEOUT_SECONDS` and `SPRITE_GEN_CLAUDE_READ_TIMEOUT_SECONDS`, and `gen-set --provider` (`codex` or `grok`).
- **Tests** — `tests/gen/test_claude_login.py` (the login before the key, the key only without a login, neither refused naming both, a batch on the key without asking the login, an unreadable status refused rather than read as no login, the child's environment without a key or the calling session, a message mapped onto the binary's flags and stdin with its image and schema, the stream-json answer, a cut answer read as max_tokens, a refused or limited login an error and not a switch to the key, no result, a timeout and a missing binary), the subscription, batch and read-back cases in `tests/gen/test_pixel_draw.py`, and `gen.base.env_api_key` in `tests/gen/test_gen.py`; `tests/gen/test_codex_login.py` (ChatGPT, an API key and not signed in; the default resolution, `generate` and `workflow` read the same login; an API-key login announces the charge and records it), `base.run_logged` in `tests/gen/test_gen.py`, the ElevenLabs billing line and key refusals in `tests/audio/test_sound.py`.
diff --git a/docs/README.md b/docs/README.md
index 026b850..97a1c8e 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -85,7 +85,7 @@ grouping is derived from `sprite_gen/_modules.py`, the one taxonomy table.
| [video.md](video.md) | `sprite-gen video` / `video-extend` / `video-edit` / `video-resume`: stills and clips to mp4 through Grok Imagine (image-to-video, last-frame pin, references, extension, editing, asking again for an unfinished generation) with the user's own credential |
| [video-pipeline.md](video-pipeline.md) | Pipeline B engine contract: state canvas, keyed frames, true-period and one-shot cycles, strip/GIF/WebP, the batch, a set's directions on one sheet |
| [loop-review.md](loop-review.md) | Automatic loop decisions, ambiguous gait review, visual evidence and explicit cut/alignment overrides |
-| [loop-repair.md](loop-repair.md) | RIFE (where it runs, cost, licences, `sprite-gen rife install`, what runs without it), jump-frame repair, the jolt index and its gate, one cycle length per direction set |
+| [loop-repair.md](loop-repair.md) | RIFE (where it runs, cost, licences, `sprite-gen rife install`, what runs without it), jump-frame repair, the flow reading (frames off a walk's way), the jolt index and its gate, one cycle length per direction set |
| [frame-interpolation.md](frame-interpolation.md) | Generative in-betweens for sprite frames, recorded as a take |
| [seamless-video-loop.md](seamless-video-loop.md) | Making a non-looping ambient clip loop forever (RIFE seam bridge) — a different job from pipeline B |
diff --git a/docs/loop-repair.md b/docs/loop-repair.md
index 3d4bed1..797135b 100644
--- a/docs/loop-repair.md
+++ b/docs/loop-repair.md
@@ -1,6 +1,6 @@
# Loop repair — RIFE in-betweens for jump frames, the jolt index, one cycle per set
-> Owns: Where RIFE runs and what it costs, how it is installed and what runs without it, jump-frame repair in `video-loop`, the jolt index and its gate, cycle alignment across a direction set · Index: [docs/README.md](README.md)
+> Owns: Where RIFE runs and what it costs, how it is installed and what runs without it, jump-frame repair in `video-loop`, the flow reading (frames off a walk's way), the jolt index and its gate, cycle alignment across a direction set · Index: [docs/README.md](README.md)
A walk loop cut from a generated clip can look right in every still and still hitch when it
plays: the video model redraws thin hair a little differently every frame, and now and then
@@ -260,6 +260,88 @@ engine replaces the same frames as the experiment on every take tried — Lite s
[3, 15, 19], Pro back-diagonal NE2 [9], Lite front S2 [0, 11, 14], and nothing in the smooth
Lite side E2. About 0.7 s a replaced frame on the Mac's GPU.
+### The flow reading — a frame off the walk's way, not a large step
+
+The jump score above counts how much a step changes. A walk's own steps change by very different
+amounts — a leg swung through moves far in one frame, a planted foot not at all — so on an ordinary
+walk the size reading names fast swings as jumps (on the synthetic walks below, five to eighteen
+steps of a loop that has none), and a frame that pops against the way a part is going reads no
+larger than a swing. `repair.flow_scores` and `repair.flow_targets` read the same loop by direction
+and speed instead. They are measured, not yet acted on: `--repair auto` still picks its frames by
+the size reading.
+
+**What is read.** Each frame is a point of the loop's path: its coverage and its shading (luma
+times coverage) inside the union box, averaged down to a grid a third of the blur's size and
+blurred with a sigma of 3 % of the body height (`FLOW_BLUR`) — a shape moved an ordinary step still
+overlaps where it was, so a step is a short move along the path, not a jump to an unrelated
+picture. The box is read in nine windows, each half its width and half its height, at a stride of a
+quarter (`FLOW_GRID` 4), so a tail, a hand or a foot is whole in at least one window.
+
+| Per frame t, per window | What |
+|---|---|
+| off the path | \|x(t+1) − 2 x(t) + x(t−1)\| / 2: how far the frame lies from the straight line between its two neighbours — the second difference, the acceleration of pose-from-video papers, and the error a straight in-between of the neighbours would make there |
+| usual step | the window's median step over the loop, and no less than the median of those over the windows (a window where little moves is not read on its noise) |
+| `off` | off the path over the usual step; a frame's `off` is its worst window's |
+| `turn` | there, the cosine between the step into the frame and the step out of it: below 0 the part goes back the way it came (1 where either step is still) |
+| `into`, `out` | there, the step into the frame and the step out of it, in the window's usual steps: a lurch is one far larger than the other |
+
+Off the path is direction and speed at once: |out − in|² = |in|² + |out|² − 2 |in| |out| cos θ.
+A part that moves on the way it was going, slow or fast, keeps it small; one that turns back, or
+lurches, makes it large. A part that slows to a stop and swings back (a leg at the end of its swing)
+turns back over small steps, and stays small.
+
+**On its drawings.** A clip filmed on twos or threes shows each drawing for two or three frames
+(`sprite_gen/video/held.py`; section 4, "Held drawings — a take to film again"): a step of nothing, then a step of two, at every drawing — a lurch at
+every drawing, read frame by frame, and a median step that falls between the two kinds. The path is
+read on the drawings instead (`flow_drawings`): the hold is `held.measure`'s, read on the path's own
+steps as a ring, a frame whose step from the frame before it is under its boundary repeats that
+drawing, and every frame that shows a drawing reads the drawing's values. A loop drawn every frame is
+a drawing a frame.
+
+**Which frames.** `flow_targets` takes the worst drawing at or over `FLOW_LIMIT` (3.0) first: the
+fewest drawings in a row around it (one, then two, `FLOW_SPAN`) whose straight in-between, from the
+drawing before them to the drawing after, brings every drawing it touches under the limit — the
+smallest result among those that do. The path then reads with that in-between and the next worst
+drawing is read. A group never takes, or is made from, a drawing a group before it took (two made
+frames side by side are made from each other). A drawing no group of up to two brings under the
+limit is `unfixed`. A flung frame is one group of one (on twos, the two frames that show it); a part
+that snaps back at a wrap that does not close is the frame on one side of the wrap, or both. The
+straight line is a stand-in for the frames RIFE makes there: it says which frames to take out, not
+how the made frames will look.
+
+Each group records its `frames` in play order, the worst drawing's `off`, `turn`, `into`, `out` and
+`window` (fractions of the box, x0, y0, x1, y1), and `off_after`; an `unfixed` entry the same with the
+best `off_after` a group reached. The record has `limit`, `span`, `blur`, `grid`, `hold`, `drawings`,
+`off_max_before` and `off_max_after`.
+
+**The limit.** On the synthetic walker of `tests/video/test_loop_flow.py` and its variants (measured
+2026-10-15), an ordinary loop reads at most 1.65 — drawn every frame with its quick swing faster or
+even, at 24 frames, with a tail swaying twice a cycle, or on twos. A frame whose tail is flung 5 % of
+the body height against its sway reads 2.8 to 4.1, by where the sway is; 8 % reads 3.7 to 6.4; 3 %
+reads 2.2, under the limit; a tail that runs a quarter of a cycle short snaps back at the wrap at 5.3,
+half a cycle short at 4.8. A part flung over the body reads less (1.8 to 2.2 at 5 %, 2.6 to 3.0 at
+8 %, where the tail crosses the torso): there the coverage does not change, only the shading. Two
+frames in a row flung as far are a plateau, each of its edges half as far off the path (2.2 at 5 %,
+3.4 at 8 %). `FLOW_LIMIT` 3.0 sits above every
+ordinary loop with room to spare: a frame is taken only where it plainly leaves the way.
+
+**The methods weighed.** The question — which frame of a sequence leaves its motion — has answers
+already; they were measured side by side on the synthetic loops above, each read in the same windows
+of the same blurred path, over the same usual step unless said otherwise.
+
+| Method | Source | On the synthetic loops | Taken? |
+|---|---|---|---|
+| Size of a step (the jump score above) | section 2, above | the ordinary walks name 8 to 18 steps over 1.4; a frame flung 3 % reads 2.61, under an ordinary walk's 2.67 | no: it counts size, not direction |
+| **Second difference — the acceleration — on the drawings** | Kanazawa et al., "Learning 3D Human Dynamics from Video", CVPR 2019, section 6.1: the acceleration error, and where there is no ground truth "we simply report the acceleration" | ordinary ≤ 1.65; flung 5 % 2.8 to 4.1; flung 3 % 2.2 | **yes**: it is the error of the straight in-between, the repair's own question; Pillow and numpy |
+| Interpolation error, with RIFE as the interpolator (the optical-flow warping family) | Baker et al., "A Database and Evaluation Methodology for Optical Flow", IJCV 2011 (interpolation error); Lai et al., "Learning Blind Video Temporal Consistency", ECCV 2018 (temporal warping error) | the same ranks; ordinary up to 2.11, on the quickest swing | no: a RIFE call for every frame (about 3 s each on a CPU in the cloud, section 1), and flow is least sure on large, occluded and flat-coloured motion in 2D animation — AnimeRun (Siyao et al., NeurIPS 2022, table 2) measures RAFT's end-point error at 58 px over motions past 50 px and 35 px on occluded pixels, where a pop is |
+| Optical flow itself (Farnebäck; RAFT) | Farnebäck, SCIA 2003; Teed and Deng, ECCV 2020 | not run | no: OpenCV or PyTorch for the engine (a PyTorch RIFE was turned down for the same reason, section 1), and the weakness above |
+| A periodic (Fourier) curve fitted to each region's path | gait as a Fourier series: Cunado, Nixon and Carter, CVIU 2003 | ordinary up to 2.94; flung 3 % 2.23 | no: a quick swing and a slow plant need more harmonics than a one-cycle loop has frames to fit them with |
+| Constant-velocity prediction (a Kalman predictor) | Kalman, Journal of Basic Engineering, 1960 | ordinary up to 3.29; names the frame after the flung one | no: one-sided — the frame after a flung frame misses most |
+| Savitzky–Golay smoothing residual | Savitzky and Golay, Analytical Chemistry, 1964 | the same ranks at half the scale | no: a wider smoothing of the same second difference |
+| A Hampel test (median and MAD) of the acceleration | Hampel, JASA 1974; Leys et al., JESP 2013 | ordinary walks up to 10; flung 3 % 20 | no: an even walk's acceleration varies so little that its z has no fixed bound. The median stays, as the usual step |
+| Frame deletion and insertion by optical-flow consistency | Chao, Jiang and Sun, IWDW 2012 | not run | no: the same question for edited video, answered on flow (above) |
+| Outermost points (each row's outermost column) fitted on a periodic curve | — | not run on these loops | no: the outermost point of a row switches from one part to another (a foot leaving the row), a jump on an ordinary step |
+
## 3. The jolt index — reported on every walk, a gate only when asked
A loop whose steps change unevenly jolts even when no single step is a jump. Every walk or run
diff --git a/sprite_gen/video/repair.py b/sprite_gen/video/repair.py
index 6e81f39..6f0123a 100644
--- a/sprite_gen/video/repair.py
+++ b/sprite_gen/video/repair.py
@@ -14,6 +14,10 @@ frame beside it (docs/loop-repair.md section 4).
Measured on the loop as it plays — cyclic, the last frame followed by the first — and inside
the union box of the body over the whole loop, the way the strip cells are cut, so a frame's
score does not depend on where the canvas put the body.
+
+The flow reading (`flow_scores`, `flow_targets`) reads the same loop by direction and speed
+instead of size: how far each frame lies off the line between its neighbours, in the usual steps
+of the region it is read in (docs/loop-repair.md section 2, "The flow reading").
"""
from __future__ import annotations
@@ -23,6 +27,7 @@ from typing import Any
from PIL import Image
from sprite_gen._deps import np
+from sprite_gen.video import held as held_mod
from sprite_gen.video.rife import Interpolate, crossfade, ghost, smear
from sprite_gen.video.interpolation_quality import clean_beside, faults, ghost_screen, looks
@@ -78,6 +83,219 @@ def jump_scores(frames: list[Image.Image], *, facing: str = "right", box: tuple[
return {"whole": w, "hair": h, "score": np.maximum(w, h)}
+# --- the flow reading (docs/loop-repair.md section 2, "The flow reading") ---------------------------
+
+# A loop plays its frames as a path: each frame a point, the body's coverage and shading blurred to
+# the size of a step. Where a part moves the way it is going — slow or fast, a leg swung through — a
+# frame lies near the line between the frames either side of it. A frame drawn where the flow does
+# not go (a tail flung against its sway for one frame, a tail snapping back at a wrap that does not
+# close) lies far off that line, whatever its size. The size reading above counts how much a step
+# changes and cannot tell the two apart: on an ordinary walk it names a fast swing a jump.
+FLOW_BLUR = 0.03 # the blur's sigma, of the body height: a shape moved one ordinary step still overlaps where it was
+FLOW_GRID = 4 # the union box in FLOW_GRID x FLOW_GRID cells, read in windows of 2 x 2 cells at a stride of one cell
+FLOW_LIMIT = 3.0 # a frame this many of its window's usual steps off the line between its neighbours leaves the flow
+FLOW_SPAN = 2 # frames in a row a group takes out at most, to be made again between the frames either side
+_LUMA = np.array([0.299, 0.587, 0.114])
+
+
+def _blur(planes: np.ndarray, sigma: float) -> np.ndarray:
+ """A Gaussian blur of `sigma` px over axes 1 and 2 of (n, h, w, c), outside the grid empty."""
+ r = max(1, int(np.ceil(3 * sigma)))
+ k = np.exp(-0.5 * (np.arange(-r, r + 1) / sigma) ** 2)
+ k /= k.sum()
+ for axis in (1, 2):
+ pad = [(0, 0)] * planes.ndim
+ pad[axis] = (r, r)
+ padded = np.pad(planes, pad)
+ size = planes.shape[axis]
+ planes = sum(k[i] * np.take(padded, np.arange(i, i + size), axis=axis) for i in range(2 * r + 1))
+ return planes
+
+
+def flow_states(frames: list[Image.Image], box: tuple[int, int, int, int] | None = None) -> np.ndarray:
+ """Each frame of the loop as a point of its path, (frames, h, w, 2): its coverage and its shading
+ (luma times coverage) inside `box` (the union box), averaged down to a grid of a third of the blur
+ and blurred by FLOW_BLUR of the body height. Raises ValueError for a loop with no body."""
+ pixels = np.stack([np.asarray(f.crop(box or union_box(frames)), dtype=np.float64) / 255.0 for f in frames])
+ alpha = pixels[..., 3]
+ rows = np.where(alpha.max(axis=(0, 2)) > 0.1)[0]
+ if rows.size == 0:
+ raise ValueError("every loop frame is fully transparent")
+ sigma = FLOW_BLUR * max(1, int(rows.max() - rows.min()))
+ planes = np.stack([alpha, (pixels[..., :3] @ _LUMA) * alpha], axis=-1)
+ n, height, width, c = planes.shape
+ f = max(1, min(int(round(sigma / 1.5)), height, width))
+ h, w = height // f, width // f
+ small = planes[:, :h * f, :w * f].reshape(n, h, f, w, f, c).mean(axis=(2, 4))
+ return _blur(small, sigma / f)
+
+
+def flow_windows(h: int, w: int) -> list[tuple[int, int, int, int]]:
+ """The windows of a (h, w) grid the flow is read in, (y0, y1, x0, x1): 2 x 2 of FLOW_GRID x FLOW_GRID
+ cells at a stride of one cell, so a part between two cells is whole in one window."""
+ ys = np.linspace(0, h, FLOW_GRID + 1).astype(int)
+ xs = np.linspace(0, w, FLOW_GRID + 1).astype(int)
+ return [(int(ys[i]), int(ys[i + 2]), int(xs[j]), int(xs[j + 2])) for i in range(FLOW_GRID - 1) for j in range(FLOW_GRID - 1)]
+
+
+def _flow_read(states: np.ndarray, windows: list[tuple[int, int, int, int]]) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
+ """Per frame and window, cyclic: how far the frame lies off the line between its two neighbours (half the
+ change from the step into it to the step out of it), the step out of it (frame k to k+1), and the cosine
+ between the step into it and the step out of it. Each (frames, windows)."""
+ n = len(states)
+ off, step, turn = (np.zeros((n, len(windows))) for _ in range(3))
+ for i, (y0, y1, x0, x1) in enumerate(windows):
+ x = states[:, y0:y1, x0:x1].reshape(n, -1)
+ out = np.roll(x, -1, axis=0) - x
+ into = np.roll(out, 1, axis=0)
+ step[:, i] = np.linalg.norm(out, axis=1)
+ off[:, i] = np.linalg.norm(out - into, axis=1) / 2
+ norms = np.linalg.norm(into, axis=1) * step[:, i]
+ turn[:, i] = np.where(norms > 0, (into * out).sum(axis=1) / np.where(norms > 0, norms, 1.0), 1.0)
+ return off, step, turn
+
+
+def _flow_scale(step: np.ndarray) -> np.ndarray:
+ """Per window, the usual step it is read against: its median step, and no less than the median of
+ those over the windows, so a window where little moves is not read on its noise."""
+ median = np.median(step, axis=0)
+ return np.maximum(median, max(float(np.median(median)), 1e-12))
+
+
+def flow_drawings(states: np.ndarray) -> tuple[list[list[int]], int]:
+ """The drawings of a loop's path, as runs of the frames that show each (each run from the frame that
+ begins it, in play order), and the hold. A loop filmed on twos or threes shows each drawing for two or
+ three frames: the repeat is the same point of the path, and its step of nothing beside the drawing's
+ step of two would read as a lurch at every drawing. The hold is `held.measure`'s, read on the steps of
+ this path as a ring; a frame whose step from the frame before it is under its boundary repeats that
+ frame's drawing. A loop drawn every frame (hold 1) is a drawing a frame."""
+ n = len(states)
+ steps = [float(np.linalg.norm(states[(k + 1) % n] - states[k])) for k in range(n)]
+ # The hold is read on the rhythm of the steps; the rate only says how many drawings a second, unused here.
+ rhythm = held_mod.measure(steps, fps=1.0, cyclic=True)
+ hold = int(rhythm.get("hold") or 1)
+ repeat = [hold > 1 and steps[(t - 1) % n] < rhythm["held_below"] for t in range(n)]
+ if all(repeat) or not any(repeat):
+ return [[t] for t in range(n)], 1
+ begin = repeat.index(False)
+ runs: list[list[int]] = []
+ for i in range(n):
+ t = (begin + i) % n
+ if repeat[t]:
+ runs[-1].append(t)
+ else:
+ runs.append([t])
+ return runs, hold
+
+
+def _flow(frames: list[Image.Image], box: tuple[int, int, int, int] | None) -> dict[str, Any]:
+ """The loop's path read on its drawings: their states, the runs of frames that show them, the windows,
+ and per drawing and window the distance off the path, the step out and the turn, and the windows' usual
+ step."""
+ states = flow_states(frames, box)
+ runs, hold = flow_drawings(states)
+ path = states[[run[0] for run in runs]]
+ windows = flow_windows(states.shape[1], states.shape[2])
+ off, step, turn = _flow_read(path, windows)
+ h, w = states.shape[1], states.shape[2]
+ return {"path": path, "runs": runs, "hold": hold, "windows": windows, "off": off, "step": step, "turn": turn,
+ "scale": _flow_scale(step), "fractions": [(x0 / w, y0 / h, x1 / w, y1 / h) for y0, y1, x0, x1 in windows]}
+
+
+def _drawing_scores(flow: dict[str, Any]) -> dict[str, Any]:
+ """Per drawing: `off`, `window`, `turn`, `into` and `out` in its worst window (`flow_scores`)."""
+ rel = flow["off"] / flow["scale"]
+ worst = rel.argmax(axis=1)
+ at = np.arange(len(rel))
+ out = flow["step"] / flow["scale"]
+ return {"off": rel[at, worst], "window": worst, "turn": flow["turn"][at, worst],
+ "into": np.roll(out, 1, axis=0)[at, worst], "out": out[at, worst]}
+
+
+def flow_scores(frames: list[Image.Image], *, box: tuple[int, int, int, int] | None = None) -> dict[str, Any]:
+ """Per frame, how far its drawing lies off the loop's flow (`off`): the distance from the line between
+ the drawings either side of it, over its window's usual step, in the window where that is largest
+ (`window`, its index in `windows`, fractions of the box (x0, y0, x1, y1)); there the cosine between
+ the step into the drawing and the step out of it (`turn`, below 0 against the way it came, 1 where
+ either is still) and the two steps in the window's usual steps (`into`, `out`). Every frame that
+ shows a drawing (`flow_drawings`, `hold`) reads the drawing's values."""
+ flow = _flow(frames, box)
+ per = _drawing_scores(flow)
+ of = np.zeros(len(frames), dtype=int)
+ for d, run in enumerate(flow["runs"]):
+ of[run] = d
+ return {**{k: v[of] for k, v in per.items()}, "windows": flow["fractions"], "hold": flow["hold"]}
+
+
+def flow_targets(frames: list[Image.Image], *, limit: float = FLOW_LIMIT, span: int = FLOW_SPAN,
+ box: tuple[int, int, int, int] | None = None) -> dict[str, Any]:
+ """The frames that leave the loop's flow, in groups to take out and make again between the frames either
+ side (docs/loop-repair.md section 2, "The flow reading"). Read on the loop's drawings (`flow_drawings`):
+ a frame on its own where every frame is a drawing, all the frames that show it on twos or threes.
+
+ The worst drawing at or over `limit` first: the fewest drawings in a row around it (one, then up to
+ `span`) whose straight in-between from the drawing before them to the drawing after brings every drawing
+ it touches under `limit`, the smallest result among the groups that do; the path then reads with that
+ in-between, and the next worst drawing is read. A group never takes, or is made from, a drawing a group
+ before it took. A drawing no group of up to `span` brings under `limit` is `unfixed`. Each group: its
+ `frames` in play order, `off` (the worst of its drawings before) with its `turn`, `into`, `out` and
+ `window`, and `off_after`. The in-between is the straight line of the blurred path, a stand-in for the frames RIFE
+ makes there: it says which frames to take out, not how the made frames will look."""
+ flow = _flow(frames, box)
+ first = _drawing_scores(flow)
+ runs, windows, scale = flow["runs"], flow["windows"], flow["scale"]
+ n = len(runs)
+ record: dict[str, Any] = {"limit": limit, "span": span, "blur": FLOW_BLUR, "grid": FLOW_GRID, "hold": flow["hold"],
+ "drawings": n, "off_max_before": round(float(first["off"].max()), 4), "groups": [], "unfixed": []}
+ if n < 4:
+ record.update(stopped="loop shorter than 4 drawings", off_max_after=record["off_max_before"])
+ return record
+
+ def reading(path: np.ndarray) -> np.ndarray:
+ return (_flow_read(path, windows)[0] / scale).max(axis=1)
+
+ def said(d: int) -> dict[str, Any]:
+ return {"off": round(float(first["off"][d]), 4), "turn": round(float(first["turn"][d]), 4),
+ "into": round(float(first["into"][d]), 4), "out": round(float(first["out"][d]), 4),
+ "window": [round(v, 4) for v in flow["fractions"][int(first["window"][d])]]}
+
+ path, taken, unfixed = flow["path"].copy(), set(), set()
+ current = reading(path)
+ while True:
+ open_ = [d for d in np.argsort(-current, kind="stable") if current[d] >= limit and d not in taken and d not in unfixed]
+ if not open_:
+ break
+ d = int(open_[0])
+ tried: list[tuple[float, list[int], np.ndarray]] = []
+ ok: list[tuple[float, list[int], np.ndarray]] = []
+ for size in range(1, min(span, n - 2) + 1):
+ for start in range(d - size + 1, d + 1):
+ group = [(start + i) % n for i in range(size)]
+ a, b = (start - 1) % n, (start + size) % n
+ if {a, b, *group} & taken:
+ continue
+ made = path.copy()
+ for i, g in enumerate(group):
+ made[g] = path[a] + (i + 1) / (size + 1) * (path[b] - path[a])
+ after = reading(made)
+ tried.append((float(max(after[(a + i) % n] for i in range(size + 2))), group, made))
+ ok = [x for x in tried if x[0] < limit]
+ if ok:
+ break
+ if not ok:
+ unfixed.add(d)
+ record["unfixed"].append({"frames": runs[d], **said(d),
+ "off_after": round(min((x[0] for x in tried), default=float(current[d])), 4)})
+ continue
+ result, group, made = min(ok, key=lambda x: x[0])
+ worst = max(group, key=lambda g: float(first["off"][g]))
+ record["groups"].append({"frames": [t for g in group for t in runs[g]], **said(worst), "off_after": round(result, 4)})
+ taken |= set(group)
+ path, current = made, reading(made)
+ record["off_max_after"] = round(float(current.max()), 4)
+ return record
+
+
def _give_way(frames: list[Image.Image], j: int, ghosts: dict[int, float], interpolate: Interpolate | None,
out: list[Image.Image]) -> dict[str, Any]:
"""The round of a filmed ghost at `j` (`why` ghost), its cell replaced in `out` where it gives way.
diff --git a/tests/video/test_loop_flow.py b/tests/video/test_loop_flow.py
new file mode 100644
index 0000000..e737dc4
--- /dev/null
+++ b/tests/video/test_loop_flow.py
@@ -0,0 +1,140 @@
+# SPDX-License-Identifier: Apache-2.0
+"""The flow reading (docs/loop-repair.md section 2, "The flow reading"): a frame is taken when it lies off
+the path its neighbours draw — against the way a part is going, or a sudden change of its speed — not
+when its step is large. An ordinary walk, whose legs swing fast and plant slow, has no frame taken; a
+frame whose tail is flung against its sway is the one frame taken; a tail that snaps back at a wrap
+that does not close has the frames at the wrap taken; and which way the body faces does not matter.
+
+The loops are drawn here: a body, two legs swinging quick through the swing and slow through the
+stance, an arm, and a tail behind that sways once a cycle."""
+
+from __future__ import annotations
+
+import math
+
+import pytest
+from PIL import Image, ImageDraw, ImageOps
+
+from sprite_gen.video import repair
+
+W, H, N = 240, 300, 36
+
+
+def _frame(t: int, n: int, *, tail_off: float = 0.0, tail_lag: float = 0.0) -> Image.Image:
+ """Phase t/n of one gait cycle; `tail_off` puts the tail that many px off its sway, `tail_lag` its sway
+ that many cycles behind."""
+ im = Image.new("RGBA", (W, H), (0, 0, 0, 0))
+ d = ImageDraw.Draw(im)
+ phi = 2 * math.pi * t / n
+ bob = 3 * math.cos(2 * phi)
+ sway = phi - 2 * math.pi * tail_lag
+ tx, ty = 70 + 22 * math.sin(sway) + tail_off, 130 + bob - 10 * math.cos(sway)
+ d.polygon([(110, 120 + bob), (110, 150 + bob), (tx - 20, ty + 20), (tx - 30, ty - 25)], fill=(220, 120, 40, 255))
+ d.ellipse((tx - 50, ty - 40, tx - 10, ty + 10), fill=(240, 150, 60, 255))
+ # quick through the swing, slow through the stance: the coverage step varies a lot over an ordinary cycle
+ swing = 0.5 * math.sin(phi + 0.6 * math.sin(phi))
+ for hip, angle, colour in ((120, swing, (70, 60, 120, 255)), (128, -swing, (90, 80, 150, 255))):
+ x1, y1 = hip + 95 * math.sin(angle), 175 + bob + 95 * math.cos(angle)
+ d.line((hip, 175 + bob, x1, y1), fill=colour, width=16)
+ d.ellipse((x1 - 12, y1 - 7, x1 + 14, y1 + 7), fill=(40, 30, 30, 255))
+ d.rectangle((100, 100 + bob, 150, 185 + bob), fill=(200, 200, 220, 255), outline=(20, 20, 20, 255), width=3)
+ d.ellipse((96, 40 + bob, 156, 102 + bob), fill=(240, 210, 180, 255), outline=(20, 20, 20, 255), width=3)
+ arm = 0.4 * math.sin(phi + math.pi + 0.6 * math.sin(phi)) + 0.3
+ d.line((150, 110 + bob, 150 + 60 * math.sin(arm), 110 + bob + 60 * math.cos(arm)), fill=(240, 210, 180, 255), width=12)
+ return im
+
+
+def _against(t: int, n: int) -> float:
+ """The sign against the tail's sway at frame t: the way it is not going."""
+ return -math.copysign(1.0, math.cos(2 * math.pi * t / n))
+
+
+def _loop(n: int = N, *, flung: dict[int, float] | None = None, lag: float = 0.0, hold: int = 1) -> list[Image.Image]:
+ """A walk loop of n frames. `flung[t]` puts the tail at frame t that many px against its sway; `lag`
+ makes the tail run that many cycles short over the loop, so it snaps back at the wrap. `hold` 2 films
+ it on twos: each drawing shown for two frames (a drawing flung is flung in both)."""
+ flung = flung or {}
+ drawn = [t - t % hold for t in range(n)]
+ return [_frame(d, n, tail_off=_against(d, n) * flung.get(d, 0.0), tail_lag=lag * d / n) for d in drawn]
+
+
+def test_an_ordinary_walk_has_no_frame_off_its_flow_where_the_size_reading_names_jumps():
+ frames = _loop()
+ record = repair.flow_targets(frames)
+ assert record["groups"] == [] and record["unfixed"] == []
+ assert record["off_max_before"] < repair.FLOW_LIMIT
+ # The size reading counts how much a step changes: the quick swing reads as a jump to it.
+ assert (repair.jump_scores(frames)["score"] >= repair.JUMP_RATIO).sum() >= 5
+
+
+def test_a_frame_flung_against_the_sway_is_the_one_frame_taken():
+ frames = _loop(flung={10: 12})
+ scores = repair.flow_scores(frames)
+ assert int(scores["off"].argmax()) == 10 and scores["turn"][10] < 0 # it goes back the way it came
+ record = repair.flow_targets(frames)
+ assert [g["frames"] for g in record["groups"]] == [[10]] and record["unfixed"] == []
+ group = record["groups"][0]
+ assert group["off"] >= repair.FLOW_LIMIT > group["off_after"] and group["turn"] < 0
+ x0, y0, x1, y1 = group["window"]
+ assert x0 < 0.45 and y0 < 0.5 # read where the tail is: behind the body, above the legs
+
+
+def test_a_tail_that_snaps_back_at_the_wrap_has_the_frames_at_the_wrap_taken():
+ frames = _loop(lag=0.25)
+ record = repair.flow_targets(frames)
+ assert len(record["groups"]) == 1 and record["unfixed"] == []
+ assert set(record["groups"][0]["frames"]) <= {N - 1, 0}
+
+
+def test_it_reads_the_same_whichever_way_the_body_faces():
+ frames = _loop(flung={10: 12})
+ mirrored = [ImageOps.mirror(f) for f in frames]
+ assert [g["frames"] for g in repair.flow_targets(mirrored)["groups"]] == [[10]]
+
+
+def test_a_walk_on_twos_is_read_on_its_drawings():
+ # Each drawing shown twice: a step of nothing then a step of two, at every drawing. On its drawings the
+ # path is as smooth as the walk drawn every frame, and a drawing flung is the two frames that show it.
+ frames = _loop(hold=2)
+ record = repair.flow_targets(frames)
+ assert record["hold"] == 2 and record["drawings"] == N // 2
+ assert record["groups"] == [] and record["off_max_before"] < repair.FLOW_LIMIT
+ # A drawing's step is two frames' step: flung as far against its sway, it is half as far off its path.
+ record = repair.flow_targets(_loop(flung={10: 20}, hold=2))
+ assert [g["frames"] for g in record["groups"]] == [[10, 11]]
+ scores = repair.flow_scores(_loop(flung={10: 20}, hold=2))
+ assert scores["off"][10] == scores["off"][11] == scores["off"].max()
+
+
+def test_two_flung_frames_in_a_row_are_one_group_of_two():
+ # Two frames flung as far are a plateau: each of its edges half as far off the path as one flung frame.
+ record = repair.flow_targets(_loop(flung={10: 20, 11: 20}))
+ assert [sorted(g["frames"]) for g in record["groups"]] == [[10, 11]]
+
+
+def test_each_flung_frame_is_a_group_of_its_own_never_made_from_a_frame_taken_before():
+ record = repair.flow_targets(_loop(flung={4: 20, 14: 20, 24: 20}))
+ assert sorted(g["frames"] for g in record["groups"]) == [[4], [14], [24]] and record["unfixed"] == []
+ taken: set[int] = set()
+ for group in record["groups"]:
+ frames = group["frames"]
+ beside = {(frames[0] - 1) % N, (frames[-1] + 1) % N}
+ assert not (set(frames) | beside) & taken
+ taken |= set(frames)
+
+
+def test_a_jump_its_span_does_not_close_is_named_unfixed():
+ frames = _loop(lag=0.25)
+ record = repair.flow_targets(frames, span=1, limit=1.5)
+ assert record["unfixed"] and all(u["off_after"] >= 1.5 for u in record["unfixed"])
+ assert all(set(u["frames"]) <= {N - 2, N - 1, 0, 1} for u in record["unfixed"])
+
+
+def test_a_loop_too_short_to_read_is_left_alone():
+ record = repair.flow_targets(_loop(3))
+ assert record["groups"] == [] and record["stopped"] == "loop shorter than 4 drawings"
+
+
+def test_a_loop_with_no_body_raises():
+ with pytest.raises(ValueError, match="fully transparent"):
+ repair.flow_states([Image.new("RGBA", (40, 40))] * 6)