Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
feat(video-loop): a hand or a foot that pops at a walk's wrap is read on the part itself and named, the loop recorded a take to film again; the cut stays as it was
Soohong Kim9b73c2ee8435
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 202cd3f..ba5e14a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,13 @@All notable public changes to `sprite-gen` are recorded here. Versions track the `version:` field in `SKILL.md` and `pyproject.toml`.+## Unreleased++**Upgrading from 3.3.0: A walk or run loop is cut to the same bytes, whether a part pops in it or not; every walk and run report gains `part_pop` and `retake`.** `--unfixed refuse` also refuses a loop recorded `retake` reason `part-pop`, whatever `--repair`. No flags are added; no frames are made and no other cut is taken.++- **New: The part reading and the `retake` record.** Squares 8 % of the body height are followed drawing to drawing and a part whose jerk leaves the curve its steps either side draw pops at the wrap. The cut stays and the report records a take to film again (`retake`, reason `part-pop`): `remedy` is `retake` where the engine's search chose the cut, and `recut-or-retake` where the cut was given (`--cycle fixed`, or `pinned`); `searched` says which. See [loop-repair](docs/loop-repair.md) section 2, "The part pop".+- **Tests**: `tests/video/test_loop_part_pop.py` (the four bounds flip the pop; flung and stays; a pop over two steps reads as their mean; an ease through a fast bell does not pop; a fist jumping 2.5, 3.5 and 5 % passes the flow and surge readings and is named; a walk whose tail, foot and eye move across the wrap, and a run, have no pop; an ordinary walk is cut to the bytes it was; a cut given whose fist pops is named, `retake` `recut-or-retake`, `--unfixed refuse` refuses, and under `warn` it is the bytes it was; a clip whose fist drifts through every cut keeps the search's cut to the bytes it was, `retake` `retake`; a clip no part pops in is cut to the bytes it was).+## v3.3.0 - PyTorch RIFE backend for CUDA and CPU, executor for a GPU on another machine, and Linux CPU and cloud T4 release lanes**Upgrading from 3.2.0: Defaults stay unchanged, cache keys update once, reports show the backend, install checks model hashes, and schemas are unchanged.** With `SPRITE_GEN_RIFE_BACKEND` unset (the default), RIFE is the `rife-ncnn-vulkan` binary as before. Its frames are the same bytes as 3.2.0. Measured: the binary's frames and sixteen-pass readings through the changed engine equal the old engine's, byte for byte. A `--between-cache` directory kept by 3.2.0 is made again once. The key now names the backend (`backend: "ncnn"`). The engine's `rife.py` changed, and its sha256 is part of the key anyway. Reports take `interpolator.kind` from what made the frames: `rife-ncnn-vulkan` as before for the binary, or `rife-torch` for the new backend. The overlapped wrap's and the seam bridge's records count `binary_calls` for the binary as before, or `runs` for the torch backend. `SPRITE_GEN_RIFE_EXECUTOR` (new) is unset by default, and RIFE runs in this process. `sprite-gen rife install` now checks the model's two files (`rife-v4.6/flownet.param`, `flownet.bin`) against pinned SHA-256 after unpacking, for either backend. A model that differs installs nothing. The line a missing RIFE is reported with (`install` in records, warnings) is `sprite-gen rife install` for the binary. Where the torch backend is chosen, that line is: `pip install "sprite-gen[torch]" && sprite-gen rife install --backend torch`. No command-line flags of `video-loop` / `video-cycle-align` / `video-set` change. No restoration schemas change: `source-restoration-v5`, repair report `schema_version` 4, comparison `schema_version` 6.diff --git a/docs/README.md b/docs/README.mdindex 2892854..49f049f 100644--- a/docs/README.md+++ b/docs/README.md@@ -86,7 +86,7 @@ grouping is derived from `sprite_gen/_modules.py`, the one taxonomy table.| [video.md](video.md) | `sprite-gen video` / `video-extend` / `video-edit` / `video-resume`: stills and clips to mp4 through Grok Imagine (image-to-video, last-frame pin, references, extension, editing, asking again for an unfinished generation) with the user's own credential || [video-pipeline.md](video-pipeline.md) | Pipeline B engine contract: state canvas, keyed frames, true-period and one-shot cycles, strip/GIF/WebP, the batch, a set's directions on one sheet, a walk or run's stop || [loop-review.md](loop-review.md) | Automatic loop decisions, ambiguous gait review, visual evidence and explicit cut/alignment overrides |-| [loop-repair.md](loop-repair.md) | RIFE (where it runs, cost, licences, `sprite-gen rife install`, what runs without it), jump-frame repair, the flow reading (frames off a walk's way), the eased retime (a part that rushes on its way), the overlapped wrap (a part on its own beat at a two-step cut's wrap), the jolt index and its gate, one cycle length per direction set |+| [loop-repair.md](loop-repair.md) | RIFE (where it runs, cost, licences, `sprite-gen rife install`, what runs without it), jump-frame repair, the flow reading (frames off a walk's way), the eased retime (a part that rushes on its way), the overlapped wrap (a part on its own beat at a two-step cut's wrap), the part pop (a hand or a foot that jumps at the wrap), the jolt index and its gate, one cycle length per direction set || [frame-interpolation.md](frame-interpolation.md) | Generative in-betweens for sprite frames, recorded as a take || [seamless-video-loop.md](seamless-video-loop.md) | Making a non-looping ambient clip loop forever (RIFE seam bridge) — a different job from pipeline B || [face-parts.md](face-parts.md) | Face requests, face packs, talking face rules, live player, `video-face`, and `face-bake`. |diff --git a/docs/loop-repair.md b/docs/loop-repair.mdindex 0feff77..0ed7d9f 100644--- a/docs/loop-repair.md+++ b/docs/loop-repair.md@@ -1,6 +1,6 @@# Loop repair — RIFE in-betweens for jump frames, the jolt index, one cycle per set-> Owns: Where RIFE runs and what it costs, which model and augmentation it runs with, its two backends (the binary and PyTorch, the latter in this process or on a GPU elsewhere), how it is installed and what runs without it, jump-frame repair in `video-loop`, the flow reading (frames off a walk's way), the eased retime (a part that rushes on its way), the seam bridge (the wrap of a loop that is not a walk), the jolt index and its gate, cycle alignment across a direction set, the redrawn wrap of a pinned clip (`--wrap-blend`) · Index: [docs/README.md](README.md)+> Owns: Where RIFE runs and what it costs, which model and augmentation it runs with, its two backends (the binary and PyTorch, the latter in this process or on a GPU elsewhere), how it is installed and what runs without it, jump-frame repair in `video-loop`, the flow reading (frames off a walk's way), the eased retime (a part that rushes on its way), the part pop (a hand or a foot that jumps at the wrap), the seam bridge (the wrap of a loop that is not a walk), the jolt index and its gate, cycle alignment across a direction set, the redrawn wrap of a pinned clip (`--wrap-blend`) · Index: [docs/README.md](README.md)A walk loop cut from a generated clip can look right in every still and still hitch when itplays: the video model redraws thin hair a little differently every frame, and now and then@@ -397,7 +397,7 @@ below; a frame made is the whole picture at one time, so the legs take the timeand on every walker measured the loop keeps the flow repair). Before all of it, a cut two stepslong whose wrap a part on its own beat leaves open has the frames beside its wrap made again betweenthe clip's frames a cycle apart and its own ([the overlapped-wrap](#the-overlapped-wrap--a-part-on-its-own-beat-that-no-cut-of-two-steps-closes) below). A loop of any other state is not read for its flow; where its wrap jumps, frames round it are made again ([the seam bridge](#the-seam-bridge-a-loop-that-is-not-a-walk-whose-wrap-jumps) below).+wrap](#the-overlapped-wrap--a-part-on-its-own-beat-that-no-cut-of-two-steps-closes) below). A part the size of a hand or a foot that jumps at a walk's wrap is read on the part itself: the engine reads and names the pop and records the loop as a take to film again, and the cut stays as it was ([the part pop](#the-part-pop-a-hand-or-a-foot-that-jumps-at-the-wrap)). A loop of any other state is not read for its flow; where its wrap jumps, frames round it are made again ([the seam bridge](#the-seam-bridge-a-loop-that-is-not-a-walk-whose-wrap-jumps) below).| Rule | Value | Why ||---|---|---|@@ -456,7 +456,7 @@ made for the source projection and for restoration, which never restores it ([thguard](loop-comparison.md#the-ghost-guard)). `--repair off` gives nothing way: the cut's ghosts aredelivered as filmed, named (section 4).-Under `--repair auto` (the default) or `on`, jump repair takes out a group of one or two drawings that lie 3.0 or more usual steps off the line between neighbours (`repair.FLOW_LIMIT`) and has RIFE make them again. A group whose made frames have a fault is refused and keeps its frames as filmed in `refused`. When the loop as it plays still reads a drawing of a refused group at or over the limit, that drawing is in `jump_repair.unfixed` too: `frames`, `off`, `turn`, `into`, `out`, `window` (read on the playing loop) and `refused`. Every drawing in `unfixed` prints the warning line `video-loop: warning: frame <frame> of the loop lies <off>x its window's usual step off the walk's flow after the jump repair: the group that would bring it back was refused (<faults>), so it plays as filmed — a jump played as filmed; --unfixed refuse refuses such a loop (docs/loop-repair.md section 2)`. Flag `--unfixed warn|refuse` (default `warn`) can refuse such a loop with `video-loop: loop frames left off the flow — ` followed by those words, the cut, and `; the motion does not play smoothly — regenerate the clip`. The `--unfixed` flag is caller choice and is not lifted by `--seam-max`.+Under `--repair auto` (the default) or `on`, jump repair takes out a group of one or two drawings that lie 3.0 or more usual steps off the line between neighbours (`repair.FLOW_LIMIT`) and has RIFE make them again. A group whose made frames have a fault is refused and keeps its frames as filmed in `refused`. When the loop as it plays still reads a drawing of a refused group at or over the limit, that drawing is in `jump_repair.unfixed` too: `frames`, `off`, `turn`, `into`, `out`, `window` (read on the playing loop) and `refused`. Every drawing in `unfixed` prints the warning line `video-loop: warning: frame <frame> of the loop lies <off>x its window's usual step off the walk's flow after the jump repair: the group that would bring it back was refused (<faults>), so it plays as filmed — a jump played as filmed; --unfixed refuse refuses such a loop (docs/loop-repair.md section 2)`. Flag `--unfixed warn|refuse` (default `warn`) can refuse such a loop with `video-loop: loop frames left off the flow — ` followed by those words, the cut, and `; the motion does not play smoothly — regenerate the clip`. The `--unfixed` flag is caller choice and is not lifted by `--seam-max`. The flag also covers a loop recorded `retake` reason `part-pop`: under `refuse`, the loop fails, whatever `--repair` says ([the part pop](#the-part-pop-a-hand-or-a-foot-that-jumps-at-the-wrap)).The flow is read again after each group, on the union box of the loop as filmed; a refused group isnever tried again in that run, and nothing is made from or beside it. The circular last/first@@ -889,6 +889,104 @@ off)", no `tries`, `calls` 0) with the `warning:` line every skipped wrap has, aas filmed, the loop failing on its seam as where every run is refused. The jump repair, the eased retime andthe gate are as with it on; `--repair off` turns it off with the rest.+### The part pop: a hand or a foot that jumps at the wrap++The flow reading reads a walk loop in nine windows, each half the body's box across and down (`FLOW_GRID` 4), on the body's coverage and shading blurred by 3 % of the body height (`FLOW_BLUR`). The surge reading ([the eased retime](#the-eased-retime--a-part-that-rushes-on-its-way)) reads the same windows.++A part the size of a hand that jumps a few per cent of the body height at the wrap (the step from the loop's last frame to its first) and stays there passes both, for three reasons: first, the window is far larger than the hand, and its usual step is set by the tail and the legs that pass through it; second, the flow's `off` is half the change of a step, so a part that jumps once and goes on reads at half; third, the distance between two blurred states stops growing once the part is further than the blur from where it was, so even a window the size of a hand reads such a jump under the surge reading's speed limit of 3.0 usual steps.++Windows small enough to see the hand (a grid of 8 or 12, or windows the size of a hand) do read the jump, but they read many of the loop's ordinary steps over the same limits too.++Synthetic evidence in `tests/video/test_loop_part_pop.py` shows the failure: a walker seen from the side, 36 frames a cycle, with a forearm held out in front ending in a fist. Its fist slips 2.5, 3.5 or 5 % of its height over the loop and jumps back at the wrap. The flow reading names no frame (1.46 off the flow at most against the limit 3.0) and the surge reading names no rush. The part reading below names the fist.++The part reading (`part_pop.read`) runs on every walk and run (the states the jump repair reads), on the cut as filmed, after the anchor and the wrap blend and before any repair, whatever `--repair` says. It is read on the loop's drawings (`repair.flow_drawings`), as the flow reading: a loop on twos is read a drawing at a time.++Parts are squares 8 % of the body height on a side (`PART_PATCH`), seeded every 8 % over the body on the loop's first drawing, where the square is covered (coverage at least 0.15, `PART_SEEN`) and shaded (luma standard deviation at least 0.02, `PART_TEXTURE`). They are read at a body height of 400 px (`PART_READ`). Each square is found drawing to drawing by normalised cross-correlation of its luma (over a mid grey by coverage) within 8 % of the body height of where it was (`PART_SEARCH`), to a fraction of a pixel on the parabola through the correlations either side.++A part counts only where every one of its steps reads back: the square where it landed, looked for in the drawing before, lands within 1.5 px (at 400 px) of where the part was (`PART_FOLLOW`), and no search reaches its edge. A part is dropped at its first step that does not read back, and nothing is read on it. Fur whose pattern repeats, a part whose drawing changes, and a part that moves further than the search in one drawing (the legs of a run) are not followed. An eye that blinks can still be followed both ways; it is then read like any other part and the bounds below leave it, so the read-back check does not by itself drop every blink.++A part's usual step is its median step, no less than the median of the followed parts' medians (the flow reading's `_flow_scale` rule, so a part that hardly moves is not read on its noise) nor 0.5 px (`PART_NOISE`).++A part does not move evenly: a tail swings slow, fast, slow again. So a run of one or two steps (`SURGE_SPAN`) is read against the curve the part's own steps either side of it draw, not against their mean: the three steps before the run and the three after (`SURGE_AROUND`), each a step vector, fitted x and y apart by a second-degree polynomial in time (least squares: the local fit of a Savitzky-Golay filter), and the run's steps predicted on that curve. How far the run's steps leave their prediction, as a mean length, is its `jerk`. A part that eases steps where its curve goes, however fast; a frame that jumps does not.++A part pops where the run is, all at once:++| Bound | Value | Read on | Why |+|---|---|---|---|+| `PART_POP_FLOOR` | 2 % of the body height | the run's largest step | a tremor stays under it |+| `SURGE_LIMIT` (the surge reading's own) | 3.0 | the jerk over the part's usual step | as the surge reading bounds a window's speed |+| `PART_POP_CURVE` | 5.0 | the jerk over the larger of: the step the curve predicts there, the curve's own scatter over the six steps it was fitted to (root mean square), 0.5 px | a part that eases fast steps where its curve goes |+| `PART_POP_LEAD` | 2.0 | the jerk over the part's largest jerk on any other run as long whose curve was fitted without this run's steps | a part that moves far inside the loop as well (a tail's flick, a foot snapping up) leaves its curve there too |++Its way is not read. Its kind is recorded: `flung` where the step after the run takes back at least half of its move, or the run takes back that share of the step before (`PART_FLUNG` 0.5); otherwise `stays`.++At the wrap the runs read are those that touch the step from the last drawing to the first. A loop under 8 drawings is not read (`skipped`): a run and the three steps either side need eight. A loop too short to hold another run whose curve leaves this one out has nothing to lead, and does not pop.++The choice of the curve was measured 2026-10-26 on synthetic paths: 50 ordinary paths (a slow part of about 1 px a step at a body height of 400 px, on a gentle wobble of 36 steps, whose speed rises and falls in a sine-squared bell over 3, 4, 5, 6 or 8 steps, to 6, 12, 20, 30 or 40 px a step at its fastest, up to a tenth of the body, placed across the wrap and inside the loop) and 24 broken paths (the slow part jumping 8, 12, 16 or 20 px in one step and staying there, or coming back the next step, or jumping inside an ease of seven steps that peaks at 8 px; at the wrap and inside).++| Baseline | Ordinary paths named | Broken paths missed |+|---|---|---|+| the mean of the three steps either side, 6 times it, and 1.5 times the part's largest step elsewhere (the reading measured first) | 15 of 50: the bells of 3 and 4 steps from 12 px a step at the wrap; inside, those of 3 steps from 20 px and of 4 steps from 12 px | 6 of 24: the jumps of 8 to 16 px inside an ease |+| the curve, 4 times the predicted step, lead 2.0 | 3 of 50: the bells of 4 steps at 30 and 40 px at the wrap and at 40 px inside | 8 of 24: every jump inside an ease |+| the curve, 5 times, lead 2.0 (taken) | none | 8 of 24: every jump inside an ease |+| the curve, 6 times, lead 2.0 | none | 8 of 24 |++5.0 is the least multiple of the predicted step that names none of the bells. A jump that rides a fast motion and is less than five times the step its curve gives there is not named (a 20 px jump inside an ease of 8 px is about 2.2 times it). The mean baseline names the largest of those (20 px) only because it also names fast eases.++The reading has four named gaps. First, a part that is not followed is not read: on a fast run the fastest parts leave the search between drawings (the test walker drawn at 16 frames a cycle, a run, its legs swinging 12 % of the body a frame, has many squares unfollowed and none of those followed pops); where a part's drawing changes at the wrap, it is not followed there and its jump is not named. Second, a detail smaller than 8 % of the body (a finger) is read with what is round it. Third, a loop under 8 drawings is not read. Fourth, a jump riding a fast motion, under five times its curve's step.++The cut is kept: the engine takes no other cut for a part pop, whichever cut it is (the search's or one given). Frames made between two at the wrap do not mend it (the part's jump is still in the clip, spread over a step or two), so a loop a part pops in is cut to the same bytes as a loop where it is not read (`cycle/`, the strip, the GIF, the WebP). Taking another cut is not done because the part reading reads parts the size of a hand, not the whole body's change at the wrap: a cut chosen on it alone is not held to the whole body. It waits on a gate that reads the whole body's change between frames at the wrap.++The loop as cut is read again (the part reading on the frames as anchored); `part_pop` records `outcome`: `none` where no part pops, `closed` where the jump repair changed frames of the cut and no part pops on the loop as it plays (`after`, the reading again), `named` where it plays as filmed; and `left`, the pops that play.++A take to film again: where a part pops on the loop as it plays, the report's top-level `retake` is `{reason: "part-pop", reasons: ["part-pop"], part_pop: {pops, cut, searched}, limits: {floor, speed, curve, lead}, remedy}`, else `null`. `pops` each: `seed`, `from`, `to`, `at`, `body_pct`, `jerk_pct`, `speed`, `curve`, `lead`, `kind`, `margin`. `remedy` is `retake` where the engine's search chose the cut, and `recut-or-retake` where the cut was given (`--cycle fixed`, or `pinned`); `searched` says which. The shape is `video-cycle-align`'s per-loop `retake` (section 4): `reason` in kebab-case, the numbers under the reason's snake_case key, `limits`, and `remedy` (`retake`, `recut`, `recut-or-retake`), so a caller reads both alike.++`--unfixed refuse` refuses a loop with such a `retake`, whatever `--repair` says (the repair makes no frame for a part pop and the cut stays, so whatever `--repair` says the pop plays as filmed). `--unfixed warn` (the default) keeps it with a warning line.++A loop is cut to the same bytes whether a part pops in it or not (`cycle/`, the strip, the GIF, the WebP); every walk and run report gains `part_pop` and `retake` (`retake` is `null` where no part pops).++Cost: the reading is NumPy on the CPU, about a second a loop; nothing else is read.++Named gaps of the take to film again: no other cut is read or taken (a pop the search's cut has may be absent at another cut of the clip; finding it waits on the whole body's gate); the pop is named for a cut given too (`remedy` `recut-or-retake`).++Synthetic outcomes (tests in `tests/video/test_loop_part_pop.py`, measured 2026-10-26 on alex-macbook-m1, except the third, a probe beside the tests):++On the front walker of `tests/video/test_loop_overlap.py` with its tail on the walk's beat and a fist held out (73 frames, 26 a cycle, `--anchor motion-auto`), the fist held still: no part pops, `retake` is `null`, and the loop is the bytes it is with no part read at all.++On the same walker with its fist drifting 0.18 px a frame through the clip: every 26-frame cut jumps it back about 4.7 px at its wrap (3 % of the body). The search's cut (two steps by the crossings) is kept and named (margin 1.39); `retake` `remedy` `retake`, `searched` true; the loop is the bytes it is with no part read.++On the walker with its fist drifting only through the clip's first 12 to 24 frames (a probe): the search takes a cut past the drift (33/26), its repeat error there being least; no part pops.++On the side walker cut whole (`--cycle fixed`), its fist slipping 3.5 % back at the wrap: five squares on the fist pop together (the worst a jerk of 3.43 % of the body, 10.2 usual steps, 14.6 times its curve's step, lead 7.4, stays); one warning line names the worst and the four beside it; `retake` `remedy` `recut-or-retake`, `searched` false; `--unfixed refuse` refuses the loop; under `warn` the loop is the bytes it is with no part read.++On the side walker whose tail swings, whose far foot lifts 16 px and whose eye shuts across the wrap, and the same walker drawn as a run (16 frames a cycle): no part pops anywhere; the walk is cut to the bytes it was.++`part_pop` in the report carries the bounds (`read_px`, `patch`, `search`, `follow_px`, `floor`, `speed`, `curve`, `lead`), `drawings`, `hold`, `body_px`, `parts` (seeded), `followed`, `usual_floor_px`, `pops` (each: `seed`, `from`, `to`, `steps`, `at`, `body_pct`, `jerk_pct`, `usual_px`, `speed`, `curve`, `lead`, `kind`, `back`, `margin`; worst first, at most one a part; `margin` is the least of the four terms over their bounds, 1 or more pops), `nearest` (the run nearest to popping, popped or not), `skipped` where it was not read, `outcome` (`none`, `closed`, `named`), `left` (the pops that play as filmed), and `after` (the reading of the loop as it plays, where a frame was changed).++The summary line's JSON carries `part_pop` (`pops` with `from`, `to`, `at`, `body_pct`, `kind`, `margin`; `outcome`; `left`) and `retake` (`reason`, `remedy`).++The engine prints these warning lines on stderr, in its own words, for a pop left as filmed:++```+video-loop: warning: film this direction again (part-pop) — the part at (<x>, <y>) px of frame <from> moves <body> % of the body's height into frame <to>, <jerk> % off the curve its steps either side draw (<speed>x its usual step, <curve>x the step that curve gives, <lead>x its largest such jump elsewhere; it stays (or: comes back); <n> parts beside it pop with it): <why>; --unfixed refuse refuses such a loop (docs/loop-repair.md section 2, "The part pop")+```++```+<why>:+the search's cut is kept as cut, and no other cut is taken for a part: film it again+the cut was given (--cycle fixed or pinned): cut it where no part pops, or film it again+```++`--unfixed refuse` fails the loop with this error line:++```+video-loop: a part pops at the loop's wrap — film this direction again (part-pop) — <the warning line's words from `the part at` to the why> (<kind> length <L> frames from <start>); the motion does not play smoothly+```++**Beyond walks: a strike.** The jump repair and the part reading run on walks and runs only. An attack has a strike: an intended rush, the largest acceleration of the loop at the impact frame, larger still with a sword. Read as a part pop, it would be named. Ways to widen it later, not built: the state declares its strike frames (or a window round them) and the reading leaves them out; the lead is read against the same part's like accelerations elsewhere in the loop, so a strike the loop repeats is its own motion; a one-shot cut (`--cycle once`) has no wrap to read.++**The body's surge reading.** The body's surge reading (`repair.surges`, `SURGE_LIMIT`, `SURGE_RATIO` 3.0 over the mean of the `SURGE_AROUND` steps either side) reads a window's run against the mean of its neighbours, the baseline the synthetic paths above show naming fast eases. Whether the curve can serve there is not measured; the flow and surge readings are unchanged.+### The seam bridge: a loop that is not a walk, whose wrap jumpsA user expects an idle loop, jump, attack, or generic in-place action to be smoothed at its wrap like a walk. A walk's flow repair reads every frame against the line between its neighbours. An idle's own motion (a blink, an eye half shut, a mouth that opens) leaves that line too, so flow repair would remake those frames and take out the motion. A loop that is not a walk is therefore not read for its flow; its wrap alone is read, leaving the walk path unchanged.diff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.pyindex 28cda9b..89e3904 100644--- a/sprite_gen/video/loop.py+++ b/sprite_gen/video/loop.py@@ -49,6 +49,7 @@ from sprite_gen.spec.runio import atomic_write_text, new_stage, refuse_overlapfrom sprite_gen.util.gif_utils import save_clean_giffrom sprite_gen.util.resample import resize_cellfrom sprite_gen.video import motion_anchor, auto_motion, local_cycle, gait_fallback, nonloop, effect+from sprite_gen.video import part_pop as part_pop_modfrom sprite_gen.video import crossings as crossings_modfrom sprite_gen.video import held as held_modfrom sprite_gen.video import legs as legs_mod@@ -134,7 +135,8 @@ REPAIR_MODES = ("auto", "on", "off")OVERLAP_WRAP_MODES = ("on", "off")OVERLAP_WRAP_OFF = "turned off (--overlap-wrap off)"# A frame the jump repair leaves off the walk's flow (`jump_repair.unfixed`: no group brings it back, or the group that-# would was refused). warn: a warning line, the loop kept; refuse: the loop fails.+# would was refused), or a part that pops at the wrap of the cut taken (`part_pop.left`, a take to film again: `retake`).+# warn: a warning line, the loop kept; refuse: the loop fails.UNFIXED_MODES = ("warn", "refuse")SIZE_HOLD_MODES = ("auto", "off")FACINGS = ("right", "left")@@ -1143,6 +1145,72 @@ def _unfixed_lines(jump_repair: dict[str, Any]) -> list[str]:return lines+def _pop_settled(record: dict[str, Any], frames: list[Image.Image], cut: list[Image.Image]) -> None:+ """What became of a part that pops at the wrap of the cut taken (`part_pop`, docs/loop-repair.md section 2, "The part+ pop"), recorded: `outcome` — `none` where no part pops, `closed` where the jump repair changed frames of the cut and no+ part pops on the loop as it now plays, `named` where it plays as filmed — and the pops `left`, read again (`after`)+ where a frame of the cut was changed."""+ if not record["pops"]:+ record.update(outcome="none", left=[])+ return+ left = record["pops"]+ if any(a is not b for a, b in zip(frames, cut)):+ again = part_pop_mod.public(part_pop_mod.read(frames))+ record["after"] = {k: again[k] for k in ("drawings", "hold", "parts", "followed", "nearest", "pops")}+ left = again["pops"]+ record.update(outcome="named" if left else "closed", left=left)+++def _pop_said(p: dict[str, Any], together: int = 1) -> str:+ """A part that pops (`part_pop.read`), in words; `together`, the parts that pop over the same run, the worst said."""+ return (f"the part at ({p['at'][0]:.0f}, {p['at'][1]:.0f}) px of frame {p['from']} moves {p['body_pct']:.2f} % of the body's "+ f"height into frame {p['to']}, {p['jerk_pct']:.2f} % off the curve its steps either side draw ({p['speed']:.1f}x its "+ f"usual step, {p['curve']:.1f}x the step that curve gives, {p['lead']:.2f}x its largest such jump elsewhere; it "+ f"{'comes back' if p['kind'] == 'flung' else 'stays'}{_beside(together)})")+++def _beside(together: int) -> str:+ """The parts that pop with the one said, in words."""+ if together < 2:+ return ""+ return f"; {together - 1} part{'s' if together > 2 else ''} beside it pop{'' if together > 2 else 's'} with it"+++def _pop_runs(pops: list[dict[str, Any]]) -> list[tuple[dict[str, Any], int]]:+ """The pops (worst first) grouped by the run they pop over: the worst of each and how many pop there."""+ runs: dict[tuple[int, int], list[dict[str, Any]]] = {}+ for p in pops:+ runs.setdefault((p["from"], p["to"]), []).append(p)+ return [(group[0], len(group)) for group in runs.values()]+++RETAKE_REASON = "part-pop"+++def part_retake(record: dict[str, Any], cut: tuple[int, int], *, given: bool) -> dict[str, Any] | None:+ """A take to film again where a part pops at the wrap of the loop as it plays (`part_pop.left`), as+ `video-cycle-align`'s `retake` is: `reason` (RETAKE_REASON), `reasons`, the numbers under `part_pop` — the pops left,+ the cut, and whether the search chose it (`searched`) — the `limits`, and `remedy`: `retake` where the engine's search+ chose the cut, `recut-or-retake` where it was given (`given`: --cycle fixed, or pinned). No other cut is taken for it.+ None where no part pops."""+ if not record.get("left"):+ return None+ return {"reason": RETAKE_REASON, "reasons": [RETAKE_REASON],+ "part_pop": {"pops": [{k: p[k] for k in ("seed", "from", "to", "at", "body_pct", "jerk_pct", "speed", "curve", "lead",+ "kind", "margin")} for p in record["left"]],+ "cut": list(cut), "searched": not given},+ "limits": {k: record[k] for k in ("floor", "speed", "curve", "lead")},+ "remedy": "recut-or-retake" if given else "retake"}+++def _pop_lines(record: dict[str, Any], *, given: bool) -> list[str]:+ """Each pop that plays as filmed, a take to film again (`retake`), in words (`video-loop: warning:` lines)."""+ why = ("the cut was given (--cycle fixed or pinned): cut it where no part pops, or film it again" if given else+ "the search's cut is kept as cut, and no other cut is taken for a part: film it again")+ return [f"film this direction again ({RETAKE_REASON}) — {_pop_said(p, together)}: {why}" for p, together in+ _pop_runs(record.get("left") or [])]++def _step_reason(jump_repair: dict[str, Any], frames: set[int]) -> dict[str, Any]:"""Why a step between drawings jumps, where the jump repair says it: a drawing of it (`frames`) left off the walk'sflow (`jump_repair.unfixed`) — the group that would bring it back refused (`repair-refused`, its faults), or none@@ -2156,6 +2224,11 @@ def _cut_loop(print(f"video-loop: warning: {line}", file=sys.stderr)# Each cut frame given way to the frame beside it, as filmed: the seam is read on it there (`seam_as_filmed`).as_filmed: dict[int, Image.Image] = {}+ if prof.gait:+ # The part reading (docs/loop-repair.md section 2, "The part pop") of every walk and run, on the cut as filmed —+ # anchored, before any repair — whatever --repair asks: a hand or a foot that pops at the wrap.+ report_base["part_pop"] = part_pop_mod.public(part_pop_mod.read(frames))+ cut_frames = framesif repair != "off" and prof.gait:report_base["jump_repair"] = Nonefilmed = frames@@ -2281,9 +2354,23 @@ def _cut_loop(f"frames from {i}); the motion does not play smoothly — regenerate the clip")refuse(target, out_dir, name, {**report_base, "status": "failed", "error": error, "cycle": cycle})raise SystemExit(error)+ # A part that pops at the wrap of the cut taken: closed where the jump repair changed it away, else a take to film+ # again (`retake`), named.+ _pop_settled(report_base["part_pop"], frames, cut_frames)+ given = cycle_mode in ("fixed", "pinned")+ report_base["retake"] = part_retake(report_base["part_pop"], (i, L), given=given)+ pops_left = _pop_lines(report_base["part_pop"], given=given)+ if pops_left and unfixed == "refuse":+ error = (f"video-loop: a part pops at the loop's wrap — {'; '.join(pops_left)} ({cycle.get('kind', 'periodic')} "+ f"length {L} frames from {i}); the motion does not play smoothly")+ refuse(target, out_dir, name, {**report_base, "status": "failed", "error": error, "cycle": cycle})+ raise SystemExit(error)for line in left:print(f"video-loop: warning: {line} — a jump played as filmed; --unfixed refuse refuses such a loop ""(docs/loop-repair.md section 2)", file=sys.stderr)+ for line in pops_left:+ print(f"video-loop: warning: {line}; --unfixed refuse refuses such a loop (docs/loop-repair.md section 2, "+ '"The part pop")', file=sys.stderr)for line in warnings:print(f"video-loop: warning: {line} (reference bound; the loop is kept — docs/loop-repair.md)", file=sys.stderr)if "ghost_given_way" not in report_base:@@ -2596,7 +2683,7 @@ def add_arguments(parser: argparse.ArgumentParser) -> None: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. A loop that is not a walk or run is not read for its flow: where its wrap steps over --seam-max times the mean of the three steps either side, one, two or four frames round it are made again by RIFE between the frames either side, the fewest first, taken only without faults and where every step from one to the other then reads within that limit (docs/loop-repair.md section 2, \"The seam bridge\"). 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("--overlap-wrap", choices=OVERLAP_WRAP_MODES, default="on", help="--anchor motion-auto, under --repair auto or on: on (default): a cut two steps long whose wrap a part on its own beat leaves open (the seam gate refuses it) has four to twelve frames beside its wrap made again between the clip's frames a cycle apart and its own, each read with RIFE's single passes for a part torn — 34 calls of the binary a frame, up to forty frames (docs/loop-repair.md section 2, \"The overlapped wrap\"); off: not tried, recorded `wrap_overlap.skipped` with a warning line, and the gate refuses the cut as filmed — for a host whose RIFE runs on a CPU, where one frame of a 960 px clip takes minutes")parser.add_argument("--wrap-blend", choices=wrap_blend_mod.MODES, default="auto", help="--cycle pinned with --anchor none: auto (default): where the pinned last frame draws the first again (the first frame and it differ by more than --seam-max times the cut's median step, at full size), the last half second of the cut takes the first frame's drawing back in a ramp, only where the two ends differ by a redraw and the cell stands where the pin stands; a ramp that steps more than the cut already does, or does not shrink the wrap, is not used and a warning line says so (report `wrap_blend`, docs/loop-repair.md section 6); off: the cut as filmed")- parser.add_argument("--unfixed", choices=UNFIXED_MODES, default="warn", help="walk/run, under --repair auto or on: a frame the jump repair leaves off the walk's flow — no group of up to two drawings brings it back, or the group that would was refused (its RIFE frame had a fault) — is recorded in jump_repair.unfixed; warn (default): a warning line, the loop kept; refuse: the loop fails")+ parser.add_argument("--unfixed", choices=UNFIXED_MODES, default="warn", help="walk/run: a frame the jump repair leaves off the walk's flow (under --repair auto or on) — no group of up to two drawings brings it back, or the group that would was refused (its RIFE frame had a fault) — is recorded in jump_repair.unfixed; a part the size of a hand or a foot that pops at the wrap of the cut taken — the cut kept as cut — in part_pop.left, a take to film again (retake, reason part-pop; docs/loop-repair.md section 2, \"The part pop\"); warn (default): a warning line, the loop kept; refuse: the loop fails")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("--seam-pop-max", type=_seam_pop_max, default=repair_mod.SEAM_POP_REFERENCE, metavar="BOUND|off",@@ -2691,6 +2778,12 @@ def run(**kwargs: object) -> int:summary["jump_repair"]["eased"] = eased[0]["replaced"]if payload.get("jump_repair", {}).get("unfixed"):summary.setdefault("jump_repair", {})["unfixed"] = [u["frames"] for u in payload["jump_repair"]["unfixed"]]+ if payload.get("part_pop", {}).get("pops"):+ popped = payload["part_pop"]+ summary["part_pop"] = {"pops": [{k: p[k] for k in ("from", "to", "at", "body_pct", "kind", "margin")} for p in popped["pops"]],+ "outcome": popped["outcome"], "left": [[p["from"], p["to"]] for p in popped["left"]]}+ if payload.get("retake"):+ summary["retake"] = {k: payload["retake"][k] for k in ("reason", "remedy")}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 0diff --git a/sprite_gen/video/part_pop.py b/sprite_gen/video/part_pop.pynew file mode 100644index 0000000..4c6b324--- /dev/null+++ b/sprite_gen/video/part_pop.py@@ -0,0 +1,307 @@+# SPDX-License-Identifier: Apache-2.0+"""A part the size of a hand or a foot that pops at a walk loop's wrap, read on the part itself (docs/loop-repair.md+section 2, "The part pop"): the loop is cut as it was, and a part that pops at its wrap is named, a take to film again.++The flow reading reads the loop in windows half the body's box each way (`repair.FLOW_GRID`). A hand that jumps a few+per cent of the body height at the wrap and stays there is a small share of such a window, whose usual step the tail and+the legs passing through it set; a part that jumps once and goes on is half of the flow's `off` (the change of its step);+and a step of the blurred state stops growing once the hand is further than the blur from where it was. So the jump+reads under every limit there — the synthetic walker of tests/video/test_loop_part_pop.py, its fist jumping 3.5 % of+its height back at the wrap, reads 1.46 off the flow at most and no rush — and windows small enough to see the hand read+the loop's ordinary steps over the same limits.++The part reading follows the parts instead (`track`): squares PART_PATCH of the body height on a side, seeded every+PART_PATCH over the body on the loop's first drawing, each found drawing to drawing by normalised cross-correlation of+its luma (alpha weighted over a mid grey) within PART_SEARCH of where it was, at a body height of PART_READ px, to a+fraction of a pixel. A step is counted only where it reads back: the patch where the part landed, looked for in the+drawing before, lands within PART_FOLLOW of where the part was, and no search reached its edge. A part any of whose steps+does not read back — fur whose pattern repeats, an eye that closes, a part whose drawing changes at the wrap — is not+followed, and nothing is read on it.++A part does not move evenly: a tail swings slow, fast and slow again. So a run of one or two steps (`repair.SURGE_SPAN`)+is read against the curve the part's own steps either side of it draw, not against their mean: the `repair.SURGE_AROUND`+steps before it and after it, each a step vector, fitted by a second-degree polynomial in time (least squares, x and y+apart: the local fit of a Savitzky-Golay filter), and the run's steps predicted on it. How far the run's steps leave+their prediction is its `jerk` (`part_runs`). A part that eases steps where the curve goes, however fast; a frame that+jumps does not. A part pops (`pops`) where the run is, all at once:+- at least PART_POP_FLOOR of the body height (its largest step);+- off the curve by at least `repair.SURGE_LIMIT` of the part's usual step: its median step, no less than the median of+ the followed parts' medians (`repair._flow_scale`'s rule, so a part that hardly moves is not read on its noise) nor+ PART_NOISE;+- off it by at least PART_POP_CURVE times the step the curve predicts there (or the curve's own scatter over the steps it+ was fitted to, or PART_NOISE, whichever is larger);+- off it by at least PART_POP_LEAD times the part's largest jerk anywhere else in the loop.+Its way is not read: a part that comes back the next step is `flung`, one that stays where the run put it `stays`.+Tails, hems, hair and feet that move far inside the loop leave their curve as far there too (the lead); a tremor stays+under the floor. Read against the mean of the steps either side instead, as the engine's surge reading reads a window+(6 times it, and 1.5 times the part's largest step elsewhere), a part that eases through a fast stretch of three or four+steps is named; against its curve it is not (docs/loop-repair.md section 2, "The part pop", has the paths measured).++Frames made between two at the wrap do not mend it: the part's jump is still in the clip, spread over a step or two. Nor+is another cut taken for it: this reading reads parts the size of a hand, not the whole body's change at the wrap, and a+cut chosen on it alone is not held to the whole body. So the loop as it plays is read here, and a pop is named+(`part_pop`) and recorded a take to film again (video-loop's `retake`, reason `part-pop`)."""++from __future__ import annotations++from collections.abc import Iterable+from typing import Any++from PIL import Image++from sprite_gen._deps import np+from sprite_gen.video import repair++PART_READ = 400 # px: the body height parts are read at+PART_PATCH = 0.08 # of the body height: a part's square, seeded every PART_PATCH over the body+PART_SEARCH = 0.08 # of the body height: how far a part is looked for from where it was, either way+PART_SEEN = 0.15 # a square less covered than this is background, not a part+PART_TEXTURE = 0.02 # a square whose luma varies less than this (std) has nothing to follow+PART_FOLLOW = 1.5 # px at PART_READ: a step read back lands within this of where the part was, or the part is not followed+PART_NOISE = 0.5 # px at PART_READ: the least usual step a part is read against+PART_POP_FLOOR = 0.02 # of the body height: a pop's largest step at least this+PART_POP_CURVE = 5.0 # a pop's jerk at least this many times the step the curve of the steps either side predicts there+PART_POP_LEAD = 2.0 # ... and this many times the part's largest jerk anywhere else in the loop+PART_FLUNG = 0.5 # the step after a pop taking back this share of it, or the pop this share of the step before: flung+PART_MIN_DRAWINGS = 2 * repair.SURGE_AROUND + repair.SURGE_SPAN # a run and the steps either side, none shared+++def body_rows(frames: list[Image.Image], box: tuple[int, int, int, int]) -> int:+ """The body's height over the loop inside `box`, px: from the highest row any frame covers to the lowest (alpha over+ a tenth, as the flow reading reads it)."""+ rows = np.where(np.max([np.asarray(f.crop(box).getchannel("A")).max(axis=1) for f in frames], axis=0) > 25)[0]+ return int(rows.max() - rows.min()) if rows.size else 0+++def _plane(frame: Image.Image, box: tuple[int, int, int, int], size: tuple[int, int], pad: int) -> tuple[np.ndarray, np.ndarray]:+ """A drawing as the parts are followed on it: its luma over a mid grey by its coverage, and its coverage, inside+ `box`, averaged down to `size` and padded by `pad` (grey, nothing covered)."""+ x = np.asarray(frame.crop(box), dtype=np.float32) / 255.0+ alpha = x[..., 3]+ luma = (x[..., :3] @ np.array([0.299, 0.587, 0.114], dtype=np.float32)) * alpha + 0.5 * (1 - alpha)++ def small(a: np.ndarray) -> np.ndarray:+ return np.asarray(Image.fromarray(np.ascontiguousarray(a, dtype=np.float32)).resize(size, Image.BOX), dtype=np.float32)++ return np.pad(small(luma), pad, constant_values=0.5), np.pad(small(alpha), pad, constant_values=0.0)+++def _found(regions: np.ndarray, templates: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:+ """Where each template best matches inside its region by normalised cross-correlation, (m, 2R + P, 2R + P) regions and+ (m, P, P) templates: the offset of the best window from the region's centre, y and x, each to a fraction of a cell on+ the parabola through the correlations either side (none at the region's edge), its correlation, and whether the best+ window is at the region's edge. Read in one transform for every part."""+ m, size, _ = regions.shape+ P = templates.shape[1]+ D = size - P + 1+ R = D // 2+ t = templates.astype(np.float64)+ t -= t.mean(axis=(1, 2), keepdims=True)+ tn = np.sqrt((t * t).sum(axis=(1, 2)))+ r = regions.astype(np.float64)+ num = np.fft.irfft2(np.fft.rfft2(r, s=(size, size)) * np.conj(np.fft.rfft2(t, s=(size, size))), s=(size, size))[:, :D, :D]++ def window_sums(a: np.ndarray) -> np.ndarray:+ c = np.zeros((m, size + 1, size + 1))+ c[:, 1:, 1:] = a.cumsum(axis=1).cumsum(axis=2)+ return c[:, P:, P:] - c[:, :-P, P:] - c[:, P:, :-P] + c[:, :-P, :-P]++ s1, s2 = window_sums(r), window_sums(r * r)+ den = np.sqrt(np.maximum(s2 - s1 * s1 / (P * P), 0.0)) * tn[:, None, None]+ ncc = np.where(den > 1e-9, num / np.where(den > 1e-9, den, 1.0), -1.0)+ flat = ncc.reshape(m, -1).argmax(axis=1)+ iy, ix = flat // D, flat % D+ at = np.arange(m)+ best = ncc[at, iy, ix]++ def bend(lo: np.ndarray, hi: np.ndarray) -> np.ndarray:+ b = lo - 2 * best + hi+ return np.where(b < -1e-9, 0.5 * (lo - hi) / np.where(b < -1e-9, b, -1.0), 0.0)++ inside_x, inside_y = (ix > 0) & (ix < D - 1), (iy > 0) & (iy < D - 1)+ fx = np.where(inside_x, bend(ncc[at, iy, np.maximum(ix - 1, 0)], ncc[at, iy, np.minimum(ix + 1, D - 1)]), 0.0)+ fy = np.where(inside_y, bend(ncc[at, np.maximum(iy - 1, 0), ix], ncc[at, np.minimum(iy + 1, D - 1), ix]), 0.0)+ return iy - R + fy, ix - R + fx, best, ~(inside_x & inside_y)+++def track(frames: list[Image.Image], box: tuple[int, int, int, int], body: int) -> tuple[list[dict[str, Any]], dict[str, Any]]:+ """The parts of a loop's drawings `frames` (in play order, the last followed by the first) followed round the loop+ (the module text): per part followed, its `seed` (px of the frame, where it was seeded on the first drawing) and `pts`+ (n + 1 places, (x, y) px at PART_READ inside the padded box, the last the first drawing's again, reached round the+ loop). A part is dropped at its first step that does not read back. Also how the parts were read (`meta`): the scale,+ the square, the search, the padding and how many parts were seeded."""+ s = PART_READ / body+ P = max(8, int(round(PART_PATCH * PART_READ)))+ R = max(4, int(round(PART_SEARCH * PART_READ)))+ pad = R + P + 2+ x0, y0, x1, y1 = box+ size = (max(1, int(round((x1 - x0) * s))), max(1, int(round((y1 - y0) * s))))+ planes = [_plane(f, box, size, pad) for f in frames]+ luma = [p[0] for p in planes]+ H, W = luma[0].shape+ n = len(frames)+ h = P // 2+ seeds = [(cx, cy) for cy in range(pad + h, H - pad - h + 1, P) for cx in range(pad + h, W - pad - h + 1, P)+ if planes[0][1][cy - h:cy - h + P, cx - h:cx - h + P].mean() >= PART_SEEN+ and luma[0][cy - h:cy - h + P, cx - h:cx - h + P].std() >= PART_TEXTURE]+ lo, hi_x, hi_y = R + h + 1, W - R - h - 2, H - R - h - 2++ def search(at: np.ndarray, source: int, target: int) -> tuple[np.ndarray, np.ndarray]:+ """From each place `at` ((m, 2) x, y), the square there in drawing `source` looked for in drawing `target`: where+ it lands and whether the search reached its edge."""+ ix = np.clip(np.round(at[:, 0]), lo, hi_x).astype(int)+ iy = np.clip(np.round(at[:, 1]), lo, hi_y).astype(int)+ templates = np.stack([luma[source][y - h:y - h + P, x - h:x - h + P] for x, y in zip(ix, iy)])+ regions = np.stack([luma[target][y - R - h:y + R + h + (P - 2 * h), x - R - h:x + R + h + (P - 2 * h)] for x, y in zip(ix, iy)])+ dy, dx, _, edge = _found(regions, templates)+ return np.stack([at[:, 0] + dx, at[:, 1] + dy], axis=1), edge++ pts = np.zeros((len(seeds), n + 1, 2))+ pts[:, 0] = np.array(seeds, dtype=float).reshape(-1, 2)+ alive = np.arange(len(seeds))+ for k in range(n):+ if not alive.size:+ break+ landed, edge = search(pts[alive, k], k, (k + 1) % n)+ back, _ = search(landed, (k + 1) % n, k)+ pts[alive, k + 1] = landed+ kept = ~edge & (np.hypot(*(back - pts[alive, k]).T) <= PART_FOLLOW)+ alive = alive[kept]+ kept = set(alive.tolist())+ parts = [{"seed": [int(round(x0 + (sx - pad) / s)), int(round(y0 + (sy - pad) / s))], "pts": pts[i]}+ for i, (sx, sy) in enumerate(seeds) if i in kept]+ return parts, {"scale": s, "patch": P, "search": R, "pad": pad, "seeded": len(seeds)}+++def _runs(n: int) -> list[list[int]]:+ """Every run of 1..SURGE_SPAN steps of a ring of `n`, from each step."""+ return [[(d + i) % n for i in range(r)] for r in range(1, repair.SURGE_SPAN + 1) for d in range(n)]+++def _curve(run_length: int) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:+ """For a run of `run_length` steps: the offsets of the SURGE_AROUND steps either side of it from its first step, a+ second-degree polynomial's terms there and its least-squares fit through them (their pseudo-inverse), and its terms at+ the run's own steps."""+ K = repair.SURGE_AROUND+ at = np.array([*range(-K, 0), *range(run_length, run_length + K)], dtype=float)+ inside = np.arange(run_length, dtype=float)+ X = np.stack([at ** 0, at, at * at], axis=1)+ return at.astype(int), X, np.linalg.pinv(X), np.stack([inside ** 0, inside, inside * inside], axis=1)+++def part_runs(pts: np.ndarray, usual: float, runs: Iterable[list[int]]) -> list[dict[str, Any]]:+ """The readings of a part's path `pts` (n + 1 places, px) over each of `runs` (step indices, step k from drawing k to+ the next) against the curve the part's steps either side draw (the module text): the SURGE_AROUND steps before the run+ and after it, each a step vector, fitted x and y apart by a second-degree polynomial in time (least squares, the local+ fit of a Savitzky-Golay filter), and the run's steps predicted on it. Per run: its largest step `px`; `jerk`, the mean+ length of its steps off their prediction (px), `predicted`, the mean length of the predicted steps, and `fit`, the+ root mean square of the steps either side off the curve; `speed` (the jerk over `usual`), `curve` (over the larger of+ the predicted step, the fit and PART_NOISE), `lead` (over the part's largest jerk on a run as long whose curve was+ fitted without this run's steps, 0 where the loop holds none); whether it `pops` (the four at their bounds, the floor in px at PART_READ) and its `kind` — `flung` where+ the step after it takes back PART_FLUNG of its move or it takes back that share of the step before, else `stays` —+ with `back`, the larger of those shares."""+ step = np.diff(pts, axis=0)+ m = np.hypot(step[:, 0], step[:, 1])+ n = len(m)+ runs = [list(run) for run in runs]+ read: dict[int, dict[str, np.ndarray]] = {}+ for r in {len(run) for run in runs}:+ at, X, fit_of, terms = _curve(r)+ start = np.arange(n)+ V = step[(start[:, None] + at[None, :]) % n] # (n, 2K, 2): the steps either side of the run from each step+ coef = np.einsum("pk,nkc->npc", fit_of, V)+ pred = np.einsum("ip,npc->nic", terms, coef)+ own = step[(start[:, None] + np.arange(r)[None, :]) % n]+ scatter = V - np.einsum("kp,npc->nkc", X, coef)+ read[r] = {"jerk": np.hypot(*(own - pred).transpose(2, 0, 1)).mean(axis=1),+ "predicted": np.hypot(*pred.transpose(2, 0, 1)).mean(axis=1),+ "fit": np.sqrt((scatter ** 2).sum(axis=2).mean(axis=1))}+ out = []+ for run in runs:+ r = len(run)+ d, e = run[0], run[-1]+ x = read[r]+ jerk = float(x["jerk"][d])+ # elsewhere: a run as long whose curve was fitted without this run's steps — beside it, a run's curve takes some of+ # this run's jump into its fit, and its own jerk with it+ apart = [k for k in range(n) if not {(k + i) % n for i in range(-repair.SURGE_AROUND, r + repair.SURGE_AROUND)} & set(run)]+ # a loop too short to hold a run as long whose curve leaves this one out has nothing to lead: it does not pop+ lead = jerk / max(float(x["jerk"][apart].max()), 1e-9) if apart else 0.0+ speed = jerk / usual+ curve = jerk / max(float(x["predicted"][d]), float(x["fit"][d]), PART_NOISE)+ move = step[run].sum(axis=0)+ size = max(float(np.hypot(*move)), 1e-9)+ back = max(1 - float(np.hypot(*(move + step[(e + 1) % n]))) / size, 1 - float(np.hypot(*(step[(d - 1) % n] + move))) / size)+ largest = float(m[run].max())+ out.append({"steps": run, "px": largest, "jerk": jerk, "predicted": float(x["predicted"][d]), "fit": float(x["fit"][d]),+ "speed": speed, "curve": curve, "lead": lead,+ "pops": (largest >= PART_POP_FLOOR * PART_READ and speed >= repair.SURGE_LIMIT and curve >= PART_POP_CURVE+ and lead >= PART_POP_LEAD),+ "kind": "flung" if back >= PART_FLUNG else "stays", "back": back})+ return out+++def margin(said: dict[str, Any]) -> float:+ """How far a run (`part_runs`) is from popping: the least of its step, speed, curve and lead over their bounds; 1 or+ more pops."""+ return min(said["px"] / (PART_POP_FLOOR * PART_READ), said["speed"] / repair.SURGE_LIMIT, said["curve"] / PART_POP_CURVE,+ said["lead"] / PART_POP_LEAD)+++def read(frames: list[Image.Image], *, drawings: tuple[list[list[int]], int] | None = None,+ steps: Iterable[int] | None = None) -> dict[str, Any]:+ """The part reading of a loop as it plays (the module text), on its drawings (`repair.flow_drawings`, or `drawings`+ (runs, hold) given): the parts seeded and followed, and per followed part the runs of one or two steps that touch+ `steps` (step indices on the drawings; the wrap, from the last drawing to the first, where none are given) — a part+ that pops there is in `pops`, worst first by margin, at most one a part; `nearest`, the run nearest to popping of all.++ Each run as said: the part (`seed`, px of the loop's first frame), the frames it runs `from` and `to` (first frames of+ its drawings), `steps`, `at` (px of the frame it runs from, where the part is), `body_pct` (its largest step),+ `jerk_pct`, `usual_px`, `speed`, `curve`, `lead`, `kind`, `back` and `margin`. A loop of fewer than PART_MIN_DRAWINGS+ drawings is not read (`skipped`)."""+ box = repair.union_box(frames)+ runs, hold = drawings if drawings is not None else repair.flow_drawings(repair.flow_states(frames, box))+ n = len(runs)+ body = body_rows(frames, box)+ record: dict[str, Any] = {"read_px": PART_READ, "patch": PART_PATCH, "search": PART_SEARCH, "follow_px": PART_FOLLOW,+ "floor": PART_POP_FLOOR, "speed": repair.SURGE_LIMIT, "curve": PART_POP_CURVE,+ "lead": PART_POP_LEAD, "drawings": n, "hold": hold, "body_px": body, "pops": [], "nearest": None}+ if n < PART_MIN_DRAWINGS or body < 2:+ record.update(skipped=f"a loop of {n} drawings, under {PART_MIN_DRAWINGS}: no steps either side of a run to read it against",+ parts=0, followed=0)+ return record+ parts, meta = track([frames[run[0]] for run in runs], box, body)+ record.update(parts=meta["seeded"], followed=len(parts))+ if not parts:+ return record+ medians = [float(np.median(np.hypot(*np.diff(p["pts"], axis=0).T))) for p in parts]+ floor = max(float(np.median(medians)), PART_NOISE)+ record["usual_floor_px"] = round(floor, 3)+ at_steps = set(range(n - 1, n) if steps is None else steps)+ asked = [run for run in _runs(n) if set(run) & at_steps]+ said_all = []+ for part, median in zip(parts, medians):+ usual = max(median, floor)+ best = None+ for x in part_runs(part["pts"], usual, asked):+ d, e = x["steps"][0], x["steps"][-1]+ p = part["pts"][d]+ said = {"seed": part["seed"], "from": runs[d][0], "to": runs[(e + 1) % n][0], "steps": x["steps"],+ "at": [round(box[0] + (p[0] - meta["pad"]) / meta["scale"], 1), round(box[1] + (p[1] - meta["pad"]) / meta["scale"], 1)],+ "body_pct": round(100 * x["px"] / PART_READ, 3), "jerk_pct": round(100 * x["jerk"] / PART_READ, 3),+ "usual_px": round(usual, 3), "speed": round(x["speed"], 3), "curve": round(x["curve"], 3),+ "lead": round(x["lead"], 3), "kind": x["kind"], "back": round(x["back"], 3),+ "pops": x["pops"], "margin": round(margin(x), 3)}+ if best is None or (said["pops"], said["margin"]) > (best["pops"], best["margin"]):+ best = said+ if best is not None:+ said_all.append(best)+ if said_all:+ record["nearest"] = {k: v for k, v in max(said_all, key=lambda x: x["margin"]).items() if k != "pops"}+ record["pops"] = sorted((x for x in said_all if x["pops"]), key=lambda x: -x["margin"])+ return record+++def public(reading: dict[str, Any]) -> dict[str, Any]:+ """A reading as a report holds it: each pop without its `pops` flag, which the list says."""+ return {**reading, "pops": [{k: v for k, v in p.items() if k != "pops"} for p in reading["pops"]]}diff --git a/tests/video/test_loop_part_pop.py b/tests/video/test_loop_part_pop.pynew file mode 100644index 0000000..ca02cfb--- /dev/null+++ b/tests/video/test_loop_part_pop.py@@ -0,0 +1,377 @@+# SPDX-License-Identifier: Apache-2.0+"""The part pop (docs/loop-repair.md section 2, "The part pop"): a part the size of a hand that jumps 2 to 5 % of the+body's height at a walk loop's wrap and stays there passes the flow reading and the surge reading, which read the loop in+windows half the body's box each way; the part reading follows the parts themselves and names it. The loop is cut as+it was, the search's cut or the cut given, to the same bytes: the pop is named in a warning line, the report records a+take to film again (`retake`, reason `part-pop`; `remedy` `retake` for the search's cut, `recut-or-retake` for a cut+given), and `--unfixed refuse` refuses the loop. A walk whose tail swings, whose foot lifts and whose eye blinks across+the wrap has no part pop, and its loop is the bytes it was.++The boundary is pinned on parts' paths: each of the floor, the speed, the curve and the lead flips the pop where it is+crossed, the share of it the next step takes back flips `flung` and `stays`, and a part that eases through a fast stretch+is not a pop. The walkers are drawn here. Synthetic frames only."""++from __future__ import annotations++import json+import math+import random+from pathlib import Path++import numpy as np+import pytest+from PIL import Image, ImageDraw++from sprite_gen.video import loop, part_pop, repair++W, H, N = 240, 300, 36+STANCE_END = 0.16 # of a cycle: where the legs' swing turns, at the loop's first frame+++# --- the boundary, on parts' paths ------------------------------------------------------------------------------------+++def _path(steps: list[tuple[float, float]]) -> np.ndarray:+ """A part's places from its steps: n steps, n + 1 places, the last step the wrap."""+ return np.concatenate([[[0.0, 0.0]], np.cumsum(np.array(steps, dtype=float), axis=0)])+++def _wrap(steps: list[tuple[float, float]], usual: float) -> dict:+ """The part's reading over the wrap step alone (the last)."""+ n = len(steps)+ return part_pop.part_runs(_path(steps), usual, [[n - 1]])[0]+++def _ordinary(n: int, size: float = 1.0) -> list[tuple[float, float]]:+ return [(size, 0.0)] * n+++FLOOR_PX = part_pop.PART_POP_FLOOR * part_pop.PART_READ # 8 px at a body height of 400+HAIR = 1e-6 # a hair's breadth either side of a bound, as a share of it+++def _far(said: dict, *but: str) -> None:+ """Every term of the run but `but` is well past its bound."""+ bounds = {"px": FLOOR_PX, "speed": repair.SURGE_LIMIT, "curve": part_pop.PART_POP_CURVE, "lead": part_pop.PART_POP_LEAD}+ assert all(said[k] >= 1.1 * v for k, v in bounds.items() if k not in but), said++[email protected]("wrap,pops", [(FLOOR_PX, True), (FLOOR_PX - 1 / 64, False)])+def test_the_floor_flips_the_pop_at_two_percent_of_the_body(wrap, pops):+ said = _wrap(_ordinary(23) + [(wrap, 0.0)], usual=1.0)+ _far(said, "px")+ assert said["px"] == wrap and said["jerk"] == pytest.approx(wrap - 1.0) # a still curve: one px a step+ assert said["pops"] is pops++[email protected]("usual,pops", [(4.0 * (1 - HAIR), True), (4.0 * (1 + HAIR), False)])+def test_the_speed_flips_the_pop_at_three_usual_steps_off_the_curve(usual, pops):+ # 12.5 px where the curve gives 0.5: 12 px off it, three usual steps of 4+ said = _wrap(_ordinary(23, 0.5) + [(12.5, 0.0)], usual=usual)+ _far(said, "speed")+ assert said["pops"] is pops++[email protected]("off,pops", [(10.0 * (1 + HAIR), True), (10.0 * (1 - HAIR), False)])+def test_the_curve_flips_the_pop_at_five_times_the_step_it_predicts(off, pops):+ # the part steps 2 px a step; at the wrap `off` px past that: five times the 2 px the curve gives there+ said = _wrap(_ordinary(23, 2.0) + [(2.0 + off, 0.0)], usual=1.0)+ _far(said, "curve")+ assert said["predicted"] == pytest.approx(2.0) and said["fit"] == pytest.approx(0.0, abs=1e-9)+ assert said["pops"] is pops++[email protected]("elsewhere,pops", [(6.0 * (1 - HAIR), True), (6.0 * (1 + HAIR), False)])+def test_the_lead_flips_the_pop_at_twice_the_parts_largest_jerk_elsewhere(elsewhere, pops):+ # a part that leaves its curve by `elsewhere` in one step inside the loop (a tail's flick) leaves it at the wrap as its+ # own motion: 12 px off at the wrap is twice 6+ steps = _ordinary(24)+ steps[10] = (1.0 + elsewhere, 0.0)+ steps[23] = (13.0, 0.0)+ said = _wrap(steps, usual=1.0)+ _far(said, "lead")+ assert said["lead"] == pytest.approx(12.0 / elsewhere)+ assert said["pops"] is pops++[email protected]("back,kind", [(6.0, "flung"), (6.0 - 1 / 64, "stays")])+def test_a_pop_the_next_step_takes_half_of_back_is_flung_else_it_stays(back, kind):+ steps = _ordinary(24)+ steps[23] = (12.0, 0.0)+ steps[0] = (-back, 0.0)+ said = _wrap(steps, usual=1.0)+ assert said["kind"] == kind and said["back"] == pytest.approx(back / 12.0)+++def test_a_pop_over_two_steps_is_read_as_their_mean_against_the_curve_beyond_them():+ steps = _ordinary(24)+ steps[22], steps[23] = (10.0, 0.0), (10.0, 0.0)+ one, two = part_pop.part_runs(_path(steps), 1.0, [[23], [22, 23]])+ assert not one["pops"] # the step beside it pulls its curve up: the one step is half explained+ assert two["pops"] and two["jerk"] == pytest.approx(9.0) and two["predicted"] == pytest.approx(1.0)++[email protected]("width", [3, 4, 5, 6, 8])[email protected]("peak", [12.0, 20.0, 40.0])+def test_a_part_that_eases_through_a_fast_stretch_does_not_pop_where_the_mean_of_its_neighbours_named_it(width, peak):+ """Slow, fast, slow: a tail that flicks over `width` steps, its speed a sin² bell to `peak` px a step (up to a tenth of+ the body), across the wrap. Its curve follows the ease; the mean of the steps either side, the first definition's+ baseline, does not (6 times it and 1.5 times the part's largest step elsewhere named every bell of three and four+ steps)."""+ n = 36+ steps = [(1.0 + 0.3 * math.sin(2 * math.pi * k / n), 0.4 * math.cos(2 * math.pi * k / n)) for k in range(n)]+ first = (n - width // 2 - 1) % n+ for i in range(width):+ x, y = steps[(first + i) % n]+ steps[(first + i) % n] = (x + peak * math.sin(math.pi * (i + 0.5) / width) ** 2, y)+ said = part_pop.part_runs(_path(steps), 1.0, [[n - 1], [n - 2, n - 1], [n - 1, 0]])+ assert not any(x["pops"] for x in said), said+++# --- the side walker -----------------------------------------------------------------------------------------------+++# Spots drawn on the torso and the head where they are, as a painted body has shading to follow: px from the torso's and+# the head's top left, radius and shade.+_SPOTS = random.Random(7)+TORSO_SPOTS = [(_SPOTS.uniform(6, 44), _SPOTS.uniform(6, 79), _SPOTS.uniform(1.5, 3.0), _SPOTS.choice((90, 150, 250))) for _ in range(28)]+HEAD_SPOTS = [(_SPOTS.uniform(10, 50), _SPOTS.uniform(6, 22), _SPOTS.uniform(1.5, 2.5), _SPOTS.choice((120, 180))) for _ in range(10)]+++def _hand_slip(slip_pct: float) -> float:+ return slip_pct / 100 * 243 # px: the walker's height over its loop, head to feet+++def _walker(phase: float, *, hand: tuple[float, float], eye_shut: bool = False, lift: float = 0.0) -> Image.Image:+ """The walker at `phase` of its cycle (0..1), seen from the side: a tail behind it swinging once a cycle, two legs+ quick through the swing and slow through the stance (the loop's wrap at the stance's end, where they hardly move), the+ far foot `lift` px off its line, a torso and a head with an eye (shut: a line), and a forearm held out in front ending+ in a fist, held where it is as the body bobs, the two `hand` px off their place."""+ im = Image.new("RGBA", (W, H), (0, 0, 0, 0))+ d = ImageDraw.Draw(im)+ phi = 2 * math.pi * (phase + STANCE_END)+ bob = 3 * math.cos(2 * phi)+ tx, ty = 62 + 26 * math.sin(phi), 135 + bob - 12 * math.cos(phi)+ d.polygon([(104, 120 + bob), (104, 150 + bob), (tx - 18, ty + 20), (tx - 28, ty - 24)], fill=(220, 120, 40, 255))+ d.ellipse((tx - 48, ty - 38, tx - 8, ty + 10), fill=(240, 150, 60, 255), outline=(120, 60, 20, 255), width=3)+ swing = 0.5 * math.sin(phi + 0.6 * math.sin(phi))+ for hip, angle, colour, up in ((120, swing, (70, 60, 120, 255), 0.0), (128, -swing, (90, 80, 150, 255), lift)):+ x1, y1 = hip + 95 * math.sin(angle), 175 + bob + 95 * math.cos(angle) - up+ d.line((hip, 175 + bob, x1, y1), fill=colour, width=16)+ d.ellipse((x1 - 12, y1 - 7, x1 + 14, y1 + 7), fill=(40, 30, 30, 255))+ d.rectangle((100, 100 + bob, 150, 185 + bob), fill=(200, 200, 220, 255), outline=(20, 20, 20, 255), width=3)+ for x, y, r, v in TORSO_SPOTS:+ d.ellipse((100 + x - r, 100 + bob + y - r, 100 + x + r, 100 + bob + y + r), fill=(v, v, v + 5, 255))+ d.ellipse((96, 40 + bob, 156, 102 + bob), fill=(240, 210, 180, 255), outline=(20, 20, 20, 255), width=3)+ for x, y, r, v in HEAD_SPOTS:+ d.ellipse((96 + x - r, 40 + bob + y - r, 96 + x + r, 40 + bob + y + r), fill=(v + 60, v, v - 40, 255))+ if eye_shut:+ d.line((134, 64 + bob, 146, 64 + bob), fill=(20, 20, 20, 255), width=3)+ else:+ d.ellipse((136, 58 + bob, 144, 70 + bob), fill=(20, 20, 20, 255))+ hx, hy = 196 + hand[0], 150 + hand[1]+ d.line((hx - 34, hy - 14, hx - 8, hy - 4), fill=(225, 195, 165, 255), width=10) # the forearm, out of the sleeve+ d.ellipse((hx - 13, hy - 12, hx + 13, hy + 12), fill=(240, 205, 170, 255), outline=(30, 20, 20, 255), width=3)+ d.line((hx + 2, hy - 8, hx + 2, hy + 8), fill=(120, 70, 50, 255), width=3) # the knuckles+ return im+++def _hand(k: float, n: int, slip: float) -> tuple[float, float]:+ """The fist's place at frame k of a loop of n: a little loop with the walk, and `slip` px over the loop, which it+ jumps back at the wrap and stays."""+ phi = 2 * math.pi * k / n+ return 1.5 * math.sin(phi) + slip * k / n, math.cos(phi)+++def _lift(k: float, n: int) -> float:+ """The far foot lifted round the wrap: up to 16 px, over the frames either side of it."""+ d = min((k + 0.5) % n, n - (k + 0.5) % n) # frames from the wrap, between the last frame and the first+ return 16 * math.exp(-(d / 2.5) ** 2)+++def _side(n: int = N, *, slip: float = 0.0, blink: tuple[int, ...] = (), lift: bool = False) -> list[Image.Image]:+ """The side walker's loop of `n` frames, its fist `slip` px off at the wrap, its eye shut at `blink`, its far foot+ lifted round the wrap where `lift`."""+ return [_walker(k / n, hand=_hand(k, n, slip), eye_shut=k in blink, lift=_lift(k, n) if lift else 0.0) for k in range(n)]+++def _keyed(root: Path, frames: list[Image.Image]) -> Path:+ keyed = root / "keyed"+ keyed.mkdir(parents=True)+ for k, f in enumerate(frames):+ f.save(keyed / f"{k:03}.png")+ return keyed+++def _cut(root: Path, frames: list[Image.Image], **kw) -> dict:+ """The loop cut whole as `video-loop --state walk --cycle fixed --anchor none` cuts it; the report, passed or not."""+ keyed = _keyed(root, frames)+ try:+ loop.run_loop(keyed, root / "out", fps=24.0, state="walk", min_len=None, max_len=None, n_out=None,+ seam_max=loop.SEAM_RATIO_MAX, name="loop", report_path=root / "loop.json", cycle_mode="fixed", start=0,+ length=len(frames), anchor="none", repair="off", **kw)+ except SystemExit as exc:+ (root / "exit.txt").write_text(str(exc))+ return json.loads((root / "loop.json").read_text())+++def _files(root: Path) -> dict[str, bytes]:+ out = root / "out"+ return {str(f.relative_to(out)): f.read_bytes() for f in sorted(out.rglob("*")) if f.suffix in (".png", ".gif", ".webp")}+++def _near_hand(pop: dict) -> bool:+ """The pop is the arm's held out in front: the part's square seeded over the fist or the arm's end on the first frame."""+ x, y = pop["seed"]+ return 160 <= x <= 225 and 110 <= y <= 180++[email protected]("slip_pct", [2.5, 3.5, 5.0])+def test_a_hand_that_pops_at_the_wrap_passes_the_flow_reading_and_the_part_reading_names_it(slip_pct):+ frames = _side(slip=_hand_slip(slip_pct))+ # the loop stage as it was: no frame off the flow, no rush — the hand is a small share of every window it is read in+ assert repair.flow_targets(frames)["groups"] == [] and repair.surges(frames) == []+ reading = part_pop.read(frames)+ assert reading["pops"], reading["nearest"]+ pop = reading["pops"][0]+ assert _near_hand(pop) and pop["kind"] == "stays" and (pop["from"], pop["to"]) == (N - 1, 0)+ (x0, y0), (x1, y1) = _hand(N - 1, N, _hand_slip(slip_pct)), _hand(0, N, _hand_slip(slip_pct))+ assert pop["body_pct"] == pytest.approx(100 * math.hypot(x1 - x0, y1 - y0) / reading["body_px"], abs=0.4)+ assert pop["margin"] >= 1.0 and all(_near_hand(p) for p in reading["pops"])+++def test_an_ordinary_walk_whose_tail_foot_and_eye_move_across_the_wrap_has_no_part_pop_anywhere():+ # its tail swings once a cycle, its far foot lifts 16 px and its eye shuts across the wrap: no part pops at the wrap,+ # nor at any step inside the loop+ frames = _side(blink=(N - 1, 0), lift=True)+ assert part_pop.read(frames)["pops"] == []+ assert part_pop.read(frames, steps=range(N))["pops"] == []+++def test_a_run_drawn_fast_has_no_part_pop_anywhere():+ # the same walker at 16 frames a cycle, a run: its legs swing 12 % of the body a frame and its foot lifts in three+ # frames across the wrap; the parts it moves fastest leave the search and are not followed, and none that is pops+ frames = _side(16, blink=(15, 0), lift=True)+ reading = part_pop.read(frames)+ assert reading["pops"] == [] and reading["followed"] < reading["parts"]+ assert part_pop.read(frames, steps=range(16))["pops"] == []+++def test_an_ordinary_walk_is_cut_to_the_bytes_it_was(tmp_path, monkeypatch):+ frames = _side(blink=(N - 1, 0), lift=True)+ report = _cut(tmp_path / "read", frames)+ assert report["status"] == "passed" and report["part_pop"]["pops"] == [] and report["part_pop"]["outcome"] == "none"+ assert report["retake"] is None+ # the same loop with the part reading reading nothing: every file the cut writes is the same bytes+ _unread(monkeypatch)+ _cut(tmp_path / "unread", frames)+ assert _files(tmp_path / "read") == _files(tmp_path / "unread")+++def _unread(monkeypatch) -> None:+ """The part reading reading nothing, as a cut was before it."""+ monkeypatch.setattr(part_pop, "read", lambda frames, **kw: {"pops": [], "nearest": None})+++def test_a_cut_given_whose_hand_pops_is_named_a_take_to_film_again_and_unfixed_refuse_refuses_it(tmp_path, capsys, monkeypatch):+ frames = _side(slip=_hand_slip(3.5))+ report = _cut(tmp_path / "warn", frames)+ assert report["status"] == "passed"+ pop = report["part_pop"]+ assert pop["outcome"] == "named" and pop["left"] == pop["pops"] and len(pop["pops"]) > 1 and _near_hand(pop["pops"][0])+ retake = report["retake"]+ assert (retake["reason"], retake["reasons"], retake["remedy"]) == ("part-pop", ["part-pop"], "recut-or-retake")+ assert retake["part_pop"]["cut"] == [0, N] and retake["part_pop"]["searched"] is False+ assert retake["limits"] == {"floor": part_pop.PART_POP_FLOOR, "speed": repair.SURGE_LIMIT, "curve": part_pop.PART_POP_CURVE,+ "lead": part_pop.PART_POP_LEAD}+ # the squares seeded on the one fist pop together: one line says the worst and how many pop with it+ err = capsys.readouterr().err+ lines = [line for line in err.splitlines() if "film this direction again (part-pop)" in line]+ assert len(lines) == 1 and f"; {len(pop['pops']) - 1} parts beside it pop with it)" in lines[0]+ assert lines[0].startswith("video-loop: warning: film this direction again (part-pop) — the part at")+ assert ("the cut was given (--cycle fixed or pinned): cut it where no part pops, or film it again; --unfixed refuse "+ "refuses such a loop" in lines[0])+ refused = _cut(tmp_path / "refuse", frames, unfixed="refuse")+ assert refused["status"] == "failed" and refused["error"].startswith(+ "video-loop: a part pops at the loop's wrap — film this direction again (part-pop) — the part at")+ assert refused["retake"]["reason"] == "part-pop"+ # the loop the pop is named in is the bytes it is with no part read at all+ _unread(monkeypatch)+ _cut(tmp_path / "unread", frames)+ assert _files(tmp_path / "warn") == _files(tmp_path / "unread")+++# --- the search, on a clip: a front walker whose fist drifts ---------------------------------------------------------++FRAMES, CYCLE = 73, 26+++def _front(k: float, hand: float) -> Image.Image:+ """The front walker of tests/video/test_loop_overlap.py with its tail on the walk's own beat, and a fist held out at+ its right `hand` px aside of its place, held where it is as the body bobs."""+ from tests.video.test_loop_overlap import _walker as front_walker++ phase = 2 * math.pi * k / CYCLE+ im = front_walker(k, (12 * math.sin(phase), 6 * math.cos(phase)))+ d = ImageDraw.Draw(im)+ cx, y = 150, 40 + round(2 * math.cos(2 * 2 * math.pi * (k + 5) / CYCLE))+ hx, hy = cx + 46 + hand, 100+ d.line((cx + 20, y + 40, hx - 4, hy), fill=(225, 225, 225, 255), width=5)+ d.ellipse((hx - 7, hy - 6, hx + 7, hy + 6), fill=(240, 205, 170, 255), outline=(30, 20, 20, 255), width=2)+ d.line((hx + 1, hy - 4, hx + 1, hy + 4), fill=(120, 70, 50, 255), width=2)+ return im+++def _drift(rate: float, until: int = FRAMES):+ """The fist's place at clip frame k: `rate` px a frame aside up to frame `until`, held there after."""+ return lambda k: rate * min(k, until)+++def _search(root: Path, hand, **kw) -> dict:+ """The front walker's clip cut as `video-loop --state walk --anchor motion-auto` cuts it; the report."""+ keyed = _keyed(root, [_front(k, hand(k)) for k in range(FRAMES)])+ try:+ loop.run_loop(keyed, root / "out", fps=24.0, state="walk", min_len=None, max_len=None, n_out=None,+ seam_max=loop.SEAM_RATIO_MAX, name="loop", report_path=root / "loop.json", anchor="motion-auto", **kw)+ except SystemExit as exc:+ (root / "exit.txt").write_text(str(exc))+ return json.loads((root / "loop.json").read_text())++++def test_a_clip_whose_fist_drifts_through_every_cut_keeps_the_search_s_cut_and_records_a_take_to_film_again(tmp_path, capsys, monkeypatch):+ """The fist drifts 0.18 px a frame through the whole clip: every cut of two steps, 26 frames, jumps it back 4.7 px at+ its wrap (3 % of the body). The search's cut is cut as it was, to the same bytes, and the pop is named: a take to+ film again, `remedy` `retake` (the search chose the cut)."""+ report = _search(tmp_path / "read", _drift(0.18))+ c = report["cycle"]+ assert report["status"] == "passed" and c["steps"] == {"count": 2, "by": "crossings"} and c["length"] == CYCLE+ assert "part_gate" not in c and "part_gate" not in (c.get("step_count") or {})+ pop = report["part_pop"]+ assert pop["outcome"] == "named" and pop["left"]+ retake = report["retake"]+ assert (retake["reason"], retake["remedy"]) == ("part-pop", "retake")+ assert retake["part_pop"]["searched"] is True and retake["part_pop"]["cut"] == [c["start"], c["length"]]+ err = capsys.readouterr().err+ assert ("film this direction again (part-pop) — the part at" in err+ and "the search's cut is kept as cut, and no other cut is taken for a part: film it again; --unfixed refuse "+ "refuses such a loop" in err)+ _unread(monkeypatch)+ unread = _search(tmp_path / "unread", _drift(0.18))+ assert unread["cycle"]["start"] == c["start"] and _files(tmp_path / "read") == _files(tmp_path / "unread")+++def test_a_clip_no_part_pops_in_is_cut_to_the_bytes_it_was(tmp_path, monkeypatch):+ """The fist held still: no part pops, nothing is recorded to film again, and the loop is the bytes it is with no part+ read at all."""+ report = _search(tmp_path / "read", _drift(0.0))+ assert report["status"] == "passed" and report["part_pop"]["outcome"] == "none" and report["retake"] is None+ _unread(monkeypatch)+ unread = _search(tmp_path / "unread", _drift(0.0))+ assert unread["cycle"]["start"] == report["cycle"]["start"] and _files(tmp_path / "read") == _files(tmp_path / "unread")