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 jump repair takes out the frames off the flow and makes them again at their own times

Soohong Kime43619fb469b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f838e19..4c53b0e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,7 +4,9 @@ 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".
+- **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. 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".
+- **Behavior change: `video-loop --repair auto` (and `on`) takes out the frames off a walk's flow and makes them again between the frames either side, each at its own time.** The frames are the flow reading's (`repair.flow_targets`), not the jump score's: a step 1.4 times the loop's median no longer remakes the frame after it, so the quick swing of an ordinary walk is left as filmed, and a frame flung against the way a part is going, which the jump score read no larger than a swing, is taken out. A group is one or two drawings in a row; RIFE makes each drawing between the first frame of the drawing before the group and of the drawing after, at the drawing's own time (`repair.between_time`: a half for one frame, a third and two thirds for two, a half for a drawing on twos), and shows it on every frame the drawing was — the loop keeps its length, every frame its time, a loop on twos its hold. One call a drawing, at most three a loop; one made frame with an interpolation fault refuses its whole group, which keeps its frames as filmed, and nothing is made from or beside a frame made, given way or refused. Of the groups that bring the reading under the limit, `flow_targets` now takes the one whose every drawing the in-between moves furthest (`move`): two frames flung together are taken out whole, where the frame beside the pair was taken before and the pair left standing. A loop whose only large steps are the steps into and out of a few jumps no longer reads as held (`HELD_RUNS`: three in four runs must be the hold, a frame more or less): read on those false drawings its jumps read as ordinary, and a drawing made would have stood for five frames. `jump_repair` reads `reading: flow`, `limit`, `span`, `hold`, `drawings`, `refused`, `unfixed`, `left`, `off_max_before` / `off_max_after` (in place of `score_max_before` / `score_max_after`, also in the summary and in `video-set`'s item record), and per round `why: flow` with its group and `made` (per drawing: `frames`, `t`, `original`, `proposal`, `faults`, `look`); `unmade` names the group's `frames`, `neighbours` and `off`. `repair.JUMP_RATIO` is gone; `repair.jump_scores` stays, the size reading `video-loop-compare`'s jump guard reads with the recorded `facing` ([loop-repair](docs/loop-repair.md#2-jump-frames--video-loop---repair-auto)).
+- **Tests** — `tests/video/test_loop_flow.py` (an ordinary walk the jump score would remake is left alone and RIFE is not called; a flung frame made again half way between its neighbours, every other frame the video's own; two flung frames made again at a third and two thirds; on twos a flung drawing made once from the frames two before and two after it and shown on both its frames; a group with one made frame at fault keeps both frames and is not tried again; the calls go to the worst frame first and stop at three, the group left named; no interpolator names the group; mirrored, the same) and `tests/video/test_loop_repair.py` (on its block walker: one flung frame, two side by side, the pair flung at the wrap taken out whole and made from the frames beside it rather than smoothed at its edges, jumps a few frames apart read a drawing a frame and not on threes, three outline-melted groups refused within the budget, groups made only from frames as filmed; `video-loop` playing two frames made again at their own times in a loop as long, and the flow numbers when no RIFE is installed); the ghost and cross-fade proposals of `tests/video/test_ghost_screen.py`, `tests/video/test_crossfade.py` and the real-RIFE case of `tests/video/test_rife.py` read through a group the flow reading is made to name.
- **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`).
diff --git a/docs/loop-comparison.md b/docs/loop-comparison.md
index e8f67a4..0a00925 100644
--- a/docs/loop-comparison.md
+++ b/docs/loop-comparison.md
@@ -414,11 +414,11 @@ reports it as delivered.
### The jump guard
A target is a cell the jump repair replaced, and the repair replaced it because
-a step into or out of the source frame at that time jumped ([loop
+the source frame at that time left the loop's flow ([loop
repair](loop-repair.md), section 2). The in-between it adopted may have melted,
and that is what restoration clears; the source frame it replaced is still the
jump. Its pixels can clear the melt and bring the jump back. `axes.jump` reads
-the jump repair's own step score on the final cells of both loops:
+the size reading's step score on the final cells of both loops:
```text
score[k] = repair.jump_scores(cells, facing, box)["score"][k] step k: cell k to cell k+1, the last to the first
@@ -428,12 +428,14 @@ jump(c) = max(score[c - 1], score[c]) the step into
regressed where jump(candidate) > jump(baseline) at a changed cell
```
-The score is the one the jump repair picks frames by: per step, the change of
-coverage over the whole box and over the hair behind the body, each over its
-own median in the loop, the larger of the two. Both loops are scored on one box,
+The score is the size reading: per step, the change of coverage over the whole
+box and over the hair behind the body, each over its own median in the loop, the
+larger of the two. The jump repair picked frames by it until it picked them by
+the flow reading ([loop repair](loop-repair.md), section 2); the guard still
+reads the size, and its record is unchanged. Both loops are scored on one box,
the source cells' (the jump repair reads the box of the loop as filmed), with
the facing the repair recorded. More than the baseline's is worse. No bound is
-read, `JUMP_RATIO` included: the baseline is the measure. A rise is a measured
+read: the baseline is the measure. A rise is a measured
worsening, as on every other axis, so the verdict is `regressed` with
`jump:regressed`, not `unknown`, and the next independent proposal may be
tried. A fall alone does not make a candidate `improved`: that still needs a
diff --git a/docs/loop-repair.md b/docs/loop-repair.md
index 797135b..9a722ec 100644
--- a/docs/loop-repair.md
+++ b/docs/loop-repair.md
@@ -66,7 +66,7 @@ cut before RIFE existed still cuts — and nothing is left unsaid:
| Where | Default without RIFE | Asked for by name |
|---|---|---|
-| `video-loop` jump repair (section 2) | `--repair auto`: a jump is cut as filmed, and each filmed ghost is given way to the clean frame beside it (its own `warning:` line). Where a jump is left, `jump_repair` reads `why`, `rife` (what was not found), `install` and `unmade` (the step, target and score the jump search stopped at), and one `video-loop: warning:` line on stderr says the jump frame was not repaired. `applied` is false only where nothing was replaced | `--repair on`: fails with the install line |
+| `video-loop` jump repair (section 2) | `--repair auto`: a jump is cut as filmed, and each filmed ghost is given way to the clean frame beside it (its own `warning:` line). Where a jump is left, `jump_repair` reads `why`, `rife` (what was not found), `install` and `unmade` (the frames, neighbours and `off` of the group the flow search stopped at), and one `video-loop: warning:` line on stderr says the jump frame was not repaired. `applied` is false only where nothing was replaced | `--repair on`: fails with the install line |
| `video-set` cycle alignment (section 4) | `--align-cycles auto`: the state is skipped and every loop keeps its own length; `cycle_align.<state>` reads `applied: false` with `why`, `rife`, `install`; the set report lists it under `warnings`; one `video-set: warning:` line | `video-cycle-align`: fails with the install line |
A RIFE that is found and then fails (a binary that cannot reach Vulkan, say) is an error in every
@@ -159,18 +159,20 @@ the zip's `LICENSE` with it.
A walk or run loop (`--state walk|run`) is read, after it is cut and anchored, as it will play:
cyclic, the last frame followed by the first, inside the union box of the body over the loop
-(the strip cells' own crop). For every step k → k+1 two numbers are taken — the mean change of
-coverage over the whole box, and over the hair behind the body, each divided by its own median
-over the loop — and the larger is the step's score.
+(the strip cells' own crop). The frames that leave the loop's flow — one or two drawings in a row
+that lie far off the line between the frames either side of them, by direction and speed, not by
+how much a step changes ([the flow reading](#the-flow-reading--a-frame-off-the-walks-way-not-a-large-step)
+below) — are taken out and made again by RIFE between the frames either side.
| Rule | Value | Why |
|---|---|---|
-| A jump | a score of at least **1.4** (`JUMP_RATIO`) | the ponytail cuts the experiment found sat at 1.5–2.5; a smooth take's worst step sits near 1.3 |
-| The hair box | (0, 0.30)–(0.45, 0.80) of the union box for a right-facing body; mirrored for `--facing left` | below the head and behind the body, where a ponytail cut at the wrong moment jumps |
-| The frame remade | the frame after the jump; but when the step *into* frame k is a jump too and larger than the step after k+1, frame k itself (a single stray frame breaks two steps) | remaking the frame after a stray frame leaves the stray standing |
-| How | propose RIFE's frame half way between the two neighbours, inspect it, then adopt it only without interpolation faults | a rejected proposal keeps the original middle frame; every other frame stays the video's own |
-| How many | at most **3 calls** (`MAX_REPAIRS`), rejected proposals included, worst eligible target first | a loop that needs more is jolting everywhere, not jumping once |
-| Never | a frame next to one already made | two made frames side by side are made from each other and melt the legs |
+| A frame off the flow | an `off` of at least **3.0** (`FLOW_LIMIT`): that many of its region's usual steps off the line between its neighbours | an ordinary walk reads at most 1.65, a part flung 5 % of the body height against its sway 2.8 to 4.1 (below) |
+| What is taken out | a group of one or two drawings in a row (`FLOW_SPAN`), worst first (`repair.flow_targets`, "Which frames" below); on twos or threes a drawing is every frame that shows it | the drawings off the flow, not the frames beside them that read off only because a neighbour is |
+| What it is made from | the frames either side of the group — the first frame of the drawing before it and of the drawing after it (`neighbours`) | the video's own frames, never a frame made |
+| When each made frame stands | each drawing at its own time between the two: t = (its first frame − the frame before) / (the frame after − the frame before), counted in play order across the wrap (`repair.between_time`) — a half for one frame, a third and two thirds for two in a row, and a half for a drawing on twos whose neighbours show from two frames before it and two after | the loop keeps its length and every frame its time; a drawing made is shown on every frame the drawing was, so a loop held on twos stays held |
+| How | one RIFE call a drawing; the group is taken only when none of its made frames has an interpolation fault (below) | a refused group keeps every frame it would take, as filmed; every other frame stays the video's own |
+| How many | at most **3 calls** (`MAX_REPAIRS`), refused groups included, worst group first; a group the calls left cannot pay for stops the stage (`left`) | a loop that needs more is jolting everywhere, not jumping once |
+| Never | made from or beside a frame already made, given way or refused | two made frames side by side are made from each other and melt the legs; the frames beside a refused group read off only because it does, and an in-between there would smooth toward it |
Re-making every frame (an offset of half a frame) is not offered: it softens the frames that
were fine, and it was judged "not corrected" (2026-10-03).
@@ -187,22 +189,28 @@ own (`why: "ghost"`), in frame order, before the jumps are read:
| RIFE's frame has a fault, a frame beside it is a filmed ghost too, or no RIFE is installed | the clean frame beside it: the one after, else the one before (`interpolation_quality.clean_beside`, the alignment's own choice at a time on a ghost) | `{"source": k}` |
| both frames beside it are filmed ghosts too | nothing: the ghost is kept, named, and the direction is to be filmed again | `null` |
-Ghost rounds are outside the three-call budget, which is the jumps'. A cell given way is in
-`replaced` like a jump frame made, so the rule "never next to a frame already made" holds around
-it too, and the jumps are then read on the loop as the ghosts left it. A cell given way to the
+Ghost rounds are outside the three-call budget, which is the flow groups'. A cell given way is in
+`replaced` like a frame made for the flow, so the rule "never made from or beside a frame already
+made" holds around it too, and the flow is then read on the loop as the ghosts left it. A cell given way to the
frame beside it is that frame shown twice in a row — a step of nothing and a step of two — and the
jolt index (section 3) measures it as it plays; the GIF and WebP hold it as one frame of twice the
delay, and are checked for one frame per run of identical cells. The seam gate reads it as filmed
(below). A loop the screen does not read (drawn part-covered, `reads: false`) has no ghost round.
-The report's `jump_repair` carries `replaced` (cycle frame indices, ghost and jump rounds alike), `attempts` (the jumps' calls),
-`blocked` targets, and each round's `why` (`ghost` or `jump`), target, `original` and `proposal`
-measurements (with each one's `ghost`, and the proposal's `crossfade`), `faults`, `look` and
-`outcome`. A jump round adds its step, score and whole/hair parts, its `outcome` `accepted` or
-`rejected`. A ghost round adds its `neighbours`, `taken` and `outcome` (`accepted` for RIFE's
-frame, `given-way` for the frame beside it, `kept`), and `no_proposal` where no frame was made
-("a frame beside it is a filmed ghost too", "no interpolator"); its `original.ghost` is the
-screen's reading. The report and its summary also carry `ghost_given_way` (`frame`, `ghost`,
+The report's `jump_repair` carries `reading` (`flow`), `limit`, `span` and `max_frames`; `facing`,
+recorded for the jump guard of `video-loop-compare`, which reads the size (below; the repair reads
+the flow whichever way the body faces); `hold` and `drawings`, the flow reading's of the loop as the
+ghosts left it; `replaced` (cycle frame indices, ghost and flow rounds alike), `refused` (the frames
+of the groups refused), `attempts` (the flow rounds' calls), `unfixed` and `left`; and each round's
+`why` (`ghost` or `flow`) and `outcome`. A flow round carries its group as `flow_targets` names it —
+`frames`, `drawings`, `neighbours`, `t`, `off`, `turn`, `into`, `out`, `window`, `move` and `off_after`
+(the reading the straight in-between brings it to) — and `made`, per drawing: its `frames`, `t`,
+`original` and `proposal` measurements (with each one's `ghost`, and the proposal's `crossfade`),
+`faults` and `look`. The round's own `faults` and `look` are its drawings' together, its `outcome`
+`accepted` or `rejected`. A ghost round carries its target, `original` and `proposal`, `faults`,
+`look`, `neighbours`, `taken` and `outcome` (`accepted` for RIFE's frame, `given-way` for the frame
+beside it, `kept`), and `no_proposal` where no frame was made ("a frame beside it is a filmed ghost
+too", "no interpolator"); its `original.ghost` is the screen's reading. The report and its summary also carry `ghost_given_way` (`frame`, `ghost`,
`taken`) and `ghost_kept` (`frame`, `ghost`), and the strip metadata carries each where it is not
empty: `cycle/` is what `video-cycle-align` reads as `cycle.source/`, and its screen no longer
sees a ghost given way, so the strip says what the cut gave way, in frames of the cut. A
@@ -213,19 +221,21 @@ made for the source projection and for restoration, which never restores it ([th
guard](loop-comparison.md#the-ghost-guard)). `--repair off` gives nothing way: the cut's ghosts are
delivered as filmed, named (section 4).
-Blocked targets are skipped while independent candidates remain. Scores are re-read
-after adoption; a rejected target is never retried in that run. The circular last/first
-adjacency rule and call budget still apply. The shared `interpolation_quality` policy
+The flow is read again after each group, on the union box of the loop as filmed; a refused group is
+never tried again in that run, and nothing is made from or beside it. The circular last/first
+adjacency rule and the call budget hold across the wrap. The shared `interpolation_quality` policy
is the same one used by cycle alignment: `dark_excess > 0.001` or
`outline_loss > 0.05` rejects a proposal, and so does a proposal that is a ghost on its own
coverage (`ghost` over 0.003, read where the loop's ghost screen reads it, section 4). An empty
-proposal is also rejected. A proposal that cross-fades two drawings inside its silhouette
-(`crossfade` over 0.015, section 4) is taken all the same and named: its round's `look` says so, and
-a `warning:` line names the frame.
-The original middle frame is retained, not a duplicate of either neighbour.
-
-The jump rounds' record is above; `jump_repair` also records `score_max_before` (the cut as
-filmed) / `score_max_after`, why it stopped, and which interpolator made the proposals. Rejection is not overall quality failure
+proposal is also rejected. One made frame at fault refuses its whole group. A proposal that
+cross-fades two drawings inside its silhouette (`crossfade` over 0.015, section 4) is taken all the
+same and named: its round's `look` says so, and a `warning:` line names the frames.
+A refused group keeps its frames as filmed, not a duplicate of a neighbour.
+
+`jump_repair` also records `off_max_before` (the flow reading of the cut as filmed) /
+`off_max_after` (of the loop as it now plays), why it stopped (`stopped`: "no frame off the flow",
+the frames left `unfixed`, the calls used, or no interpolator), and which interpolator made the
+proposals. Rejection is not overall quality failure
or success: original drawing changes and normal gait motion can remain.
When a frame was made — RIFE's, for a jump or for a filmed ghost — the seam gate measures the
rendered cells (`seam_measurement: rendered-cells`), because the source frames no longer say what
@@ -241,24 +251,28 @@ that only gave its ghosts way to the frames beside them is gated on its source f
To compare an active result with a final candidate after all processing, use
[`video-loop-compare`](loop-comparison.md); a seam pass alone is not an improvement.
-A replaced cell restored later from its source frame is compared with these
-same scores around it, with the recorded `facing`: a restoration that brings
+A replaced cell restored later from its source frame is compared with the
+size reading around it (`repair.jump_scores`, the change of coverage over the whole box and the hair
+behind the body, with the recorded `facing`): a restoration that brings
the jump back is not an improvement ([the jump guard](loop-comparison.md#the-jump-guard)).
RIFE is located only when a frame is to be made. A loop with a jump and no RIFE is cut as filmed
with a warning under `--repair auto`, and fails under `--repair on` (section 1, "Without RIFE");
so does a filmed ghost between two clean frames under `--repair on`. Under `--repair auto` each
filmed ghost then gives way to the clean frame beside it (`no_proposal: "no interpolator"`), and
-only a jump left (`unmade`: the step, target and score the search stopped at) sets `why`, `rife`
-and `install`.
+only a jump left (`unmade`: the `frames`, `neighbours` and `off` of the group the search stopped at)
+sets `why`, `rife` and `install`.
`--repair off` cuts the loop as filmed and records `jump_repair: {"applied": false, "why":
"--repair off"}`. Other states are not touched (`"why": "not a gait state (…)"`).
-Checked on the 2026-10-03 takes (`retime.py` in the experiment folder is the reference): the
-engine replaces the same frames as the experiment on every take tried — Lite side E1
+Until the flow reading picked the frames, the size reading did: a step whose change of coverage,
+over the whole box or the hair behind the body, was at least 1.4 times the loop's median remade
+the frame after it, half way between its neighbours. Checked on the 2026-10-03 takes with it
+(`retime.py` in the experiment folder is the reference), that engine replaced the same frames as the experiment on every take tried — Lite side E1
[0, 16, 8] (score 1.75 → 1.42), Lite back-diagonal NE2 [13, 0] (1.60 → 1.43), Pro side E1
[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.
+Lite side E2. About 0.7 s a replaced frame on the Mac's GPU. Those takes have not been read with
+the flow reading.
### The flow reading — a frame off the walk's way, not a large step
@@ -267,8 +281,7 @@ amounts — a leg swung through moves far in one frame, a planted foot not at al
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.
+and speed instead, and `--repair auto` takes out the frames `flow_targets` names (above).
**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
@@ -296,23 +309,42 @@ every drawing, read frame by frame, and a median step that falls between the two
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`.
+a drawing a frame. A loop whose only large steps are the steps into and out of a few jumps can read
+as held to `held.measure` — its ordinary steps the repeats, its jumps the drawings; on those drawings
+its jumps would read as ordinary steps, and a drawing made again would stand for every frame of a
+run of five. Its runs are not its hold, so a hold is taken only where at least three in four runs
+(`HELD_RUNS`) show their drawing for the hold, a frame more or less (a slip); the loop is otherwise
+read a drawing a frame. A held loop's runs are its hold by construction.
+
+**Which frames.** `flow_targets` takes the worst drawing at or over `FLOW_LIMIT` (3.0) first. A
+group is one or two drawings in a row (`FLOW_SPAN`) that take it or lie beside it; its in-between is
+the straight line of the path from the drawing before the group to the drawing after, each drawing at
+its own time (the time rule above). Of the groups whose in-between brings every drawing from the one
+before them to the one after under the limit, the one taken is the one whose every drawing the
+in-between moves furthest (`move`: the least, over the group's drawings, of how far the in-between
+moves it in its worst window, in that window's usual steps). Those are the drawings off the flow;
+the drawings beside them read off only because a neighbour does, and a drawing the in-between
+hardly moves is not off at all. Ties go to the smaller result, then to the fewer drawings. 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), or
+one that shows a frame `fixed` names (the repair passes the frames already made, given way or
+refused). A drawing no group of up to two brings under the limit is `unfixed`.
+
+| Off the flow | The group taken | Not |
+|---|---|---|
+| one frame flung | that frame (on twos, the two frames that show it) | two frames with it: the in-between hardly moves the second |
+| two frames in a row flung together | both | the frame on either side of the pair: its in-between can bring the reading under the limit by smoothing the pair's edges, and leaves the pair standing — it moves half as far as the pair's own |
+| a part that snaps back at a wrap that does not close | the frame on one side of the wrap | two frames, which spread the snap over a frame the in-between moves two thirds as far |
+| two frames flung with one frame between them | each its own group, where the frame between reads under the limit once the first is made (flung 8 % of the body height on the synthetic walker) | flung farther (12 %), no group of up to two drawings straightens either while the other stands: the frames around them are `unfixed`, kept and named |
+
+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 `drawings` it takes (the frames that show each),
+its `neighbours` and each drawing's time `t`, the worst drawing's `off`, `turn`, `into`, `out` and
+`window` (fractions of the box, x0, y0, x1, y1), `move` and `off_after`; an `unfixed` entry its frames,
+the same readings and 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
@@ -1016,7 +1048,10 @@ repaired, aligned), it jumped at all three, so the take — not the resampling
The kept picks of both sets (Pro and Lite, five views each) and the refused Lite side take, from
their keyed frames through `video-loop --state walk --anchor motion-auto --body-height 400
--strip-height 640` and then `video-cycle-align` per set, on an M4 Max with the Apple GPU. The
-experiment's own scripts (`retime.py`, `finalize.py`) are the reference.
+experiment's own scripts (`retime.py`, `finalize.py`) are the reference. This is the 2.17 engine,
+whose jump repair picked its frames by the size reading (section 2, the end of its rules): the
+"Frames repaired" and "Jump score" columns are that reading's. The flow reading has not been run on
+this set.
| | Cut (start, length) | Frames repaired | Jump score before → after | Jolt index | Head sideways step, % | Warning |
|---|---|---|---|---|---|---|
diff --git a/docs/video-pipeline.md b/docs/video-pipeline.md
index 8ff1e0f..cd4d9a8 100644
--- a/docs/video-pipeline.md
+++ b/docs/video-pipeline.md
@@ -921,10 +921,12 @@ Gates, all fail-loud: no period (profile flat, below the recorded `periodicity_m
above `--seam-max` (2.0), GIF/WebP re-opened and checked (frame count, `loop=0`,
transparent corners, no RGB under alpha 0 in the WebP).
-A walk or run loop then has its jump frames repaired before the strip is built: a frame that
-breaks a step 1.4× the loop's median (whole body, or the hair behind it) is replaced by RIFE's
-frame between its two neighbours, at most three and never two side by side (`--repair auto`,
-the default; `--repair off` cuts as filmed). A frame the ghost screen names a filmed ghost, read on
+A walk or run loop then has its jump frames repaired before the strip is built: one or two
+drawings in a row that leave the loop's flow — 3× their region's usual step off the line between
+the frames either side, by direction and speed, not by the size of a step — are taken out and
+made again by RIFE between those frames, each at its own time so the loop keeps its length, at
+most three calls and never made from or beside a frame made (`--repair auto`, the default;
+`--repair off` cuts as filmed). A frame the ghost screen names a filmed ghost, read on
the cut as filmed, is replaced in the same stage first: by RIFE's frame between the two clean
frames beside it, else by the clean frame beside it, else kept and named (`ghost_given_way`,
`ghost_kept`) — a walk of one direction is delivered as cut and never meets the alignment that would
diff --git a/sprite_gen/video/batch.py b/sprite_gen/video/batch.py
index 643b637..8079cc0 100644
--- a/sprite_gen/video/batch.py
+++ b/sprite_gen/video/batch.py
@@ -804,7 +804,7 @@ def run_item(
result["loop"]["motion_anchor"] = lp["motion_anchor"]
if "rife" in (lp.get("jump_repair") or {}):
# cut as filmed for want of RIFE: the set report lists it under `warnings`
- result["loop"]["jump_repair"] = {k: lp["jump_repair"][k] for k in ("applied", "why", "score_max_before", "install")}
+ result["loop"]["jump_repair"] = {k: lp["jump_repair"][k] for k in ("applied", "why", "off_max_before", "install")}
result["ok"] = True
except SystemExit as exc:
result["ok"] = False
diff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.py
index 3003cbf..c0ac19d 100644
--- a/sprite_gen/video/loop.py
+++ b/sprite_gen/video/loop.py
@@ -893,12 +893,13 @@ def shown_runs(cells: list[Image.Image]) -> int:
def _repair_jumps(frames: list[Image.Image], interpolate: rife_mod.Interpolate | None, *, facing: str,
required: bool, screen: dict[str, Any]) -> tuple[list[Image.Image], dict[str, Any]]:
"""`repair_mod.repair_jumps` on the cut as filmed and its ghost `screen`, with RIFE located only
- once a frame is to be made: a loop without a jump or a ghost between two clean frames needs no
- binary. The report names the interpolator that made the frames.
+ once a frame is to be made: a loop with no frame off its flow and no ghost between two clean frames
+ needs no binary. The report names the interpolator that made the frames.
A frame to make and no RIFE installed: `required` lets `RifeNotInstalled` through; otherwise
- each filmed ghost gives way to the clean frame beside it, a jump stays as filmed, and the record
- says why where a jump was left (`rife`, `install`; `applied` false where nothing was replaced)."""
+ each filmed ghost gives way to the clean frame beside it, a jump (a frame off the flow) stays as
+ filmed, and the record says why where a jump was left (`rife`, `install`; `applied` false where
+ nothing was replaced)."""
made_by: list[dict[str, str]] = []
calls = 0
@@ -1441,15 +1442,21 @@ def run_loop(
for line in _ghost_lines(report_base["jump_repair"]):
print(f"video-loop: warning: {line}", file=sys.stderr)
for r in report_base["jump_repair"].get("rounds", []):
- if r["outcome"] == "accepted" and r["look"]:
- print(f"video-loop: warning: frame {r['target']} was {'given way for a filmed ghost' if r['why'] == 'ghost' else 'repaired'} "
- "with RIFE's frame between its neighbours, which may "
- f"cross-fade two drawings inside its outline (crossfade {r['proposal']['crossfade']:.4f}); kept, a reading to "
+ if r["outcome"] != "accepted" or not r["look"]:
+ continue
+ # A ghost round made one frame; a flow round a frame a drawing it took, each read on its own.
+ looked = ([(f"frame {r['target']} was given way for a filmed ghost", r["proposal"])] if r["why"] == "ghost" else
+ [(f"frame{'s' if len(m['frames']) > 1 else ''} {', '.join(map(str, m['frames']))} "
+ f"{'were' if len(m['frames']) > 1 else 'was'} repaired", m["proposal"]) for m in r["made"] if m["look"]])
+ for what, proposal in looked:
+ print(f"video-loop: warning: {what} with RIFE's frame between its neighbours, which may "
+ f"cross-fade two drawings inside its outline (crossfade {proposal['crossfade']:.4f}); kept, a reading to "
"look at — see it in the loop, or cut it with --repair off (docs/loop-repair.md section 4)", file=sys.stderr)
if "rife" in report_base["jump_repair"]:
- print(f"video-loop: warning: a jump frame was not repaired ({report_base['jump_repair']['score_max_before']:.2f}x "
- f"the median step) — RIFE is not installed, so the loop is cut as filmed; run `{rife_mod.INSTALL_COMMAND}` "
- "and cut it again (docs/loop-repair.md)", file=sys.stderr)
+ unmade = report_base["jump_repair"]["unmade"]
+ print(f"video-loop: warning: a jump frame was not repaired (frames {unmade['frames']}, {unmade['off']:.2f}x its "
+ "region's usual step off the line between its neighbours) — RIFE is not installed, so the loop is cut as filmed; "
+ f"run `{rife_mod.INSTALL_COMMAND}` and cut it again (docs/loop-repair.md)", file=sys.stderr)
else:
report_base["jump_repair"] = {"applied": False, "why": "--repair off" if repair == "off" else f"not a gait state ({state})"}
if prof.gait:
@@ -1672,10 +1679,10 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--body-height", type=int, help="scale so the STANDING height (the subject in the clip's first frame, i.e. the base still's pose) is this many px — the same value across states gives the same character size; --strip-height stays the cap")
parser.add_argument("--anchor", choices=ANCHOR_MODES, default=None, help="motion-auto: automatic stable regions, local repeat selection and XY ramp (walk/run); motion: fixed cut with explicit regions; body (default for walk/run): measure the last-to-first head-and-torso offset once and spread it as a ramp over the cycle; feet: remove in-canvas drift (a straight-line trend) so every cell stands on the mean foot line; none: leave placement as filmed (default for other states)")
parser.add_argument("--anchor-region", type=motion_anchor.parse_region, action="append", help="motion anchor only: repeat twice with head then torso x0,y0,x1,y1 in the first selected frame; requires --cycle fixed and at least 6 frames")
- parser.add_argument("--repair", choices=REPAIR_MODES, default="auto", help="auto (default): propose RIFE's frame between the neighbours of a jump (a step 1.4x the median, whole body or the hair behind it); adopt only without smear/outline faults, at most 3 calls and never two adopted frames side by side (docs/loop-repair.md). Rejected proposals keep the original. Missing RIFE keeps the filmed loop with a warning (`sprite-gen rife install`); on: the same repair, but no RIFE fails the loop; off: cut as filmed")
+ parser.add_argument("--repair", choices=REPAIR_MODES, default="auto", help="auto (default): take out the frames off the walk's flow (one or two drawings that lie 3x their region's usual step off the line between the frames either side) and make them again with RIFE between those frames, each at its own time, so the loop keeps its length; adopt only without smear/outline faults, at most 3 calls and never made from or beside a frame made (docs/loop-repair.md section 2). A rejected group keeps its frames. Missing RIFE keeps the filmed loop with a warning (`sprite-gen rife install`); on: the same repair, but no RIFE fails the loop; off: cut as filmed")
parser.add_argument("--jolt-max", type=float, default=None, help=f"walk/run: fail the repaired loop when its jolt index (how far each step strays from its neighbours' mean, over the median step) exceeds this. Default: no gate — the index is reported and a value over {repair_mod.JOLT_REFERENCE} is a warning line")
parser.add_argument("--head-step-max", type=float, default=None, help=f"walk/run: fail the repaired loop when the head's largest sideways move in one frame exceeds this %% of the body height. Default: no gate — reported, and over {repair_mod.HEAD_STEP_REFERENCE} is a warning line")
- parser.add_argument("--facing", choices=FACINGS, default="right", help="which way the body faces in the frames (default right): the hair the jump search watches is behind it")
+ parser.add_argument("--facing", choices=FACINGS, default="right", help="which way the body faces in the frames (default right): the jolt index's hair, and the size reading video-loop-compare's jump guard reads, are behind it; the jump repair reads the flow either way")
parser.add_argument("--size-hold", choices=SIZE_HOLD_MODES, default="auto", help="--anchor motion-auto: auto (default) scales a clip whose height, read one cycle on (the same pose a cycle later), changes by 1 %% or more over the clip back to its first frame's size before the cycle search, so the loop's last frame is the size of its first (recorded as size_hold, with the evidence); off: search the frames as filmed")
parser.add_argument("--steps", type=int, choices=STEPS, default=None,
help="--anchor motion-auto: how many steps the cut it takes without this holds, as counted by whoever looked "
@@ -1727,7 +1734,7 @@ def run(**kwargs: object) -> int:
if payload.get(key):
summary[key] = payload[key]
if payload.get("jump_repair", {}).get("replaced"):
- summary["jump_repair"] = {k: payload["jump_repair"][k] for k in ("replaced", "score_max_before", "score_max_after")}
+ summary["jump_repair"] = {k: payload["jump_repair"][k] for k in ("replaced", "off_max_before", "off_max_after")}
summary["strip"] = {k: payload["strip"][k] for k in ("path", "frames", "w", "h", "body_h", "delay_ms")}
print(json.dumps(summary, ensure_ascii=False, indent=2))
return 0
diff --git a/sprite_gen/video/repair.py b/sprite_gen/video/repair.py
index 6f0123a..7c041e0 100644
--- a/sprite_gen/video/repair.py
+++ b/sprite_gen/video/repair.py
@@ -1,13 +1,15 @@
# SPDX-License-Identifier: Apache-2.0
-"""Jump frames in a walk loop, found by how much the body's coverage changes, replaced by RIFE.
+"""Frames off a walk loop's flow, found by direction and speed, taken out and made again by RIFE.
A video model redraws thin hair a little differently every frame, and now and then a ponytail
-lands somewhere it was not one frame earlier: one step of the loop changes far more than the
-loop's usual step. That step is a jump; the frame after it is replaced by the frame RIFE makes
-half-way between its two neighbours, and every other frame stays the video's own
-(docs/loop-repair.md section 2). Re-making every frame instead (an offset of half a frame) also
+lands somewhere it was not one frame earlier, or a tail snaps back at a wrap that does not close:
+a frame drawn where the flow does not go. The flow reading (`flow_scores`, `flow_targets`) finds
+it by how far it lies off the line between its neighbours, in the usual steps of the region it is
+read in; the frames off the flow, one or two drawings in a row, are taken out and made again by
+RIFE between the frames either side, each at its own time, and every other frame stays the video's
+own (docs/loop-repair.md section 2). Re-making every frame instead (an offset of half a frame) also
softens the frames that were fine, and was judged "not corrected" (2026-10-03). A frame the
-ghost screen names a filmed ghost is replaced in the same stage, before the jumps are read: by
+ghost screen names a filmed ghost is replaced in the same stage, before the flow is read: by
RIFE's frame between its neighbours where both are clean and it has no fault, else by the clean
frame beside it (docs/loop-repair.md section 4).
@@ -15,13 +17,14 @@ Measured on the loop as it plays — cyclic, the last frame followed by the firs
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").
+The size reading (`jump_scores`) counts how much a step changes, whole body and hair behind it.
+It picked the frames until the flow reading did, and names a fast swing a jump; the jump guard of
+`video-loop-compare` still reads it (docs/loop-comparison.md, "The jump guard").
"""
from __future__ import annotations
+from collections.abc import Iterable
from typing import Any
from PIL import Image
@@ -31,13 +34,12 @@ 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
-# A step this many times the loop's median step (whole body, or the hair behind it) is a jump.
-JUMP_RATIO = 1.4
-# Interpolation calls at most per loop, including rejected proposals. A loop that needs more is jolting everywhere, not jumping
-# once, and a few made frames do not fix it (the jolt index, section 3, says so instead).
+# Interpolation calls at most per loop, a drawing made one call, including rejected proposals. A loop that needs more is
+# jolting everywhere, not jumping once, and a few made frames do not fix it (the jolt index, section 3, says so instead).
MAX_REPAIRS = 3
# The hair behind a right-facing body, below the head, as fractions of the union box: where a
-# ponytail cut at the wrong moment jumps. A left-facing body has it on the other side.
+# ponytail cut at the wrong moment jumps (the size reading, and the jolt index's hair). A left-facing
+# body has it on the other side.
HAIR_BOX_RIGHT = (0.0, 0.30, 0.45, 0.80)
ALPHA_SOLID = 8 # alpha at or above this is body, as everywhere in video-loop
BOX_MARGIN = 8 # px around the union box, the strip cells' own side margin
@@ -74,7 +76,8 @@ def steps(alphas: list[np.ndarray], frac: tuple[float, float, float, float] | No
def jump_scores(frames: list[Image.Image], *, facing: str = "right", box: tuple[int, int, int, int] | None = None) -> dict[str, Any]:
- """Per step: the whole body's change and the hair's, each over its own median; the score is the larger."""
+ """The size reading, per step: the whole body's change and the hair's, each over its own median; the score
+ is the larger. The jump guard of `video-loop-compare` reads it (`restoration.jump`); the repair reads the flow."""
al = coverage(frames, box or union_box(frames))
whole, hair = steps(al), steps(al, hair_box(facing))
mw, mh = float(np.median(whole)), float(np.median(hair))
@@ -95,6 +98,9 @@ FLOW_BLUR = 0.03 # the blur's sigma, of the body height: a shape moved one ordi
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
+# The share of a held loop's runs that show their drawing for the hold, a frame more or less (a slip): under it the
+# runs are not the hold, and the loop is read a drawing a frame (`flow_drawings`).
+HELD_RUNS = 0.75
_LUMA = np.array([0.299, 0.587, 0.114])
@@ -168,7 +174,13 @@ def flow_drawings(states: np.ndarray) -> tuple[list[list[int]], int]:
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."""
+ frame's drawing. A loop drawn every frame (hold 1) is a drawing a frame.
+
+ A loop whose only large steps are the steps into and out of a few jumps can read as held there: its
+ ordinary steps the repeats, its jumps the drawings. On those drawings its jumps would read as ordinary
+ steps, and a drawing made again would stand for every frame of a run of five. Its runs are not its
+ hold: a hold is taken only where at least HELD_RUNS of the runs are the hold, a frame more or less,
+ and the loop is otherwise read 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.
@@ -185,6 +197,8 @@ def flow_drawings(states: np.ndarray) -> tuple[list[list[int]], int]:
runs[-1].append(t)
else:
runs.append([t])
+ if sum(abs(len(run) - hold) <= 1 for run in runs) < HELD_RUNS * len(runs):
+ return [[t] for t in range(n)], 1
return runs, hold
@@ -227,24 +241,42 @@ def flow_scores(frames: list[Image.Image], *, box: tuple[int, int, int, int] | N
return {**{k: v[of] for k, v in per.items()}, "windows": flow["fractions"], "hold": flow["hold"]}
+def between_time(a: int, frame: int, b: int, count: int) -> float:
+ """The time of `frame` on the way from frame `a` to frame `b` of a loop `count` frames long, 0..1, in play
+ order (the wrap included): a frame made there shows the pose at its own time, so the loop keeps its length,
+ every frame its time, and a drawing held on twos its two frames."""
+ return ((frame - a) % count) / ((b - a) % count)
+
+
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]:
+ box: tuple[int, int, int, int] | None = None, fixed: Iterable[int] = ()) -> 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."""
+ The worst drawing at or over `limit` first. A group is up to `span` drawings in a row that take that
+ drawing or lie beside it; its in-between is the straight line of the path from the drawing before the
+ group to the drawing after, each drawing at its own time (`between_time`). Of the groups whose in-between
+ brings every drawing from the one before them to the one after under `limit`, the one taken is the one
+ whose every drawing the in-between moves furthest (`move`, the least over its drawings of the move in its
+ worst window, in the window's usual steps): the drawings off the flow, not the ones beside them that read
+ off only because a neighbour is, and no drawing the in-between hardly moves. A pair flung together is taken
+ out whole, where an in-between beside it would bring the reading under `limit` by smoothing its edges and
+ leave it standing; a part that snaps back at the wrap is one frame on either side of it, where two would
+ spread the snap over a frame the in-between hardly moves. Ties go to the smaller result, then the fewer
+ drawings. 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, or a drawing that shows a frame in `fixed`
+ (made, given way or refused already). A drawing no group brings under `limit` is `unfixed`.
+
+ Each group: its `frames` in play order, the `drawings` it takes (the frames that show each), the
+ `neighbours` it is made from (the first frame of the drawing before it and of the drawing after), each
+ drawing's time `t` between them, `off` (the worst of its drawings before) with its `turn`, `into`, `out` and
+ `window`, `move`, 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)
+ n, count = len(runs), len(frames)
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:
@@ -254,42 +286,49 @@ def flow_targets(frames: list[Image.Image], *, limit: float = FLOW_LIMIT, span:
def reading(path: np.ndarray) -> np.ndarray:
return (_flow_read(path, windows)[0] / scale).max(axis=1)
+ def moved(made: np.ndarray, path: np.ndarray, group: list[int]) -> float:
+ return min(max(float(np.linalg.norm(made[g, y0:y1, x0:x1] - path[g, y0:y1, x0:x1]) / scale[i])
+ for i, (y0, y1, x0, x1) in enumerate(windows)) for g in group)
+
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()
+ of = {t: d for d, run in enumerate(runs) for t in run}
+ taken = {of[t] for t in fixed}
+ path, unfixed = flow["path"].copy(), 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]] = []
+ tried: list[tuple[float, float, list[int], int, int, np.ndarray]] = []
for size in range(1, min(span, n - 2) + 1):
- for start in range(d - size + 1, d + 1):
+ # the groups of `size` that take d or lie beside it: d is between the drawing before them and the one after
+ for start in range(d - size, d + 2):
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])
+ for g in group:
+ made[g] = path[a] + between_time(runs[a][0], runs[g][0], runs[b][0], count) * (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
+ tried.append((float(max(after[(a + i) % n] for i in range(size + 2))), moved(made, path, group), group, a, b, made))
+ ok = [x for x in tried if x[0] < limit]
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])
+ result, move, group, a, b, made = max(ok, key=lambda x: (round(x[1], 9), -x[0], -len(x[2])))
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)})
+ record["groups"].append({"frames": [t for g in group for t in runs[g]], "drawings": [runs[g] for g in group],
+ "neighbours": [runs[a][0], runs[b][0]],
+ "t": [round(between_time(runs[a][0], runs[g][0], runs[b][0], count), 4) for g in group],
+ **said(worst), "move": round(move, 4), "off_after": round(result, 4)})
taken |= set(group)
path, current = made, reading(made)
record["off_max_after"] = round(float(current.max()), 4)
@@ -334,38 +373,41 @@ def _give_way(frames: list[Image.Image], j: int, ghosts: dict[int, float], inter
def repair_jumps(frames: list[Image.Image], interpolate: Interpolate | None, *, facing: str = "right",
- ratio: float = JUMP_RATIO, max_frames: int = MAX_REPAIRS,
+ limit: float = FLOW_LIMIT, span: int = FLOW_SPAN, max_frames: int = MAX_REPAIRS,
screen: dict[str, Any] | None = None) -> tuple[list[Image.Image], dict[str, Any]]:
- """Replace each filmed ghost the screen names, then the frame that breaks each jump with RIFE's
- frame between its neighbours, worst jump first.
+ """Replace each filmed ghost the screen names, then take out each group of frames off the loop's flow and
+ make it again with RIFE between the frames either side, worst first (docs/loop-repair.md section 2).
`screen` is the ghost screen of `frames` as filmed (`interpolation_quality.ghost_screen`, read
here when not given). Each ghost it names is a round of its own (`why` ghost, in frame order,
outside the call budget): RIFE's frame between its two neighbours where both are clean and the
frame has no fault, else the clean frame beside it (the frame after it, else the one before it),
- else, both being filmed ghosts too, the ghost kept (`_give_way`). The jumps are then read on
- the loop as the ghosts left it (`why` jump): at most `max_frames` calls, and never next to a
- frame already made or given way: two made frames side by side are made from each other and
- melt the legs. A proposal with a shared interpolation-quality fault — a ghost too, on its own
- coverage, where the screen reads the loop — keeps the original middle frame; a proposal that
- cross-fades two drawings inside its silhouette is still taken, its round naming it (`look`).
- Blocked and rejected targets do not end the search for independent targets. `interpolate` may
- be None: a ghost then gives way to the clean frame beside it, and the jump search stops at the
- first frame it would make, naming it (`unmade`). Scores are re-read after each replacement, on
- the union box of the original loop."""
+ else, both being filmed ghosts too, the ghost kept (`_give_way`). The flow is then read on the
+ loop as the ghosts left it (`flow_targets`, `why` flow): the worst group first, one call a drawing
+ it takes, each drawing made at its own time between the group's neighbours (`between_time`) and
+ shown on every frame the drawing was — the loop keeps its length, every frame its time, a drawing
+ held on twos its two frames. At most `max_frames` calls; a group the calls left cannot pay for
+ stops the stage (`left`). Never made from or beside a frame already made or given way: two made
+ frames side by side are made from each other and melt the legs. A group whose made drawings carry
+ a shared interpolation-quality fault — a ghost too, on its own coverage, where the screen reads
+ the loop — keeps every frame it would take, as filmed, and nothing is made from or beside them
+ (`refused`); a made drawing that cross-fades two drawings inside its silhouette is still taken,
+ its round naming it (`look`). `interpolate` may be None: a ghost then gives way to the clean frame
+ beside it, and the flow search stops at the first group it would make, naming it (`unmade`). The
+ flow is read again after each group, on the union box of the original loop. `facing` reads nothing
+ here: it is recorded for the jump guard of `video-loop-compare` (`restoration.jump`)."""
out = list(frames)
n = len(out)
box = union_box(frames)
screen = screen if screen is not None else ghost_screen(frames)
reads = bool(screen["reads"])
- first = jump_scores(out, facing=facing, box=box)
record: dict[str, Any] = {
- "ratio": ratio, "max_frames": max_frames, "facing": facing, "hair_box": list(hair_box(facing)),
- "score_max_before": round(float(first["score"].max()), 4), "replaced": [], "rounds": [],
- "blocked": [], "attempts": 0,
+ "reading": "flow", "limit": limit, "span": span, "max_frames": max_frames, "facing": facing,
+ "off_max_before": round(float(flow_scores(frames, box=box)["off"].max()), 4), "replaced": [], "rounds": [],
+ "refused": [], "attempts": 0,
}
if n < 4:
- record.update(stopped="loop shorter than 4 frames", score_max_after=record["score_max_before"])
+ record.update(stopped="loop shorter than 4 frames", off_max_after=record["off_max_before"])
return out, record
replaced: list[int] = []
ghosts = {g["frame"]: g["ghost"] for g in screen["ghosts"]}
@@ -374,61 +416,55 @@ def repair_jumps(frames: list[Image.Image], interpolate: Interpolate | None, *,
record["rounds"].append(round_)
if "replaced" in round_:
replaced.append(j)
- attempted: set[int] = set()
- blocked: set[int] = set()
- stopped = f"{max_frames} interpolation calls used"
- scores = jump_scores(out, facing=facing, box=box) if replaced else first
- for _ in range(max_frames):
- selected = None
- for k0 in np.argsort(-scores["score"], kind="stable"):
- k = int(k0)
- score = float(scores["score"][k])
- if score < ratio:
- break
- # Two jumps around a stray frame point back to that frame; a single cut points
- # to the frame after the step. This is the existing target rule, worst first.
- before, after = float(scores["score"][(k - 1) % n]), float(scores["score"][(k + 1) % n])
- j = k if before >= ratio and before > after else (k + 1) % n
- if j in replaced or (j - 1) % n in replaced or (j + 1) % n in replaced:
- if j not in blocked:
- record["blocked"].append({"target": j, "reason": "already-made-or-adjacent"})
- blocked.add(j)
- continue
- if j in attempted:
- continue
- selected = (k, j, score)
+ refused: list[int] = []
+ calls = 0
+ while True:
+ plan = flow_targets(out, limit=limit, span=span, box=box, fixed=[*replaced, *refused])
+ record.setdefault("hold", plan["hold"])
+ record.setdefault("drawings", plan["drawings"])
+ if not plan["groups"]:
+ stopped = ("no frame off the flow" if not plan["unfixed"] else
+ f"no group of up to {span} drawings brings the frames left off the flow under {limit:g} (`unfixed`)")
break
- if selected is None:
- stopped = (f"no step at or above {ratio}x the median" if float(scores["score"].max()) < ratio
- else "no independent unattempted target; remaining targets rejected or next to a frame already made")
+ group = plan["groups"][0]
+ need = len(group["drawings"])
+ if calls + need > max_frames:
+ stopped = (f"{max_frames} interpolation calls used" if calls >= max_frames else
+ f"the next group needs {need} interpolation calls, {max_frames - calls} left")
+ record["left"] = [{"frames": g["frames"], "off": g["off"]} for g in plan["groups"]]
break
- k, j, score = selected
if interpolate is None:
- record["unmade"] = {"step": [k, (k + 1) % n], "target": j, "score": round(score, 4)}
- stopped = "a frame to make after a jump and no interpolator"
+ record["unmade"] = {k: group[k] for k in ("frames", "neighbours", "off")}
+ stopped = "a frame to make off the flow and no interpolator"
break
- a, b = out[(j - 1) % n], out[(j + 1) % n]
- made = interpolate(a, b, 0.5)
- if made.mode != "RGBA" or made.size != out[j].size:
- raise ValueError("repair interpolator must return an RGBA frame of the original size")
- attempted.add(j)
- measure = {**smear(made, a, b), "ghost": ghost(made) if reads else None, "crossfade": crossfade(made, a, b, 0.5)}
- wrong = faults(measure)
- if not made.getchannel("A").getbbox():
- wrong.append("empty")
- record["rounds"].append({"why": "jump", "step": [k, (k + 1) % n], "target": j, "score": round(score, 4),
- "whole": round(float(scores["whole"][k]), 4), "hair": round(float(scores["hair"][k]), 4),
- "original": {**smear(out[j], a, b), "ghost": ghost(out[j]) if reads else None},
- "proposal": measure, "faults": wrong, "look": looks(measure),
- "outcome": "rejected" if wrong else "accepted", **({"replaced": j} if not wrong else {})})
- if not wrong:
- out[j] = made
- replaced.append(j)
- scores = jump_scores(out, facing=facing, box=box)
- record["replaced"] = replaced
- record["attempts"] = len(attempted)
- record["stopped"] = stopped
- record["score_max_after"] = round(float(scores["score"].max()), 4)
+ ia, ib = group["neighbours"]
+ a, b = out[ia], out[ib]
+ made: list[tuple[list[int], Image.Image, dict[str, Any]]] = []
+ for drawing in group["drawings"]:
+ t = between_time(ia, drawing[0], ib, n)
+ frame = interpolate(a, b, t)
+ if frame.mode != "RGBA" or frame.size != out[drawing[0]].size:
+ raise ValueError("repair interpolator must return an RGBA frame of the original size")
+ measure = {**smear(frame, a, b), "ghost": ghost(frame) if reads else None, "crossfade": crossfade(frame, a, b, t)}
+ wrong = faults(measure) + ([] if frame.getchannel("A").getbbox() else ["empty"])
+ made.append((drawing, frame, {
+ "frames": drawing, "t": round(t, 4), "proposal": measure, "faults": wrong, "look": looks(measure),
+ "original": {**smear(out[drawing[0]], a, b), "ghost": ghost(out[drawing[0]]) if reads else None}}))
+ calls += need
+ wrong = sorted({f for *_, m in made for f in m["faults"]})
+ round_ = {"why": "flow", **group, "made": [m for *_, m in made], "faults": wrong,
+ "look": sorted({w for *_, m in made for w in m["look"]}), "outcome": "rejected" if wrong else "accepted"}
+ if wrong:
+ refused.extend(group["frames"])
+ else:
+ for drawing, frame, _ in made:
+ for k in drawing:
+ out[k] = frame
+ replaced.extend(group["frames"])
+ round_["replaced"] = group["frames"]
+ record["rounds"].append(round_)
+ record.update(replaced=replaced, refused=refused, attempts=calls, stopped=stopped, unfixed=plan["unfixed"],
+ off_max_after=plan["off_max_before"])
return out, record
diff --git a/sprite_gen/video/restoration.py b/sprite_gen/video/restoration.py
index b1cfb56..797dffc 100644
--- a/sprite_gen/video/restoration.py
+++ b/sprite_gen/video/restoration.py
@@ -13,9 +13,10 @@ Source correspondence, proposal generation and final acceptance are separate.
A failed independent proposal never hides the next one; a missing shared source
bridge stops the operation. All quality measurements consume final pixels.
-A target is a cell the jump repair replaced because a step into or out of the
-source frame there jumped. Restoring that frame's pixels can restore the jump:
-acceptance also reads the jump repair's own step score around the changed cell.
+A target is a cell the jump repair replaced because the source frame there left
+the loop's flow. Restoring that frame's pixels can restore the jump: acceptance
+also reads the size reading's step score (`repair.jump_scores`) around the
+changed cell.
The jump repair also replaces a filmed ghost, a frame the ghost screen names, and
restoring it would deliver the ghost again: a cell whose source frame the cut's
screen names is never a target, and acceptance reads the ghost on final pixels.
@@ -262,7 +263,7 @@ def _status(pairs: list[tuple[float, float]]) -> str:
def jump(before: list[Image.Image], after: list[Image.Image], ref: list[Image.Image], changed: list[int],
facing: str | None) -> dict[str, Any]:
- """The jump repair's step score (`repair.jump_scores`) on the two steps into and out of each changed cell.
+ """The size reading's step score (`repair.jump_scores`) on the two steps into and out of each changed cell.
Both loops are scored on one box, the source cells' union box (the jump repair reads the box of
the loop as filmed), with the facing the repair recorded. A cell's reading is the larger of its
diff --git a/tests/video/test_crossfade.py b/tests/video/test_crossfade.py
index 133de30..ab08051 100644
--- a/tests/video/test_crossfade.py
+++ b/tests/video/test_crossfade.py
@@ -25,6 +25,7 @@ from PIL import Image, ImageDraw
from sprite_gen.video import align, repair, rife
from sprite_gen.video.interpolation_quality import CROSSFADE_LOOK, faults, looks
from tests.video.test_ghost_screen import _band, _block_walker, _cut
+from tests.video.test_loop_repair import forced_flow_group
GREY, BLACK = (125, 118, 112), (20, 20, 20)
LIGHT_BOOTS = (225, 210, 180)
@@ -171,12 +172,11 @@ def test_jump_repair_takes_a_crossfaded_proposal_and_names_it(monkeypatch):
sa, sb = (10, -10), (5, -5)
a, b, drawn, made = _inside(sa, sb, 0.5)
frames = [a, _walker(20, -20), b, _walker(8, -8)]
- scores = np.array([3., 2., 1., 1.])
- monkeypatch.setattr(repair, "jump_scores", lambda *x, **kw: {k: scores for k in ("whole", "hair", "score")})
+ forced_flow_group(monkeypatch, [1], (0, 2), [0.5])
out, record = repair.repair_jumps(frames, lambda x, y, t: made)
first = record["rounds"][0]
assert first["outcome"] == "accepted" and first["faults"] == [] and first["look"] == ["crossfade"]
- assert first["proposal"]["crossfade"] > CROSSFADE_LOOK and out[1] is made
+ assert first["made"][0]["proposal"]["crossfade"] > CROSSFADE_LOOK and out[1] is made
@pytest.mark.real_rife
diff --git a/tests/video/test_ghost_screen.py b/tests/video/test_ghost_screen.py
index 88049ad..f85f7ff 100644
--- a/tests/video/test_ghost_screen.py
+++ b/tests/video/test_ghost_screen.py
@@ -23,6 +23,7 @@ from sprite_gen.video import loop as loop_mod
from sprite_gen.video import repair
from sprite_gen.video.interpolation_quality import GHOST_WARN, faults, ghost_screen
from tests.video.test_cycle_align import _walker as _block_walker
+from tests.video.test_loop_repair import forced_flow_group
from tests.video.test_rife import _walker
@@ -190,11 +191,11 @@ def test_jump_repair_rejects_a_proposal_that_carries_a_ghost(monkeypatch):
from: the jump repair gives it way first, tests/video/test_ghost_given_way.py.)"""
frames = [_walker(20, -20), _walker(8, -8), _walker(-5, 5), _walker(10, -10)]
before = [f.tobytes() for f in frames]
- scores = np.array([3., 2., 1., 1.])
- monkeypatch.setattr(repair, "jump_scores", lambda *a, **kw: {k: scores for k in ("whole", "hair", "score")})
+ forced_flow_group(monkeypatch, [1], (0, 2), [0.5])
out, record = repair.repair_jumps(frames, lambda a, b, t: _band(_walker(8, -8)))
- assert record["replaced"] == [] and record["rounds"][0]["why"] == "jump" and "ghost" in record["rounds"][0]["faults"]
- assert record["rounds"][0]["proposal"]["ghost"] > GHOST_WARN and record["rounds"][0]["original"]["ghost"] == 0
+ (round_,) = record["rounds"]
+ assert record["replaced"] == [] and round_["why"] == "flow" and "ghost" in round_["faults"]
+ assert round_["made"][0]["proposal"]["ghost"] > GHOST_WARN and round_["made"][0]["original"]["ghost"] == 0
assert [f.tobytes() for f in out] == before
diff --git a/tests/video/test_loop_flow.py b/tests/video/test_loop_flow.py
index e737dc4..50da080 100644
--- a/tests/video/test_loop_flow.py
+++ b/tests/video/test_loop_flow.py
@@ -4,6 +4,8 @@ the path its neighbours draw — against the way a part is going, or a sudden ch
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 repair (`repair.repair_jumps`) takes those frames out and makes them again between the frames
+either side, each at its own time: the loop keeps its length, and a loop on twos its hold.
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."""
@@ -12,12 +14,14 @@ from __future__ import annotations
import math
+import numpy as np
import pytest
from PIL import Image, ImageDraw, ImageOps
from sprite_gen.video import repair
W, H, N = 240, 300, 36
+SIZE_JUMP = 1.4 # a step this many times the loop's median: the size reading's jump, which picked frames before the flow reading
def _frame(t: int, n: int, *, tail_off: float = 0.0, tail_lag: float = 0.0) -> Image.Image:
@@ -64,7 +68,7 @@ def test_an_ordinary_walk_has_no_frame_off_its_flow_where_the_size_reading_names
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
+ assert (repair.jump_scores(frames)["score"] >= SIZE_JUMP).sum() >= 5
def test_a_frame_flung_against_the_sway_is_the_one_frame_taken():
@@ -112,6 +116,15 @@ def test_two_flung_frames_in_a_row_are_one_group_of_two():
assert [sorted(g["frames"]) for g in record["groups"]] == [[10, 11]]
+def test_two_frames_flung_with_one_between_are_two_groups_or_named_unfixed():
+ # One made, the frame between reads under the limit: each its own group. Flung farther, the frame between still
+ # reads over it while the other stands, no group of up to two straightens either, and they are kept, named.
+ record = repair.flow_targets(_loop(flung={12: 20, 14: 20}))
+ assert sorted(g["frames"] for g in record["groups"]) == [[12], [14]] and record["unfixed"] == []
+ record = repair.flow_targets(_loop(flung={12: 30, 14: 30}))
+ assert record["groups"] == [] and {12, 13, 14} <= {t for u in record["unfixed"] for t in u["frames"]}
+
+
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"] == []
@@ -138,3 +151,115 @@ def test_a_loop_too_short_to_read_is_left_alone():
def test_a_loop_with_no_body_raises():
with pytest.raises(ValueError, match="fully transparent"):
repair.flow_states([Image.new("RGBA", (40, 40))] * 6)
+
+
+# --- the repair: the frames off the flow taken out and made again (docs/loop-repair.md section 2) ----------------
+
+
+class Between:
+ """A stand-in RIFE: the walker as drawn at the time t of the way from frame a to frame b of `filmed` (found
+ by identity), with no tail flung. Records each call as (a, b, t) and keeps what it made. (The walker's own
+ frames 10 and 34 read a smear against their neighbours — the arm drawn over the torso's outline — so the
+ frames flung here are others.)"""
+
+ def __init__(self, filmed: list[Image.Image], n: int = N):
+ self.at = {id(f): k for k, f in enumerate(filmed)}
+ self.n = n
+ self.calls: list[tuple[int, int, float]] = []
+ self.made: list[Image.Image] = []
+
+ def __call__(self, a: Image.Image, b: Image.Image, t: float) -> Image.Image:
+ ka, kb = self.at[id(a)], self.at[id(b)]
+ self.calls.append((ka, kb, round(t, 4)))
+ self.made.append(_frame(ka + t * ((kb - ka) % self.n), self.n))
+ return self.made[-1]
+
+
+def test_the_repair_leaves_an_ordinary_walk_alone_where_the_size_reading_names_jumps():
+ frames = _loop()
+ between = Between(frames)
+ out, record = repair.repair_jumps(frames, between)
+ assert record["replaced"] == [] and between.calls == [] and all(o is f for o, f in zip(out, frames))
+ assert record["off_max_before"] == record["off_max_after"] < repair.FLOW_LIMIT
+ assert (repair.jump_scores(frames)["score"] >= SIZE_JUMP).sum() >= 5
+
+
+def test_the_repair_takes_the_flung_frame_out_and_makes_it_again_between_its_neighbours():
+ frames = _loop(flung={12: 12})
+ between = Between(frames)
+ out, record = repair.repair_jumps(frames, between)
+ assert record["replaced"] == [12] and between.calls == [(11, 13, 0.5)]
+ assert len(out) == N and out[12] is between.made[0]
+ assert all(out[k] is frames[k] for k in range(N) if k != 12) # every other frame stays the video's own
+ (round_,) = record["rounds"]
+ assert round_["why"] == "flow" and round_["outcome"] == "accepted" and round_["frames"] == [12]
+ assert round_["neighbours"] == [11, 13] and round_["t"] == [0.5] and round_["turn"] < 0
+ assert record["off_max_before"] >= repair.FLOW_LIMIT > record["off_max_after"]
+
+
+def test_two_flung_frames_in_a_row_are_made_again_as_two_each_at_its_own_time():
+ frames = _loop(flung={12: 20, 13: 20})
+ between = Between(frames)
+ out, record = repair.repair_jumps(frames, between)
+ assert record["replaced"] == [12, 13] and record["attempts"] == 2
+ assert between.calls == [(11, 14, 0.3333), (11, 14, 0.6667)] # a third and two thirds of the way: their own times
+ assert len(out) == N and out[12] is between.made[0] and out[13] is between.made[1]
+
+
+def test_on_twos_a_flung_drawing_is_made_once_and_shown_for_both_its_frames():
+ frames = _loop(flung={12: 20}, hold=2)
+ between = Between(frames)
+ out, record = repair.repair_jumps(frames, between)
+ # The drawing before shows from frame 10, the one after from frame 14: the drawing made is half way, held as filmed.
+ assert record["replaced"] == [12, 13] and between.calls == [(10, 14, 0.5)] and record["attempts"] == 1
+ assert out[12] is out[13] is between.made[0] and len(out) == N
+ assert all(out[k] is frames[k] for k in range(N) if k not in (12, 13))
+ assert record["rounds"][0]["drawings"] == [[12, 13]] and record["hold"] == 2
+
+
+def test_a_group_with_a_frame_at_fault_keeps_every_frame_it_would_take_and_is_not_tried_again():
+ frames = _loop(flung={12: 20, 13: 20})
+ between = Between(frames)
+
+ def melted(a: Image.Image, b: Image.Image, t: float) -> Image.Image:
+ made = between(a, b, t)
+ if t < 0.5:
+ return made
+ pixels = np.asarray(made).copy()
+ dark = (pixels[..., :3].max(axis=2) < 70) & (pixels[..., 3] > 0)
+ pixels[dark, :3] = (200, 200, 220) # the outlines melted into the fill
+ return Image.fromarray(pixels, "RGBA")
+
+ out, record = repair.repair_jumps(frames, melted)
+ assert record["replaced"] == [] and all(o is f for o, f in zip(out, frames))
+ (round_,) = record["rounds"]
+ assert round_["outcome"] == "rejected" and "outline" in round_["faults"] and round_["frames"] == [12, 13]
+ assert [m["faults"] for m in round_["made"]][0] == [] and "outline" in round_["made"][1]["faults"]
+ assert record["attempts"] == len(between.calls) == 2 # both calls spent; the group is not made again
+
+
+def test_the_calls_go_to_the_worst_frame_first_and_stop_at_the_budget():
+ frames = _loop(flung={4: 20, 14: 20, 24: 20, 32: 20})
+ between = Between(frames)
+ out, record = repair.repair_jumps(frames, between)
+ assert len(record["replaced"]) == record["attempts"] == repair.MAX_REPAIRS == len(between.calls)
+ assert set(record["replaced"]) < {4, 14, 24, 32} and record["stopped"] == f"{repair.MAX_REPAIRS} interpolation calls used"
+ offs = [r["off"] for r in record["rounds"]]
+ assert offs == sorted(offs, reverse=True)
+ (left,) = record["left"]
+ assert set(left["frames"]) | set(record["replaced"]) == {4, 14, 24, 32}
+
+
+def test_without_an_interpolator_the_first_group_is_named_and_nothing_is_made():
+ frames = _loop(flung={12: 12})
+ out, record = repair.repair_jumps(frames, None)
+ assert record["replaced"] == [] and all(o is f for o, f in zip(out, frames))
+ assert record["unmade"]["frames"] == [12] and record["unmade"]["off"] >= repair.FLOW_LIMIT
+ assert record["stopped"] == "a frame to make off the flow and no interpolator"
+
+
+def test_the_repair_reads_the_same_whichever_way_the_body_faces():
+ frames = [ImageOps.mirror(f) for f in _loop(flung={12: 12})]
+ calls: list[float] = []
+ out, record = repair.repair_jumps(frames, lambda a, b, t: calls.append(t) or ImageOps.mirror(_frame(12, N)))
+ assert record["replaced"] == [12] and calls == [0.5]
diff --git a/tests/video/test_loop_repair.py b/tests/video/test_loop_repair.py
index 28b7c3f..f24bf83 100644
--- a/tests/video/test_loop_repair.py
+++ b/tests/video/test_loop_repair.py
@@ -1,10 +1,11 @@
# SPDX-License-Identifier: Apache-2.0
-"""Jump-frame repair (docs/loop-repair.md section 2): only the frame after a jump is replaced,
-by the interpolator's frame between its two neighbours; at most three, never two side by side;
-the hair watched is behind the body whichever way it faces; and `video-loop` records what it
-replaced and gates the cells as they now play. When a frame needs making and no RIFE is
-installed, `--repair auto` cuts the loop as filmed with a warning and the install line, and
-`--repair on` refuses.
+"""Jump-frame repair (docs/loop-repair.md section 2): the frames off the loop's flow are taken out
+and made again by the interpolator between the frames either side, each at its own time; at most
+three calls, never made from or beside a frame made; and `video-loop` records what it replaced and
+gates the cells as they now play. The size reading (`jump_scores`, the hair behind the body
+whichever way it faces) is what the jump guard of `video-loop-compare` reads. When a frame needs
+making and no RIFE is installed, `--repair auto` cuts the loop as filmed with a warning and the
+install line, and `--repair on` refuses.
The interpolator is a stand-in that returns the true in-between of the synthetic loop, so the
tests need no binary and can say exactly which frame should come back."""
@@ -24,6 +25,7 @@ from sprite_gen.video import loop as loop_mod
from sprite_gen.video import repair
W, H, N = 120, 140, 24
+SIZE_JUMP = 1.4 # a step this many times the loop's median: the size reading's jump, which picked frames before the flow reading
def _frame(phase: float, *, tail_dx: int = 0, tail_side: str = "left", tail_jump: int = 0) -> Image.Image:
@@ -54,8 +56,9 @@ def _loop(jumps: dict[int, int] | None = None, *, side: str = "left") -> tuple[l
return filmed, truth
-class TrueMiddle:
- """Stand-in interpolator: the true frame between two frames of the synthetic loop."""
+class TrueBetween:
+ """Stand-in interpolator: the true frame of the synthetic loop at the time t of the way from one
+ frame to another (a time the loop has a frame for)."""
def __init__(self, filmed: list[Image.Image], truth: list[Image.Image]):
self.index = {id(f): k for k, f in enumerate(filmed)}
@@ -64,21 +67,34 @@ class TrueMiddle:
def __call__(self, a: Image.Image, b: Image.Image, t: float) -> Image.Image:
ka, kb = self.index[id(a)], self.index[id(b)]
- self.calls.append((ka, kb, t))
- assert (kb - ka) % N == 2 and t == 0.5 # always the two neighbours, half way
- return self.truth[(ka + 1) % N]
+ self.calls.append((ka, kb, round(t, 4)))
+ at = t * ((kb - ka) % N)
+ assert abs(at - round(at)) < 1e-9 # always a frame's own time
+ return self.truth[(ka + round(at)) % N]
-def test_only_the_frame_after_a_jump_is_replaced_by_its_neighbours_middle():
+def forced_flow_group(monkeypatch, frames: list[int], neighbours: tuple[int, int], t: list[float]) -> None:
+ """Isolate adoption from target detection: the flow reading names this one group (a drawing a frame),
+ until a round has made it or refused it."""
+ group = {"frames": frames, "drawings": [[k] for k in frames], "neighbours": list(neighbours), "t": t, "off": 9.0}
+
+ def read(loop, *, fixed=(), skip=(), **kw):
+ groups = [] if set(frames) & (set(fixed) | set(skip)) else [group]
+ return {"groups": groups, "unfixed": [], "hold": 1, "drawings": len(loop), "off_max_before": 9.0 if groups else 0.0}
+
+ monkeypatch.setattr(repair, "flow_targets", read)
+
+
+def test_only_the_frame_off_the_flow_is_made_again_between_its_neighbours():
filmed, truth = _loop({10: 12})
- fake = TrueMiddle(filmed, truth)
+ fake = TrueBetween(filmed, truth)
out, record = repair.repair_jumps(filmed, fake)
assert record["replaced"] == [10]
assert fake.calls == [(9, 11, 0.5)]
assert out[10] is truth[10]
assert all(out[k] is filmed[k] for k in range(N) if k != 10) # every other frame stays the video's own
- assert record["score_max_before"] >= repair.JUMP_RATIO > record["score_max_after"]
- assert record["stopped"].startswith("no step at or above")
+ assert record["off_max_before"] >= repair.FLOW_LIMIT > record["off_max_after"]
+ assert record["stopped"] == "no frame off the flow"
def test_a_smooth_loop_is_left_alone_and_needs_no_interpolator():
@@ -87,45 +103,68 @@ def test_a_smooth_loop_is_left_alone_and_needs_no_interpolator():
assert record["replaced"] == [] and all(a is b for a, b in zip(out, filmed))
-def test_at_most_three_and_never_next_to_a_made_frame():
- filmed, truth = _loop({3: 14, 9: 13, 15: 12, 20: 11})
- out, record = repair.repair_jumps(filmed, TrueMiddle(filmed, truth))
+def test_at_most_three_calls_worst_first():
+ filmed, truth = _loop({3: 14, 10: 13, 15: 12, 21: 11})
+ fake = TrueBetween(filmed, truth)
+ out, record = repair.repair_jumps(filmed, fake)
assert len(record["replaced"]) == 3 and record["stopped"] == "3 interpolation calls used"
- assert record["replaced"][0] == 3 and set(record["replaced"]) < {3, 9, 15, 20} # worst first, only stray frames
+ assert set(record["replaced"]) < {3, 10, 15, 21} and all(out[k] is truth[k] for k in record["replaced"])
+ offs = [r["off"] for r in record["rounds"]]
+ assert offs == sorted(offs, reverse=True) # worst first, by the flow reading
+ assert [g["frames"] for g in record["left"]] == [[k] for k in {3, 10, 15, 21} - set(record["replaced"])]
+
- filmed, truth = _loop({8: 14, 9: 14}) # two jump frames side by side
- out, record = repair.repair_jumps(filmed, TrueMiddle(filmed, truth))
- assert len(record["replaced"]) == 1
- assert "next to a frame already made" in record["stopped"]
+def test_jumps_a_few_frames_apart_are_not_read_as_a_loop_on_threes():
+ # Its only large steps are the ones into and out of the jumps, every few frames: to `held.measure` the ordinary
+ # steps are repeats and the jumps drawings. Its runs are not a hold (five and six frames, and one), so it is read
+ # a drawing a frame: each jump a frame of its own, and a frame made stands for itself alone.
+ filmed, truth = _loop({3: 14, 9: 13, 15: 12, 20: 11})
+ record = repair.flow_targets(filmed)
+ assert record["hold"] == 1 and sorted(g["frames"] for g in record["groups"]) == [[3], [9], [15], [20]]
+ out, record = repair.repair_jumps(filmed, TrueBetween(filmed, truth))
+ assert len(record["replaced"]) == 3 and all(len(r["frames"]) == 1 for r in record["rounds"])
+
+
+def test_two_jump_frames_side_by_side_are_made_again_as_two():
+ filmed, truth = _loop({8: 14, 9: 14})
+ fake = TrueBetween(filmed, truth)
+ out, record = repair.repair_jumps(filmed, fake)
+ assert record["replaced"] == [8, 9] and fake.calls == [(7, 10, 0.3333), (7, 10, 0.6667)]
+ assert out[8] is truth[8] and out[9] is truth[9]
def test_the_hair_watched_is_behind_the_body_whichever_way_it_faces():
# A small ponytail jump: the whole frame barely notices, the hair box does.
right_filmed, right_truth = _loop({12: 6}, side="left") # tail on the left = behind a right-facing body
- assert repair.jump_scores(right_filmed, facing="right")["hair"].max() >= repair.JUMP_RATIO
- assert repair.jump_scores(right_filmed, facing="left")["hair"].max() < repair.JUMP_RATIO
+ assert repair.jump_scores(right_filmed, facing="right")["hair"].max() >= SIZE_JUMP
+ assert repair.jump_scores(right_filmed, facing="left")["hair"].max() < SIZE_JUMP
left_filmed, _ = _loop({12: 6}, side="right") # tail on the right = behind a left-facing body
- assert repair.jump_scores(left_filmed, facing="left")["hair"].max() >= repair.JUMP_RATIO
+ assert repair.jump_scores(left_filmed, facing="left")["hair"].max() >= SIZE_JUMP
assert repair.hair_box("left") == (0.55, 0.30, 1.0, 0.80)
+ # The flow reading needs no facing: the jump is taken out on either side.
+ for filmed, truth in (_loop({12: 6}, side="left"), _loop({12: 6}, side="right")):
+ out, record = repair.repair_jumps(filmed, TrueBetween(filmed, truth))
+ assert record["replaced"] == [12]
-def test_blocked_worst_target_does_not_hide_an_independent_jump():
+def test_each_group_is_made_from_frames_as_filmed_never_beside_a_frame_made():
filmed, truth = _loop({8: 14, 9: 14, 18: 10})
- fake = TrueMiddle(filmed, truth)
+ fake = TrueBetween(filmed, truth)
out, record = repair.repair_jumps(filmed, fake)
- assert 18 in record["replaced"] and out[18] is truth[18]
- assert record["blocked"] and len(fake.calls) <= repair.MAX_REPAIRS
- assert all((k + 1) % N not in record["replaced"] for k in record["replaced"])
+ assert sorted(record["replaced"]) == [8, 9, 18] and len(fake.calls) == repair.MAX_REPAIRS
+ for r in record["rounds"]:
+ assert not set(r["neighbours"]) & set(record["replaced"])
+ assert all(filmed[k] is out[k] for k in r["neighbours"])
def test_bad_outline_proposals_preserve_originals_and_consume_the_call_budget():
- filmed, truth = _loop({3: 14, 9: 13, 15: 12, 20: 11})
+ filmed, truth = _loop({3: 14, 10: 13, 15: 12, 21: 11})
for frame in filmed + truth:
d = ImageDraw.Draw(frame)
d.rectangle((50, 30, 69, 99), outline=(10, 10, 10, 255), width=2)
d.rectangle((48, 10, 71, 29), outline=(10, 10, 10, 255), width=2)
before = [f.tobytes() for f in filmed]
- fake = TrueMiddle(filmed, truth)
+ fake = TrueBetween(filmed, truth)
def melted(a, b, t):
pixels = np.asarray(fake(a, b, t)).copy()
@@ -136,19 +175,22 @@ def test_bad_outline_proposals_preserve_originals_and_consume_the_call_budget():
out, record = repair.repair_jumps(filmed, melted)
assert record["replaced"] == []
assert record["attempts"] == len(fake.calls) == repair.MAX_REPAIRS
- assert len({r["target"] for r in record["rounds"]}) == repair.MAX_REPAIRS
+ assert len({tuple(r["frames"]) for r in record["rounds"]}) == repair.MAX_REPAIRS
assert all(r["outcome"] == "rejected" and "outline" in r["faults"] for r in record["rounds"])
assert [f.tobytes() for f in out] == before == [f.tobytes() for f in filmed]
-def test_circular_adjacency_and_zero_call_budget():
+def test_a_pair_flung_at_the_wrap_is_taken_out_whole_not_smoothed_at_its_edges():
+ # Frames N-1 and 0 flung together: the frames either side of them read as far off the line as they do, and
+ # an in-between there brings the reading under the limit too, leaving the pair. The pair is what the
+ # in-between moves furthest: it is taken out, made again from frames N-2 and 1.
filmed, truth = _loop({0: 16, N - 1: 15, 12: 10})
- fake = TrueMiddle(filmed, truth)
- _, record = repair.repair_jumps(filmed, fake)
- made = record["replaced"]
- assert 12 in made and not (0 in made and N - 1 in made)
- assert all((k + 1) % N not in made for k in made)
- no_calls = TrueMiddle(filmed, truth)
+ fake = TrueBetween(filmed, truth)
+ out, record = repair.repair_jumps(filmed, fake)
+ assert sorted(record["replaced"]) == [0, 12, N - 1]
+ assert sorted(fake.calls) == [(11, 13, 0.5), (N - 2, 1, 0.3333), (N - 2, 1, 0.6667)]
+ assert all(out[k] is truth[k] for k in (0, 12, N - 1))
+ no_calls = TrueBetween(filmed, truth)
out, record = repair.repair_jumps(filmed, no_calls, max_frames=0)
assert not no_calls.calls and record["attempts"] == 0
assert all(a is b for a, b in zip(out, filmed))
@@ -189,6 +231,25 @@ def test_video_loop_records_the_repair_and_plays_the_made_frame(tmp_path):
assert made == [0.5]
+def test_video_loop_plays_two_frames_made_again_at_their_own_times_in_a_loop_as_long(tmp_path):
+ filmed, truth = _loop({8: 14, 9: 14})
+ keyed = _keyed(tmp_path, filmed)
+ made = []
+
+ def between(a, b, t):
+ made.append(round(t, 4))
+ return truth[8] if t < 0.5 else truth[9]
+
+ rep = _run(tmp_path, keyed, interpolate=between)
+ assert rep["jump_repair"]["replaced"] == [8, 9] and made == [0.3333, 0.6667]
+ (round_,) = [r for r in rep["jump_repair"]["rounds"] if r["why"] == "flow"]
+ assert round_["neighbours"] == [7, 10] and round_["t"] == [0.3333, 0.6667]
+ cells = sorted((tmp_path / "out" / "cycle").glob("frame-*.png"))
+ assert len(cells) == N # the loop keeps its length: each frame its own time
+ for k in (8, 9):
+ assert np.array_equal(np.asarray(Image.open(cells[k])), np.asarray(truth[k]))
+
+
def _no_rife(monkeypatch, tmp_path: Path) -> None:
"""No RIFE anywhere the engine looks: no SPRITE_GEN_RIFE, an empty PATH, an empty data directory."""
monkeypatch.delenv("SPRITE_GEN_RIFE", raising=False)
@@ -208,7 +269,8 @@ def test_a_jump_without_rife_is_cut_as_filmed_with_a_warning(tmp_path, monkeypat
jr = rep["jump_repair"]
assert jr["applied"] is False and jr["replaced"] == [] and jr["why"] == "RIFE not installed — cut as filmed"
assert jr["install"] == "sprite-gen rife install" and "rife-ncnn-vulkan not found" in jr["rife"]
- assert jr["score_max_before"] >= repair.JUMP_RATIO and jr["score_max_after"] == jr["score_max_before"]
+ assert jr["off_max_before"] >= repair.FLOW_LIMIT and jr["off_max_after"] == jr["off_max_before"]
+ assert jr["unmade"]["frames"] == [10]
assert rep["seam_measurement"] == "source-frames" and rep["jolt"]["measured"] == "as filmed"
on_disk = np.asarray(Image.open(tmp_path / "out" / "cycle" / "frame-010.png"))
assert np.array_equal(on_disk, np.asarray(reopened[10])) # the jump frame stays as filmed
diff --git a/tests/video/test_rife.py b/tests/video/test_rife.py
index 45e5a59..d449933 100644
--- a/tests/video/test_rife.py
+++ b/tests/video/test_rife.py
@@ -232,13 +232,13 @@ def test_real_rife_melts_legs_crossing_too_far_and_alignment_takes_the_nearer_fr
@pytest.mark.real_rife
def test_real_rife_repair_rejects_outline_loss_and_keeps_the_original_middle(monkeypatch):
from sprite_gen.video import repair
+ from tests.video.test_loop_repair import forced_flow_group
frames = [_walker(20, -20), _walker(8, -8), _walker(-5, 5), _walker(10, -10)]
before = [f.tobytes() for f in frames]
# Isolate adoption from candidate detection: this target spans the wide crossing
# above, where the actual external RIFE loses an outline the original middle has.
- scores = np.array([3., 2., 1., 1.])
- monkeypatch.setattr(repair, "jump_scores", lambda *a, **kw: {k: scores for k in ("whole", "hair", "score")})
+ forced_flow_group(monkeypatch, [1], (0, 2), [0.5])
interpolate = rife.Rife()
out, facts = repair.repair_jumps(frames, interpolate)
assert interpolate.made == facts["attempts"] == 1