Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
fix(video-loop): drift is read on the torso the anchor tracks, and the overlapped wrap holds it to the stretch as played
Soohong Kimb83850c7f0c1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0769dad..2442e4e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,12 +4,12 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the## Unreleased-- **New: `video-loop --anchor motion-auto` closes a two-step cut's wrap that a part on its own beat leaves open, with the clip's frames a cycle apart.** A walk cut two steps long by the clip's crossings closes for the legs; a tail swinging round on a beat of its own closes on no cut of two steps, so the seam gate refused every one — and the eased retime does not reach it, since the part turns back at the wrap, where its frames read off the flow against the way. The clip goes on past the cut, and its frame a cycle after one of the cut's shows the legs at the same point of the walk. Under `--repair auto` (and `on`), where such a cut's wrap reads over `--seam-max` on its frames as corrected (`loop.wrap_on_cells`), the frames beside the wrap are made again before the jump repair (`repair.overlap_wrap`): each by RIFE between its two frames of one time — the clip's frame a cycle apart, moved by the analysis translation between the two and corrected as the cut frame was (`loop.cycle_apart`), and the cut's own — so the wrap plays a step the clip filmed and the part goes over to the cut's way over those frames, each frame at its own time. The weights (`repair.overlap_weights`) are the ease in and out x²(3 − 2x), held off it only in the steps where the rest of the body or a body measure, read on the line between the two frames, would go past its bound; a weight of 0 or 1 shows a frame whole, with no call. Four frames, then six (`OVERLAP_WIDTHS`), on the side — after the wrap or before it — whose frames a cycle apart differ least, never past half the loop; a run is taken only where no made frame has an interpolation fault, the gate passes it, the loop played round still covers two steps (`loop.ring_steps`), no body measure moves a pixel past the largest step there of either run its frames are made from — the stretch as the loop plays it and the frames a cycle apart as the clip filmed them, whose step into the run the wrap now plays — the part steps no further than over the stretch, no new rush is read, no window of the rest of the body steps further than its own largest step over either run, and no frame is left further off the flow over its limit (`rejected_for`). The jump repair after it makes nothing from, beside or again over those frames (`jump_repair.overlapped`). The report carries `wrap_overlap` (each try, and the run taken), the summary names it, and without RIFE the wrap is cut as filmed with a warning line (`--repair on` refuses). On the test walker (front, 26 frames a cycle, the tail on a 41-frame beat) the cut 29/26 reads 6.23 at the gate as filmed and 3.17 after the jump repair alone; four frames after the wrap rush the tail and are refused, six are taken, and the loop passes at 1.04, two steps ([loop-repair](docs/loop-repair.md#the-overlapped-wrap--a-part-on-its-own-beat-that-no-cut-of-two-steps-closes)).-- **Tests** — `tests/video/test_loop_overlap.py` (a front walker whose tail swings round on its own beat, refused at the seam on every cut of two steps, is closed at the wrap: each frame beside it made between the clip's frame a cycle apart and the cut's own at its eased weight, four frames refused for a rush and six taken, two steps on the loop played round, the body within its drift, the rest of it no faster, every other frame the clip's own and nothing made by the jump repair; `--repair off` refused as before; without RIFE cut as filmed with a warning, and with `--repair on` refused asking for it; a made frame with a fault refuses every run and the cut is kept as filmed; a weighting search on lines drawn by hand: the ease where nothing binds, held off it in the one step a window of the rest of the body is bounded in, none where a body measure may not move).+- **New: `video-loop --anchor motion-auto` closes a two-step cut's wrap that a part on its own beat leaves open, with the clip's frames a cycle apart.** A walk cut two steps long by the clip's crossings closes for the legs; a tail swinging round on a beat of its own closes on no cut of two steps, so the seam gate refused every one — and the eased retime does not reach it, since the part turns back at the wrap, where its frames read off the flow against the way. The clip goes on past the cut, and its frame a cycle after one of the cut's shows the legs at the same point of the walk. Under `--repair auto` (and `on`), where such a cut's wrap reads over `--seam-max` on its frames as corrected (`loop.wrap_on_cells`), the frames beside the wrap are made again before the jump repair (`repair.overlap_wrap`): each by RIFE between its two frames of one time — the clip's frame a cycle apart, moved by the analysis translation between the two and corrected as the cut frame was (`loop.cycle_apart`), and the cut's own — so the wrap plays a step the clip filmed and the part goes over to the cut's way over those frames, each frame at its own time. The weights (`repair.overlap_weights`) are the ease in and out x²(3 − 2x), held off it only in the steps where the rest of the body or a body measure, read on the line between the two frames, would go past its bound; a weight of 0 or 1 shows a frame whole, with no call, and a frame at one weight is made once, whatever the run. Four frames, then six, eight, ten and twelve (`OVERLAP_WIDTHS`), on the side — after the wrap or before it — whose frames a cycle apart differ least, never past half the loop; a run is taken only where no made frame has an interpolation fault, the gate passes it, the loop played round still covers two steps (`loop.ring_steps`), no body measure — the foot line, the torso, the ground — moves a pixel past the largest step of the stretch as the loop plays it (the eased retime's bound on the same torso, never the clip's frames a cycle apart: the part going over pulls the body's mass, which is reported, while a torso the clip's frame a cycle on shows elsewhere would slide) — the part steps no further than over the stretch, no new rush is read, no window of the rest of the body steps further than its own largest step over the stretch, and no frame is left further off the flow over its limit (`rejected_for`). The jump repair after it makes nothing from, beside or again over those frames (`jump_repair.overlapped`). The report carries `wrap_overlap` (each try, and the run taken), the summary names it, and without RIFE the wrap is cut as filmed with a warning line (`--repair on` refuses). It costs at most forty RIFE calls, where every width is made and refused. On the test walker (front, 26 frames a cycle, the tail on a 41-frame beat) the cut 29/26 reads 6.23 at the gate as filmed and 3.17 after the jump repair alone; four frames after the wrap rush the tail and are refused, six are taken, and the loop passes at 1.04, two steps, in ten calls. On a second walker whose big tuft bobs on the loop and a cycle on is carried 8 px aside a frame, the walker in its place, four frames are taken at the ease (3.41 → 1.53 at the gate, four calls): the torso moves 0.05 px, the body's mass 3.95 px against the stretch's 0.71, reported; where the whole walker also stands 3 px aside a cycle on, its torso sliding, every run is held at 0.85 of the cut's own frame next to the wrap, the wrap stays open and the cut is kept as filmed for the gate to refuse ([loop-repair](docs/loop-repair.md#the-overlapped-wrap--a-part-on-its-own-beat-that-no-cut-of-two-steps-closes)).+- **Tests** — `tests/video/test_loop_overlap.py` (a front walker whose tail swings round on its own beat, refused at the seam on every cut of two steps, is closed at the wrap: each frame beside it made between the clip's frame a cycle apart and the cut's own at its eased weight, once a frame and weight, four frames refused for a rush and six taken, two steps on the loop played round, the body within its drift, the rest of it no faster, every other frame the clip's own and nothing made by the jump repair; on a walker whose big tuft a cycle on is carried aside, every run's drift bound is the stretch's own as the loop plays it — the torso's, which stands still there, never the clip's frames a cycle apart — and the body's mass is reported beside it; with the tuft alone carried over the run is taken near the ease, the torso within its pixel while the mass moves 2 px and more past its own; with the whole walker also standing aside a cycle on, its torso sliding, no run moves it more than a pixel in a step on the frames shown, drawn again, the frame next to the wrap is held off the ease and the cut is kept as filmed; `--repair off` refused as before; without RIFE cut as filmed with a warning, and with `--repair on` refused asking for it; a made frame with a fault refuses every run and the cut is kept as filmed; a weighting search on lines drawn by hand: the ease where nothing binds, held off it in the one step a window of the rest of the body is bounded in, none where a body measure may not move).- **Behavior change: `video-loop --anchor motion-auto` cuts a walk two steps long — the left foot forward once and the right once — wherever the clip shows its feet pass.** Left foot forward and right foot forward are nearly the same silhouette from the side or a diagonal, so the pixel search could take one step for a cycle (a half step loop: one foot goes forward), three steps where a tail on its own beat repeated there (the wrap puts the nearer foot back: a stomp in place), or refuse a slow walk whose cycle its window could not hold. The feet are now read (`crossings.read`): where they are seen apart, each run of frames with them together is a crossing; where they never are (front, back), the foot band's lean about the body's axis changing side is, and the lean must turn over a step on. Every crossing counted is one the clip shows whole: a run cut by the clip's first or last frame counts only where its twin confirms it, every step a cut plays — on both sides of its wrap — lies within √2 of the clip's own step, and a cut is two steps only when the walk's phase advances by two over it, its wrap joins two points of a step within [1/√2 − 1, √2 − 1] of each other under every bound of what the clip does not show, and the loop as played shows two crossings too (`two`; `refuted` one or three steps; anything else `uncertain`, never two). The search's cut is kept, every image as before, where it is a two within 1.5 frames of phase; otherwise the cut is the two-step cut in phase whose top band does not pop at the wrap, whose wrap is within the seam gate of its step and whose seam is the smoothest by the flow reading (both seam frames under `repair.FLOW_LIMIT`, within 0.5 of the smoothest, the wrap nearest the clip's own way on), read on the frames moved as the cut will be corrected, of any length the count allows inside an explicit `--min-len`/`--max-len` (`method: observed-two-steps-v1`); of the first four, the first whose seam the gate will pass, read as the gate reads it (`loop.seam_on_cells`), is taken. A window that holds no two steps of a walk whose steps are seen is refused, naming both (`no cut of two steps in --max-len 25: …`), never cut one step long. A clip whose feet are not read is cut exactly as before. The report records `cycle.step_count` (the crossings, the step range, the verdict of the cut taken and of the search's cut, `chosen_by`); a cut on two steps records `cycle.steps` `{count: 2, by: crossings}` and `strip.json` `steps: 2`, so `video-cycle-align` reads its half-way return as its step, and the step screen's pixel suspicion is settled (`pixel_suspect`). Where the clip shows its steps but no cut of two, the search runs again refusing the cuts the crossings refute, and a refusal lists each window's count, those refuted last. `--steps` is still the word on the search's cut. `repair.clip_flow_states` and `repair.ring_scores` read the flow of every cut of a clip on one path; `flow_scores` and the repair read as before ([loop-repair](docs/loop-repair.md) section 3, "The step count").- **Tests** — `tests/video/test_crossings.py` (a walk that stalls proves no two steps across the stall, on either side of the wrap; a hold before or after the cut, a stall with the feet apart, a stand with them together, a stomp in place, the stance a clip opens on, a pass the first frame cuts with or without a twin that confirms it, a change the clip ends on: none two; half a cycle and three steps refuted, a wrap half a step off and a wrap that slips feet together in uncertain; noise at the threshold and a wobble at the axis no steps; a hold the step range absorbs stays two and a longer one does not; two crossings set no range; a lean that does not turn over is not read; every two lies in the lengths two steps cover; the lean and gap off drawn frames), `tests/video/test_walk_steps.py` (on synthetic walkers the pixel search alone cuts one step, one step past its window, three steps by the gait fallback, nothing at all, and across a stalled step: each is cut two steps long, in phase, the strip saying `steps: 2`; a walk the search already cuts two steps in phase is cut byte for byte as before; a legless body is cut as the search cuts it; a count given is the word; the set aligns a loop cut on two steps as one cycle; `detect` refuses what the crossings refute and orders a refusal by the count), the step screen's tests in `tests/video/test_one_step_cut.py` and the pixel search's in `tests/video/test_auto_motion.py`, `tests/video/test_loop_prop_seam.py` and `tests/video/test_loop_prop_seam_held.py` (a walker whose legs open and close once a drawing and never pass each other, which the count reads as one step a drawing) read their walker's feet as unseen (`tests/conftest.py`, `feet_unseen`), and `tests/video/test_explicit_window.py` refuses a `--max-len 25` that holds one step of the 42-frame walker.-- **New: `video-loop --repair auto` (and `on`) eases a part that rushes on its way — the frames either side of the rush are made again at times that spread it, the body's own steps kept.** A part can keep its way and still jump: a tail that runs short of the cycle rushes on at the wrap, covering in one step what it covers in eight elsewhere, and each frame there lies near enough the line between its neighbours that the flow reading lets it pass, or takes the frame at the wrap out and leaves the rush over two steps. `repair.surges` reads the speed on the flow reading's own path and windows: a run of one or two steps whose mean step is at least 3.0 usual steps and 3.0 times the mean of the three steps either side, the part going on the way it came through it (a step that turns back is a frame flung, the flow repair's). After the flow groups, the worst rush is eased over three or four drawings either side, made from the frames as filmed (a frame the flow made inside is made again, `supersedes`) and kept between two frames as filmed, never leaving more than half the loop made with the rounds before it (as much as `video-loop-compare` reads back as the repair's): `repair.ease_times` gives every frame a time, on a grid of a twentieth of a step, where the part's step changes from one step to the next as little as it can — from the speed it came in with to the speed it goes on with — while the foot line's centre and the body's mass (`loop.foot_centre`, `loop.body_centre`) and the lowest solid row move in a step no further than the stretch's largest step as it played and half a pixel, and every other window of the flow reading no further than its own largest step there; within 2 % of that, the timing nearest the frames' own. How far the part has gone is the path of its coverage's centre in the windows that read the rush, which grows as far as the part moves where a blurred distance stops growing. RIFE makes each drawing between the frames as filmed either side of its time, one call a drawing, at most nine, outside the three of the flow groups; the stretch is taken only where no frame made has an interpolation fault, no body measure moves a pixel past the stretch's largest step, the part's largest step falls, no frame is left further off the flow and over its limit, no new rush appears in the rest of the body, and no window of the rest of the body steps further on the frames made than its own largest step over the stretch as it played (`rejected_for`, `the rest faster`: the search reads the rest of the body on the line between the frames as filmed, and the frames made, which go the body's own way between them, step further where a part moves far between frames). On the synthetic walker drawn over 24 frames a cycle, the tail a quarter short goes, after the flow repair, from 5.3 usual steps into the wrap to 3.4 with no rush left; over 16 frames, 15 % short and under the flow reading's limit, from 3.6 to 1.7; over 36 frames every stretch is refused, the rest of the body 1.5 % to 19 % past its own largest step on the frames made; ordinary walks and a flung frame read no rush. A loop with no rush costs one more reading and no call. `jump_repair` carries `surge`, `surge_after`, `ease_skipped`, `ease_calls` and the round `why: ease` (its `rest`: per window the rush is not read in, `step_max_before`, `step_max_after` and `faster`), `replaced` its frames, and the summary `eased`; without RIFE the rush is cut as filmed with a warning line, and `--repair on` refuses ([loop-repair](docs/loop-repair.md) section 2, "The eased retime").-- **Tests** — `tests/video/test_loop_ease.py` (a tail that rushes on at the wrap after the flow repair is eased over three or four drawings either side, in play order, made only from frames as filmed — the flow's frame at the wrap made again — every frame outside as it was, the part's largest step down by a quarter or more and the body's feet, mass and ground within the stretch's own steps and a pixel, and every window of the rest of the body within its own largest step, read again on the loop as it plays; a rush under the flow reading's limit eased, none left; over 36 frames, the stretch whose frames made step further in the arm, the head and the legs than they did there refused for that alone, the loop as the flow left it; ordinary walks, drawn every frame and on twos, have no rush and nothing is made; a frame flung against the way is not a rush; on twos each drawing made once and shown on both its frames; a made frame pushed sideways refuses the stretch for drift, and one with its outline melted for a fault, the loop left as the flow left it; without an interpolator the rush named and nothing made; the same frames whichever way the body faces; a fourteen-frame loop eased three a side where four would leave more than half of it made; the search keeps every frame at its own time where the part moves evenly, and spreads a rush as far as the body's bound lets it; `video-loop` playing the frames made in a loop as long, a rush without RIFE cut as filmed with a warning line, `--repair on` without RIFE refused), and `tests/video/test_loop_flow.py`'s walker draws its dark parts whole on asking (`dark_whole`), so that a frame drawn between two phases has no more dark pixels than they have.+- **New: `video-loop --repair auto` (and `on`) eases a part that rushes on its way — the frames either side of the rush are made again at times that spread it, the body's own steps kept.** A part can keep its way and still jump: a tail that runs short of the cycle rushes on at the wrap, covering in one step what it covers in eight elsewhere, and each frame there lies near enough the line between its neighbours that the flow reading lets it pass, or takes the frame at the wrap out and leaves the rush over two steps. `repair.surges` reads the speed on the flow reading's own path and windows: a run of one or two steps whose mean step is at least 3.0 usual steps and 3.0 times the mean of the three steps either side, the part going on the way it came through it (a step that turns back is a frame flung, the flow repair's). After the flow groups, the worst rush is eased over three or four drawings either side, made from the frames as filmed (a frame the flow made inside is made again, `supersedes`) and kept between two frames as filmed, never leaving more than half the loop made with the rounds before it (as much as `video-loop-compare` reads back as the repair's): `repair.ease_times` gives every frame a time, on a grid of a twentieth of a step, where the part's step changes from one step to the next as little as it can — from the speed it came in with to the speed it goes on with — while the foot line's centre (`loop.foot_centre`), the torso and the lowest solid row move in a step no further than the stretch's largest step as it played and half a pixel, and every other window of the flow reading no further than its own largest step there; the torso is the head and torso the motion anchor tracks (`repair.Torso`: `auto_motion.discover` on the loop as cut, each frame matched by the anchor's masked NCC within its own fine search, 14 px across and 28 down, x to a fraction of a pixel), so a part swaying on its own beat — a tail, the hair's ends — which pulls the body's mass along and is what the repair moves, is not drift; where the anchor finds no head and torso, or one reaches the edge of that search on a frame of the loop, the body's mass (`loop.body_centre`) stands in, and the mass is reported beside the drift either way (`drift.body_mass`, `torso`); within 2 % of that, the timing nearest the frames' own. How far the part has gone is the path of its coverage's centre in the windows that read the rush, which grows as far as the part moves where a blurred distance stops growing. RIFE makes each drawing between the frames as filmed either side of its time, one call a drawing, at most nine, outside the three of the flow groups; the stretch is taken only where no frame made has an interpolation fault, no body measure moves a pixel past the stretch's largest step, the part's largest step falls, no frame is left further off the flow and over its limit, no new rush appears in the rest of the body, and no window of the rest of the body steps further on the frames made than its own largest step over the stretch as it played (`rejected_for`, `the rest faster`: the search reads the rest of the body on the line between the frames as filmed, and the frames made, which go the body's own way between them, step further where a part moves far between frames). On the synthetic walker drawn over 24 frames a cycle, the tail a quarter short goes, after the flow repair, from 5.3 usual steps into the wrap to 3.4 with no rush left; over 16 frames, 15 % short and under the flow reading's limit, from 3.6 to 1.7; over 36 frames every stretch is refused, the rest of the body 1.5 % to 19 % past its own largest step on the frames made; ordinary walks and a flung frame read no rush. A loop with no rush costs one more reading and no call. `jump_repair` carries `surge`, `surge_after`, `ease_skipped`, `ease_calls` and the round `why: ease` (its `rest`: per window the rush is not read in, `step_max_before`, `step_max_after` and `faster`), `replaced` its frames, and the summary `eased`; without RIFE the rush is cut as filmed with a warning line, and `--repair on` refuses ([loop-repair](docs/loop-repair.md) section 2, "The eased retime").+- **Tests** — `tests/video/test_loop_ease.py` (a tail that rushes on at the wrap after the flow repair is eased over three or four drawings either side, in play order, made only from frames as filmed — the flow's frame at the wrap made again — every frame outside as it was, the part's largest step down by a quarter or more and the body's feet, torso and ground within the stretch's own steps and a pixel (the torso read as the round read it, the body's mass beside it), and every window of the rest of the body within its own largest step, read again on the loop as it plays; a rush under the flow reading's limit eased, none left; over 36 frames, the stretch whose frames made step further in the arm, the head and the legs than they did there refused for that alone, the loop as the flow left it; ordinary walks, drawn every frame and on twos, have no rush and nothing is made; a frame flung against the way is not a rush; on twos each drawing made once and shown on both its frames; a made frame pushed sideways refuses the stretch for drift, and one with its outline melted for a fault, the loop left as the flow left it; without an interpolator the rush named and nothing made; the same frames whichever way the body faces; a fourteen-frame loop eased three a side where four would leave more than half of it made; the search keeps every frame at its own time where the part moves evenly, and spreads a rush as far as the body's bound lets it; `video-loop` playing the frames made in a loop as long, a rush without RIFE cut as filmed with a warning line, `--repair on` without RIFE refused), and `tests/video/test_loop_flow.py`'s walker draws its dark parts whole on asking (`dark_whole`), so that a frame drawn between two phases has no more dark pixels than they have.- **Behavior change: a frame the jump repair or the cycle alignment makes between outlined drawings loses its outline only where it is lighter than its neighbours' edge rank by rank, too.** The fault `outline` read the made frame's edge against one dark line (a solid pixel under 70/255 within 2 px, `outline_loss` over 5 %), so art outlined in a mid tone — a brown or a painted line whose tone lies about 70/255 — had its line on the near side of the line in the drawings and on the far side wherever the flow softened it by a few tones: every frame made between two such drawings read as melted, and the repair and `--between auto` refused it. `rife.outline_shift(made, a, b)` reads the same edge, each pixel by how dark the darkest solid pixel within 2 px of it is, in order, against the lighter neighbour's edge at the same rank, and counts it where it is lighter by more than 50/255 (`rife.OUTLINE_SHIFT`). The fault `outline` now needs both over 5 %: a softened line is lighter by less at every rank and is kept, whatever tone the art outlines in; a line gone to the fill beside it is lighter by its whole contrast and is lost. Art outlined near-black reads the same on both, and art outlined lighter than 70/255 is still not judged by the outline. On the two-tone walker of the tests, the drawing between with its line 20 to 45 tones lighter reads `outline_loss` 57 % and `outline_shift` 0 (refused before, kept now); with its legs' line turned to fill, 24 % and 48 % (refused). A line less than 50/255 darker than the fill it melts into is not read as lost. The rank reading is read only between outlined drawings: `rife.outlined(frame)` is the share of a frame's edge whose line, the darkest solid pixel within 2 px, is darker than its fill, its colour from twice the bleed's depth inside (`rife.LINE_DEPTH`), by more than 50/255, and both neighbours must read at least 75 % (`rife.OUTLINED`); elsewhere `outline_shift` is `null` and the dark line judges alone, as before. Art painted without a line has no line to lose, and a part the flow melts there — a boot washed pale — can come out lighter by less than 50/255 at every rank: read rank by rank it would be kept and delivered, where refused it is replaced by the nearer filmed frame. On the walker of the tests painted without a line (outlined on 4 % of its edge), the drawing between with its near boot washed 40 tones lighter reads `outline_loss` 7.8 % and, rank by rank, 0: refused. The 75 % is set on frames made between drawn walks and judged by eye so that no frame seen as broken that the dark line alone refused is kept. The jump repair's proposals and the alignment's `smear` rows carry `outline_shift`, and the alignment's warning line names it where it was read; `video-loop-compare` and `video-loop-repair` keep their versioned measures, `rife.smear` alone, and judge the outline on the dark line as before ([loop-repair](docs/loop-repair.md) section 4).- **Tests** — `tests/video/test_outline_shift.py` (a mid-tone line drawn lighter is kept and one gone to fill is lost; the versioned measures judge on the dark line alone, and so does a measure whose rank reading was not read; art outlined near-black reads the same on both; a frame with no edge reads 0 and neighbours with none are not read; the jump repair takes a lighter line and refuses one gone to fill; the alignment keeps the one and takes the nearer frame for the other; on the walker painted without a line, a boot washed 40 tones lighter is refused by the jump repair and replaced by the alignment, and the two-tone and black walkers read outlined on all their edge; through RIFE, a short step of two-tone legs keeps its outline and legs crossing far lose it on both).- **Behavior change: every RIFE call runs the binary's test-time augmentation, `-x -z` (`rife.TTA`).** `-x` runs the pair as its eight flips and transposes and `-z` both ways in time, and the results are averaged, so a frame made from a to b is the one made from b to a. Neither rife-ncnn-vulkan nor Practical-RIFE has released a model since 2024; the model stays `rife-v4.6`. On the synthetic pairs of `tests/video/test_rife.py`, `-x -z` is the one setting of the four (none, `-x`, `-z`, both) that makes legs crossing far the same both ways with no ghost, and it keeps the most of a short step's outline. On the Mac's GPU it adds a tenth to half a second a frame; on Modal's CPU it costs 15 to 19 times a plain call's CPU — 12 to 30 s a 280 × 520 frame on two cores, 44 to 61 s a 960 × 960 frame. `SPRITE_GEN_RIFE_TTA` names another (`-x`, `-z`, both, or empty for none; anything else is refused before a frame is asked for), for a CPU-only machine that aligns sets. The interpolator a report names (`jump_repair.interpolator`, the alignment's `interpolator`) carries `tta`. A call past 600 s (120 s before) is stopped and reported as a RIFE that failed, where it used to end in Python's own timeout ([loop-repair](docs/loop-repair.md) section 1, "Which setting").diff --git a/docs/loop-repair.md b/docs/loop-repair.mdindex 4bb83f4..25030a7 100644--- a/docs/loop-repair.md+++ b/docs/loop-repair.md@@ -484,10 +484,10 @@ rush split by it would come out faster in the middle than the search reckoned. Estretch is given a time, on a grid of a twentieth of a step (`EASE_GRID`); of the timings that goforward and keep, in every step,-- each body measure — the foot line's centre and the body's mass, x (`loop.foot_centre`,- `loop.body_centre`: the reference `--anchor feet` reads drift on), and the lowest solid row, y,- the ground it stands on (`repair.drift_points`) — within the stretch's largest step as it played,- and half a pixel (`DRIFT_PIXEL` − `EASE_MARGIN`), drawn between the frames as filmed, and+- each body measure — the foot line's centre (`loop.foot_centre`) and the torso (below), x, and the+ lowest solid row, y, the ground it stands on (`repair.drift_points`) — within the stretch's largest+ step as it played, and half a pixel (`DRIFT_PIXEL` − `EASE_MARGIN`), drawn between the frames as+ filmed, and- every other window of the flow reading — the rest of the body — within its own largest step inthe stretch, read on the line between the states of the frames as filmed: no leg or arm hurriedpast what it did there (read again on the frames made, below),@@ -498,6 +498,21 @@ slows down as gradually as the body lets it, from the speed it came in with to twith — an ease in and out whose ends are its own. Of the timings within 2 % of that, the one nearestthe frames' own times, so a frame the part does not need moved keeps its time.+**The torso.** Drift is the body sliding or lifting off its line. A part that sways on its own beat+— a tail, the hair's ends — pulls the body's mass along, and moving such a part is what the repair+is for: that is not drift. The body's point is the torso, the head and torso the motion anchor+tracks (`repair.Torso`): `auto_motion.discover` on the loop as cut finds the two regions the anchor+would track — a part swaying on its own beat does not hold still enough to be chosen — and each frame+is matched by the anchor's masked NCC within the anchor's own fine search (`motion_anchor.SEARCH_RADIUS`:+14 px across, 28 down — a walk's bob lifts the head further than it sways) of where the loop's first+frame has them, the two weighted as the anchor weights them (0.7 and 0.3), x to a fraction of a pixel+on the parabola through the costs either side of the best. Where the anchor finds no such regions,+or one of them reaches the edge of that search on a frame of the loop, the body's mass+(`loop.body_centre`) stands in. The round records which (`torso`: `regions`, or+`stand_in` and `why`), and reports the body's mass beside the drift either way, as information+(`drift.body_mass`: its largest step over the stretch as it played, `bound`, and on the frames made,+`moved`). The overlapped wrap below reads the same torso.+**Made, then read again.** Each drawing not at its own time is made by RIFE between the two framesas filmed either side of its time, at that fraction of the way between them (in frames), and shownon every frame the drawing was; a time on a frame as filmed is that frame. One call a drawing made,@@ -507,7 +522,7 @@ on the frames made:| Read on the frames made | Refused for (`rejected_for`) ||---|---|| no made frame carries an interpolation fault (section 4) | `fault` |-| no body measure moves in a step more than a pixel past the stretch's largest step as it played — the measures are read on whole pixels, the ground on a row (`drift`: `bound`, `moved`, `over`) | `drift` |+| no body measure — the foot line, the torso, the ground — moves in a step more than a pixel past the stretch's largest step as it played — the measures are read on whole pixels, the ground on a row (`drift`: `bound`, `moved`, `over`; the body's mass beside it, `body_mass`) | `drift` || the part's largest step over the stretch falls (`part`) | `no gain` || no frame of the stretch is read further off the flow than before and at or over its limit (`off_max`) | `off the flow` || no rush is read in the stretch in a window the part does not rush in: the rest of the body was hurried | `a new rush` |@@ -582,27 +597,28 @@ frames.|---|---|---|| When | `--repair auto` or `on`; a cut whose two steps the clip's crossings show (`cycle.steps.by: crossings`) and whose wrap the gate reads over `--seam-max` on its frames as corrected (`loop.wrap_on_cells`) | the legs close; what does not is a part on its own beat. A cut whose steps are not counted keeps the gate's word || The frames a cycle apart | the clip's frame a cycle after each of the cut's first frames (`after`), or before each of its last (`before`), one past the widest run, as far as the clip after its lead-in holds them; each moved by the analysis translation between the two — the drift the clip walks over a cycle — and corrected as its cut frame was (`loop.cycle_apart`) | placed where the cut frame is, the in-between moves the part, not the body |-| How many | four frames, then six (`OVERLAP_WIDTHS`), never past half the loop (`MADE_SHARE`), on the side whose frames a cycle apart differ least from the cut's over the run | the fewer made, the more of the loop is the clip's own; six where four rush the part |-| Each frame | made by RIFE between its two frames of one time — the late (the clip's frame a cycle after, or the loop's own before the wrap) and the early (the loop's own, or the clip's frame a cycle before) — at the weight of the early the search chooses (`repair.overlap_weights`, below); a weight of 0 or 1 shows that frame whole, no call | each frame at its own time, the legs where they were on both; next to the wrap near the frame that continues the clip across it |-| The weights | in play order, from 0 at the frame before the run to 1 at the frame after it, never going back, on a grid of a twentieth: of those that keep every window of the rest of the body within its own largest step over either run (below) and every body measure within the largest step either run takes and half a pixel, read on the line between the two frames' states, the one nearest the ease in and out x²(3 − 2x), x = p/(width + 1) at the run's p-th frame (`repair.overlap_weight`) | the part goes over in an ease in and out, held off it only in the steps where the rest of the body has no room: a window that closes all but a step still moves by what it differs a cycle apart, and a weight that moves there pushes it past its own step |--The stretch runs from the frame before the run to the frame after it, the wrap inside, and its frames-are made between two runs the clip filmed: the stretch as the loop plays it, and the frames a cycle-apart as the clip filmed them, from the loop's own frame on the far side of the wrap (`after`: the-cut's last frame, then the clip's frames a cycle after the run and one more). A made frame next to the-wrap stands near the clip's frame a cycle on, and the wrap then plays the clip's own step into it: the-body moves there as the clip moved it, which the stretch as the loop played it need not show. The run-is taken only where, on the frames made:+| How many | four frames, then six, eight, ten and twelve (`OVERLAP_WIDTHS`), never past half the loop (`MADE_SHARE`), on the side whose frames a cycle apart differ least from the cut's over the run | the fewer made, the more of the loop is the clip's own; a longer run where a shorter one rushes the part or leaves the body no room, its weights going over in smaller steps |+| Each frame | made by RIFE between its two frames of one time — the late (the clip's frame a cycle after, or the loop's own before the wrap) and the early (the loop's own, or the clip's frame a cycle before) — at the weight of the early the search chooses (`repair.overlap_weights`, below); a weight of 0 or 1 shows that frame whole, no call, and a frame at one weight is made once, whatever the run | each frame at its own time, the legs where they were on both; next to the wrap near the frame that continues the clip across it |+| The weights | in play order, from 0 at the frame before the run to 1 at the frame after it, never going back, on a grid of a twentieth: of those that keep every window of the rest of the body within its own largest step over the stretch as the loop plays it and every body measure within the stretch's largest step and half a pixel (below), read on the line between the two frames' states, the one nearest the ease in and out x²(3 − 2x), x = p/(width + 1) at the run's p-th frame (`repair.overlap_weight`) | the part goes over in an ease in and out, held off it only in the steps where the body has no room: a window that closes all but a step still moves by what it differs a cycle apart, and a weight that moves there pushes it past its own step |++The stretch runs from the frame before the run to the frame after it, the wrap inside, and the body is+held to it as the loop plays it — the eased retime's bound, on the same torso ([the+torso](#the-eased-retime--a-part-that-rushes-on-its-way) above), never on the clip's frames a cycle+apart. A made frame next to the wrap stands near the clip's frame a cycle on: the part going over+pulls the body's mass, which is the move the run is made for, reported and not held+(`drift.body_mass`); a torso the clip's frame a cycle on shows elsewhere — the clip walked on over the+cycle — would slide, and the bound holds such a frame toward the cut's own, the wrap then closing only+as far as that lets it. The run is taken only where, on the frames made:| Read on the frames made | Refused for (`rejected_for`) ||---|---|| no made frame carries an interpolation fault (section 4) | `fault` || the seam gate's reading passes | `seam` || the loop, played round three times, still covers two steps: the crossings read on it, its middle turn judged `two` (`loop.ring_steps`) | `steps` |-| no body measure (`repair.drift_points`) moves in a step more than a pixel past the largest step either run takes there | `drift` |+| no body measure (`repair.drift_points`: the foot line, the torso, the ground) moves in a step more than a pixel past the largest step of the stretch as the loop plays it | `drift` || the part — the windows of the flow reading where the frames a cycle apart differ by a usual step or more somewhere in the run (`OVERLAP_APART`) — steps no further than it did over the stretch as the loop played it | `no gain` || no rush the loop did not have is read across the stretch (`repair.surges`) | `a new rush` |-| no window of the rest of the body steps further than its own largest step over either run | `the rest faster` |+| no window of the rest of the body steps further than its own largest step over the stretch as the loop plays it | `the rest faster` || no frame of the stretch is read further off the flow than before and at or over its limit | `off the flow` |The first run taken ends the search; where none is, the cut is kept as filmed and the gate refuses it@@ -620,6 +636,15 @@ tail swinging round on a beat of 41 frames, 73 frames, with the stand-in in-betw| the jump repair alone: the flow repair takes the frame at the wrap, and the tail turns back there (turn −0.91), so the retime eases nothing | 3.17 | 0.44 | two steps || overlapped: four frames after the wrap refused (`a new rush`), six taken at the ease (weights 0.05, 0.2, 0.4, 0.6, 0.8, 0.95) | 1.04 | 0.30 | two steps |+The file's second walker tells the part from the torso: a tuft of 30 px on a short tail bobs up and+down on the loop, the walker in its place, and drops at the wrap (3.41 at the gate); a cycle on, the+clip carries the tuft on its bob and 8 px aside a frame.++| The second walker | The run | Seam gate (2.0) | Torso, largest step (stretch → made) | Body's mass (stretch → made) |+|---|---|---|---|---|+| the tuft alone carried over | four frames at the ease (0.1, 0.35, 0.65, 0.9) taken, 4 calls | 3.41 → 1.53 | 0.03 → 0.05 | 0.71 → 3.95, reported |+| the whole walker also 3 px aside a cycle on (its torso slides) | every run of four to twelve held at 0.85 of the cut's own frame next to the wrap, all refused (`seam`), 15 calls | 3.41 → 3.04 to 3.15 | 0.03 → 0.05 at most | 0.71 → 1.96 to 3.91 |+The report's `wrap_overlap` carries `seam` (the reading that asked for it), `seam_max`, `widths`,`calls`, and each try in `tries` — `side`, `width`, `frames`, `stretch`, `eased` and `off_ease` (theease and how far the weights left it), `made` (per frame: `frame`, its weight `t`, `proposal`, `faults`,@@ -632,8 +657,10 @@ for a run that leaves half of it filmed, the clip holds no frames a cycle from tno interpolator). The summary names it. A made framethat cross-fades two drawings inside its outline is kept and named in a `warning:` line, as for thejump repair. Without RIFE the wrap is cut as filmed with a warning line (`why`: "RIFE not installed —-the wrap cut as filmed"), and `--repair on` refuses. It costs at most ten RIFE calls, outside the jump-repair's.+the wrap cut as filmed"), and `--repair on` refuses. Each run tried makes its frames with RIFE, a frame+at one weight once: at most forty calls where every width is made and refused, outside the jump+repair's — the first walker above takes ten, the second four where it is taken and fifteen where its+torso slides.## 3. The jolt index — reported on every walk, a gate only when askeddiff --git a/docs/video-pipeline.md b/docs/video-pipeline.mdindex 7419194..d1a351f 100644--- a/docs/video-pipeline.md+++ b/docs/video-pipeline.md@@ -935,12 +935,14 @@ frames beside it, else by the clean frame beside it, else kept and named (`ghost`ghost_kept`) — a walk of one direction is delivered as cut and never meets the alignment that wouldtake a clean frame there. Then a part that keeps its way and rushes — a tail that runs short ofthe cycle, rushing on at the wrap — has the three or four drawings either side of the rush made-again at times that spread it, made from the frames as filmed, the body's feet, mass and ground-line moving no further in a step, nor the rest of it faster, than they did there (the eased-retime, up to nine calls of its own). Before all of it, a cut two steps long whose wrap a part-on its own beat leaves open — a tail swinging round on a beat of its own, closing on no cut of two-steps — has the four or six frames beside its wrap made again between the clip's frames a cycle-apart and its own, so the wrap plays a step the clip filmed (the overlapped wrap, `wrap_overlap`).+again at times that spread it, made from the frames as filmed, the body's feet, torso (the head+and torso the motion anchor tracks; a part swaying on its own beat is not drift) and ground line+moving no further in a step, nor the rest of it faster, than they did there (the eased retime, up+to nine calls of its own). Before all of it, a cut two steps long whose wrap a part on its own beat+leaves open — a tail swinging round on a beat of its own, closing on no cut of two steps — has four+to twelve frames beside its wrap made again between the clip's frames a cycle apart and its own, so+the wrap plays a step the clip filmed, as far as the torso held to the stretch as the loop plays it+allows (the overlapped wrap, `wrap_overlap`).The report's `jump_repair` names the frames. RIFEis installed once with `sprite-gen rife install`; without it a loop that needs a frame is cut asfilmed with a warning, each filmed ghost given way to the clean frame beside it (`--repair on`diff --git a/sprite_gen/video/auto_motion.py b/sprite_gen/video/auto_motion.pyindex 453eacb..977ea3f 100644--- a/sprite_gen/video/auto_motion.py+++ b/sprite_gen/video/auto_motion.py@@ -75,7 +75,36 @@ def _correlate(region, kernel, rows, cols):def _match(reference, moving, center, radius):- """Bounded masked NCC at every translation, never wrap pixels.+ """Bounded masked NCC at every translation, never wrap pixels (`_match_costs`), the best taken+ (`_best`): the shift (dx, dy) that lays `moving` over the reference, and its cost."""+ (x, y, right, bottom), mask, feature, norm = reference+ cx, cy = center+ costs, xs, ys = _match_costs(reference, moving, center, radius)+ iy, ix = _best(costs, xs, ys, reference, center)+ dx, dy = x-(xs+ix), y-(ys+iy)+ if abs(dx-cx) == radius or abs(dy-cy) == radius:+ raise ValueError("automatic motion anchor match reached search boundary")+ return np.array([dx, dy]), float(costs[iy, ix])+++def _best(costs, xs, ys, reference, center):+ """The offset of the least cost in `costs` (`_match_costs`), as (row, column).++ A patch on a flat fill matches equally at several offsets, and FFT rounding — not the same on+ every machine — would pick among them. Costs within MATCH_TIE are one match; the evidence does+ not decide between them, so the prior does: the offset nearest the centre the search was put on.+ """+ (x, y, right, bottom) = reference[0]+ cx, cy = center+ tied = np.argwhere(costs <= costs.min()+MATCH_TIE)+ return min(((int(iy), int(ix)) for iy, ix in tied),+ key=lambda at: ((x-(xs+at[1])-cx)**2+(y-(ys+at[0])-cy)**2, at))+++def _match_costs(reference, moving, center, radius):+ """The masked NCC cost of every translation within `radius` (px, or px across and down) of+ `center`, never wrap pixels: costs[iy, ix] with the reference's box laid at (xs + ix, ys + iy)+ in `moving`; returns (costs, xs, ys).Per channel, the masked patch sum, squared sum and product with the centered referenceare window correlations, so all offsets come out of a few FFTs instead of one gathered@@ -83,9 +112,10 @@ def _match(reference, moving, center, radius):"""(x, y, right, bottom), mask, feature, norm = referencecx, cy = center+ rx, ry = (radius, radius) if isinstance(radius, int) else radiusheight, width = mask.shape- xs, xe = max(0, x-cx-radius), min(moving.shape[1]-width, x-cx+radius)- ys, ye = max(0, y-cy-radius), min(moving.shape[0]-height, y-cy+radius)+ xs, xe = max(0, x-cx-rx), min(moving.shape[1]-width, x-cx+rx)+ ys, ye = max(0, y-cy-ry), min(moving.shape[0]-height, y-cy+ry)if xs > xe or ys > ye:raise ValueError("automatic motion anchor has no search overlap")region = moving[ys:ye+height, xs:xe+width].astype(np.float64)@@ -104,17 +134,7 @@ def _match(reference, moving, center, radius):product += _correlate(values, kernel[:, :, channel], rows, cols) - total * kernel[:, :, channel].sum() / countenergy += _correlate(values * values, weights, rows, cols) - total * total / countdenominator = np.sqrt(np.maximum(energy, 0.0)) * norm- costs = 1 - product / np.maximum(1e-10, denominator)- # A patch on a flat fill matches equally at several offsets, and FFT rounding — not the same on- # every machine — would pick among them. Costs within MATCH_TIE are one match; the evidence does- # not decide between them, so the prior does: the offset nearest the centre the search was put on.- tied = np.argwhere(costs <= costs.min()+MATCH_TIE)- iy, ix = min(((int(iy), int(ix)) for iy, ix in tied),- key=lambda at: ((x-(xs+at[1])-cx)**2+(y-(ys+at[0])-cy)**2, at))- dx, dy = x-(xs+ix), y-(ys+iy)- if abs(dx-cx) == radius or abs(dy-cy) == radius:- raise ValueError("automatic motion anchor match reached search boundary")- return np.array([dx, dy]), float(costs[iy, ix])+ return 1 - product / np.maximum(1e-10, denominator), xs, ysdef discover(frames: list[Image.Image], *, reference_index: int) -> tuple[list, dict]:diff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.pyindex fc59076..0a8e34a 100644--- a/sprite_gen/video/loop.py+++ b/sprite_gen/video/loop.py@@ -902,7 +902,8 @@ def _repair_jumps(frames: list[Image.Image], interpolate: rife_mod.Interpolate |`wrap` (the clip's frames a cycle from the cut's beside its wrap, `cycle_apart`, and the gate's `seam_max`) asksfirst for the overlapped wrap (`repair_mod.overlap_wrap`) of a cut two steps long whose wrap the gate refuses;the frames it makes are then neither made from, nor beside, nor again (`overlapped`). Its record is returned- third, None where it was not asked.+ third, None where it was not asked. The overlapped wrap and the eased retime after it read the body's drift on+ one torso, the cut's as filmed (`repair_mod.Torso`).A frame to make and no RIFE installed: `required` lets `RifeNotInstalled` through; otherwiseeach filmed ghost gives way to the clean frame beside it, a jump (a frame off the flow), a rush and a wrap that does@@ -922,9 +923,11 @@ def _repair_jumps(frames: list[Image.Image], interpolate: rife_mod.Interpolate |overlap: dict[str, Any] | None = Noneoverlapped: list[int] = []+ torso = Noneif wrap is not None:+ torso = repair_mod.Torso(frames)asked = partial(repair_mod.overlap_wrap, others=wrap["others"], seam=wrap_on_cells, steps=ring_steps,- seam_max=wrap["seam_max"], reads=bool(screen["reads"]))+ seam_max=wrap["seam_max"], reads=bool(screen["reads"]), torso=torso)try:frames, overlap = asked(frames, interpolate=lazy)except rife_mod.RifeNotInstalled as exc:@@ -937,13 +940,15 @@ def _repair_jumps(frames: list[Image.Image], interpolate: rife_mod.Interpolate |overlap["interpolator"] = {"kind": "rife-ncnn-vulkan", **made_by[0]} if made_by else {"kind": "injected"}wrap_calls = callstry:- repaired, record = repair_mod.repair_jumps(frames, lazy, facing=facing, screen=screen, overlapped=overlapped)+ repaired, record = repair_mod.repair_jumps(frames, lazy, facing=facing, screen=screen, overlapped=overlapped,+ torso=torso)except rife_mod.RifeNotInstalled as exc:if required:raise# RIFE is located before the first frame is made, so nothing was made yet: the stage runs again# with no interpolator, each ghost giving way to the clean frame beside it and a jump left as filmed.- repaired, record = repair_mod.repair_jumps(frames, None, facing=facing, screen=screen, overlapped=overlapped)+ repaired, record = repair_mod.repair_jumps(frames, None, facing=facing, screen=screen, overlapped=overlapped,+ torso=torso)record["applied"] = bool(record["replaced"])if "unmade" in record:record.update(why="RIFE not installed — cut as filmed" if not record["replaced"] elsediff --git a/sprite_gen/video/repair.py b/sprite_gen/video/repair.pyindex 49229fe..5befe66 100644--- a/sprite_gen/video/repair.py+++ b/sprite_gen/video/repair.py@@ -16,9 +16,11 @@ frame beside it (docs/loop-repair.md section 4).A part can also keep its way and still rush: a tail that runs short of the cycle covers at the wrap in one step whatit covers in eight elsewhere. The surge reading (`surges`) reads that speed; the frames either side of the rush, threeor four drawings each way, are made again by RIFE at times chosen so the part's speed rises and falls gradually-(`ease_times`), while the body's feet, mass and ground line move no further in a step, nor the rest of the body+(`ease_times`), while the body's feet, torso and ground line move no further in a step, nor the rest of the bodyfaster, than they did in that stretch — read again on the frames made, which go the body's own way between the-frames as filmed (docs/loop-repair.md section 2, "The eased retime").+frames as filmed (docs/loop-repair.md section 2, "The eased retime"). The torso is the head and torso the motion+anchor tracks (`Torso`): a part that sways on its own beat pulls the body's mass along, and moving it is what the+repair is for, not drift.A part on a beat of its own — a tail swinging round every 41 frames on a walk of 26 — closes on no cut of two steps,and turns back at the wrap, where no retime reaches it. Before the rounds above, the frames beside such a cut's wrap@@ -42,6 +44,7 @@ from typing import Anyfrom PIL import Imagefrom sprite_gen._deps import np+from sprite_gen.video import auto_motion, motion_anchorfrom sprite_gen.video import held as held_modfrom sprite_gen.video import legs as legs_modfrom sprite_gen.video.rife import Interpolate, crossfade, ghost, outline_shift, smear@@ -398,26 +401,99 @@ EASE_GRID = 20 # times the search tries per step between two drawingsEASE_SLACK = 0.02 # of the timings within this share of the least change of the part's step, the nearest its own# A made frame's body measures may move in a step up to the stretch's largest step as it played and DRIFT_PIXEL more:# they are read on whole pixels (the ground is a row). The search keeps EASE_MARGIN inside that, as a made frame's feet-# and mass land a little off the line between its two frames that the search reads them on.+# and torso land a little off the line between its two frames that the search reads them on.DRIFT_PIXEL = 1.0EASE_MARGIN = 0.5-DRIFT_MEASURES = ("foot_centre", "body_centre", "ground")+DRIFT_MEASURES = ("foot_centre", "torso_centre", "ground")# With the frames the ghost and flow rounds replaced, a stretch leaves at most this share of the loop made:# `video-loop-compare` reads no more back as the repair's (`source.py`, "repair-locations-unverified").MADE_SHARE = 0.5---def drift_points(frame: Image.Image) -> np.ndarray:- """Where the body stands in `frame`: the foot line's centre and the body's mass, x (`loop.foot_centre`,- `loop.body_centre`, the reference `--anchor feet` reads drift on), and the lowest solid row (`legs.LOW_ALPHA`), y,- the ground it stands on. NaN for an empty frame."""+# Drift is the body sliding or lifting off its line. A part that sways on its own beat — a tail, the hair's ends — pulls+# the body's mass along, and moving such a part is what the repairs here are for: that is not drift. The body's point is+# the torso, the head and torso the motion anchor tracks (`auto_motion.discover` on the loop as cut), which a part swaying+# on its own beat does not hold still enough to be chosen: each frame matched by the anchor's masked NCC within the+# anchor's own fine search (`motion_anchor.SEARCH_RADIUS`, px across and down — a walk's bob lifts the head further than+# it sways) of where the loop's first frame has them, the two weighted as the anchor weights them, x to a fraction of a+# pixel on the parabola through the costs either side of the best. A loop whose head and torso go to the edge of that+# search on any of its frames (cut as filmed, the drift left in) is not read on them: its mass stands in.+++class Torso:+ """The head and torso of a loop as the motion anchor tracks them (`auto_motion.discover` on `frames`, the first the+ reference, at full size): the body's point of the drift (`drift_points`). Where the anchor finds no head and torso+ to track (`why`), the body's mass (`loop.body_centre`) stands in."""++ def __init__(self, frames: list[Image.Image]):+ self.regions: list[list[int]] | None = None+ self.why: str | None = None+ self._references: list[tuple] | None = None+ try:+ regions, _ = auto_motion.discover(frames, reference_index=0)+ self._references = motion_anchor._references(motion_anchor._features(frames[0]), regions)+ except ValueError as exc:+ self.why = str(exc)+ return+ far = [k for k, f in enumerate(frames) if self._at(f)[1]]+ if far:+ self._references = None+ self.why = f"the head and torso reach the edge of the anchor's search on frames {far}"+ return+ self.regions = [list(r) for r in regions]++ def _at(self, frame: Image.Image) -> tuple[float, bool]:+ """Where `frame` shows the head and torso, x px from where the first frame has them, and whether a region was+ found only at the edge of the search (`motion_anchor.SEARCH_RADIUS`)."""+ features = motion_anchor._features(frame)+ rx, ry = motion_anchor.SEARCH_RADIUS+ at, edge = 0.0, False+ for weight, reference in zip(motion_anchor.REGION_WEIGHTS, self._references):+ costs, xs, ys = auto_motion._match_costs(reference, features, (0, 0), (rx, ry))+ iy, ix = auto_motion._best(costs, xs, ys, reference, (0, 0))+ off = 0.0+ if 0 < ix < costs.shape[1] - 1:+ left, best, right = costs[iy, ix - 1], costs[iy, ix], costs[iy, ix + 1]+ bend = left - 2 * best + right+ off = 0.5 * (left - right) / bend if bend > 1e-12 else 0.0+ dx, dy = xs + ix - reference[0][0], ys + iy - reference[0][1]+ edge |= abs(dx) >= rx or abs(dy) >= ry+ at += weight * (dx + off)+ return float(at), edge++ def x(self, frame: Image.Image, box: tuple[int, int, int, int]) -> float:+ """Where `frame` shows the head and torso, x px from where the loop's first frame has them; or the body's mass+ inside `box`, x."""+ from sprite_gen.video import loop as loop_mod # loop imports this module++ if self._references is None:+ return loop_mod.body_centre(frame, box)+ return self._at(frame)[0]++ def said(self) -> dict[str, Any]:+ return {"regions": self.regions} if self.why is None else {"stand_in": "the body's mass", "why": self.why}+++def drift_points(frame: Image.Image, torso: Torso | None = None) -> np.ndarray:+ """Where the body stands in `frame`: the foot line's centre (`loop.foot_centre`) and the torso (`torso`; the body's+ mass, `loop.body_centre`, where none is given), x, and the lowest solid row (`legs.LOW_ALPHA`), y, the ground it+ stands on. NaN for an empty frame."""from sprite_gen.video import loop as loop_mod # loop imports this modulebox = frame.getchannel("A").point(lambda v: 255 if v >= ALPHA_SOLID else 0).getbbox()rows = np.nonzero((np.asarray(frame.getchannel("A")) >= legs_mod.LOW_ALPHA).any(axis=1))[0]if box is None or rows.size == 0:return np.full(len(DRIFT_MEASURES), np.nan)- return np.array([loop_mod.foot_centre(frame, box), loop_mod.body_centre(frame, box), float(rows.max())])+ body = torso.x(frame, box) if torso is not None else loop_mod.body_centre(frame, box)+ return np.array([loop_mod.foot_centre(frame, box), body, float(rows.max())])+++def mass_step(frames: list[Image.Image]) -> float:+ """The largest step of the body's mass (`loop.body_centre`), x, over `frames` in order: reported beside the drift,+ as information — a part swaying on its own beat moves it."""+ from sprite_gen.video import loop as loop_mod # loop imports this module++ boxes = [f.getchannel("A").point(lambda v: 255 if v >= ALPHA_SOLID else 0).getbbox() for f in frames]+ x = np.array([loop_mod.body_centre(f, b) if b else np.nan for f, b in zip(frames, boxes)])+ return round(float(np.abs(np.diff(x)).max()), 3)def _surges(flow: dict[str, Any]) -> list[dict[str, Any]]:@@ -561,14 +637,14 @@ def _part_accel(progress: np.ndarray, at: list[float], times: np.ndarray, into:def _ease(frames: list[Image.Image], out: list[Image.Image], interpolate: Interpolate | None,box: tuple[int, int, int, int], blocked: set[int], made: set[int], taken: set[int], reads: bool,- record: dict[str, Any], ease: bool) -> list[Image.Image]:+ record: dict[str, Any], ease: bool, torso: Torso | None) -> list[Image.Image]:"""The eased retime stage of `repair_jumps`, on the loop `out` as the ghost and flow rounds left it.`blocked` holds the frames no stretch may hold (given way, refused; the frames read off the flow against the wayare added here), `made` the frames the flow rounds made: a stretch makes them again, never from them, and neverends on one. `taken` holds every frame the rounds replaced: with the stretch they are at most MADE_SHARE of the- loop. Records `surge` and, where a stretch- was made, an `ease` round (`ease_calls`); `ease_skipped` says why+ loop. The body's point of the drift is `torso`'s, the `Torso` of `frames` where none is given. Records `surge` and,+ where a stretch was made, an `ease` round (`ease_calls`); `ease_skipped` says whynone was. With `ease` false the surge is read and nothing made."""flow = _flow(out, box)found = _surges(flow)@@ -585,7 +661,9 @@ def _ease(frames: list[Image.Image], out: list[Image.Image], interpolate: Interp# a drawing off the flow that turns back is a frame flung, not the rush: nothing is eased over itread = _drawing_scores(flow)blocked = blocked | {t for d in range(n) if read["off"][d] >= FLOW_LIMIT and read["turn"][d] < 0 for t in runs[d]}- points = [drift_points(out[t]) for t in first]+ torso = torso if torso is not None else Torso(frames)+ record["torso"] = torso.said()+ points = [drift_points(out[t], torso) for t in first]cell = (box[2] - box[0]) / flow["path"].shape[2] # px a cell of the path's gridplans = []why = "the frames around it were given way, refused, or flung against the way"@@ -680,7 +758,7 @@ def _ease(frames: list[Image.Image], out: list[Image.Image], interpolate: Interpfor k in drawing:new[k] = frameafter_flow = _flow(new, box, (runs, flow["hold"]))- moved = np.abs(np.diff(np.array([drift_points(new[first[d]]) for d in stretch]), axis=0)).max(axis=0)+ moved = np.abs(np.diff(np.array([drift_points(new[first[d]], torso) for d in stretch]), axis=0)).max(axis=0)over = bool(np.any(~np.isfinite(moved)) or np.any(moved > plan["bound"] + DRIFT_PIXEL + 1e-9))W = plan["W"]part_before = float(max(rel[d, w] for d in stretch[:-1] for w in W))@@ -716,7 +794,9 @@ def _ease(frames: list[Image.Image], out: list[Image.Image], interpolate: Interp"step_max_after": [round(float(v), 4) for v in rest_after / flow["scale"][rest]],"faster": [[round(v, 4) for v in flow["fractions"][w]] for w in faster]},"drift": {"measures": list(DRIFT_MEASURES), "bound": [round(float(v), 3) for v in plan["bound"]],- "moved": [round(float(v), 3) for v in moved], "over": over},+ "moved": [round(float(v), 3) for v in moved], "over": over,+ "body_mass": {"bound": mass_step([out[first[d]] for d in stretch]),+ "moved": mass_step([new[first[d]] for d in stretch])}},"off_max": {"before": round(off_before, 4), "after": round(off_after, 4)}, "calls": calls, "faults": wrong,"look": sorted({w for r in made_rows for w in r["look"]}), "outcome": "rejected" if rejected else "accepted"}if rejected:@@ -736,8 +816,10 @@ def _ease(frames: list[Image.Image], out: list[Image.Image], interpolate: Interp# after one of the cut's shows the legs at the same point of the walk and the part where the clip carried it. The frames# beside the wrap are made again between the two, each at its own time, the weight going over from the clip's frame a# cycle on, next to the wrap, to the cut's own frame away from it: the wrap plays a step the clip filmed, and the part goes-# over from the clip's way to the cut's over those frames, the legs where they were on both.-OVERLAP_WIDTHS = (4, 6) # frames beside the wrap made again, the fewer first+# over from the clip's way to the cut's over those frames, the legs where they were on both. The body is held to the+# stretch as the loop plays it, as the eased retime holds it, on its torso (`Torso`): the part going over moves the body's+# mass and is the move the run is made for, while a torso the clip's frame a cycle on shows elsewhere would slide.+OVERLAP_WIDTHS = (4, 6, 8, 10, 12) # frames beside the wrap made again, the fewer first; a longer run, smaller steps of weightOVERLAP_SIDES = ("after", "before") # the clip's frames a cycle after the loop's first frames, or a cycle before its lastOVERLAP_APART = 1.0 # usual steps: a window whose frames a cycle apart differ by this much somewhere in the run is the partOVERLAP_GRID = 20 # weights the search tries between a frame's two, 0 and 1 included: OVERLAP_GRID + 1 points@@ -794,7 +876,7 @@ def overlap_weights(step: np.ndarray, body: np.ndarray, rest: list[int], rest_bodef overlap_wrap(frames: list[Image.Image], others: dict[str, dict[int, Image.Image]], interpolate: Interpolate | None, *,seam: Callable[[list[Image.Image]], float], steps: Callable[[list[Image.Image]], dict[str, Any]],- seam_max: float, reads: bool) -> tuple[list[Image.Image], dict[str, Any]]:+ seam_max: float, reads: bool, torso: Torso | None = None) -> tuple[list[Image.Image], dict[str, Any]]:"""The overlapped wrap (docs/loop-repair.md section 2, "The overlapped wrap") of a loop cut two steps long whose wrapthe seam gate refuses (`seam`: the gate's reading of a loop, over `seam_max`).@@ -803,20 +885,21 @@ def overlap_wrap(frames: list[Image.Image], others: dict[str, dict[int, Image.Imwidth (OVERLAP_WIDTHS, the fewer first), on the side whose frames a cycle apart differ least from the loop's over it,and never past MADE_SHARE of the loop. The stretch runs from the frame before the run to the frame after it, the wrapinside; each of its frames has two of one time, the late (the clip's frame a cycle after, or the loop's own before the- wrap) and the early (the loop's own, or the clip's frame a cycle before), and two runs the clip filmed pass through- them: the stretch as the loop plays it, and the frames a cycle apart as the clip filmed them, from the loop's own frame- on the far side of the wrap. Each frame of the run is shown at the weight of its early frame `overlap_weights` chooses- on the line between the two frames' states — an ease in and out, moved off it only as far as the rest of the body and- the body's measures need — as RIFE's frame between them (`interpolate`), or either one whole at 0 or 1.+ wrap) and the early (the loop's own, or the clip's frame a cycle before). Each frame of the run is shown at the weight+ of its early frame `overlap_weights` chooses on the line between the two frames' states — an ease in and out, moved off+ it only as far as the rest of the body and the body's measures need — as RIFE's frame between them (`interpolate`), or+ either one whole at 0 or 1.The run is taken only where, on the frames made: no frame has an interpolation fault; the gate passes it; the loopplayed round still covers two steps (`steps`, the clip's crossings read on it); no body measure moves in a step more- than a pixel past the largest step either run takes there (`drift_points`); the part — the windows where the frames a- cycle apart differ by OVERLAP_APART usual steps or more — steps no further than it did over the stretch (`no gain`);- no window of the rest of the body steps further than its own largest step over either run (`the rest faster`); no- rush the loop did not have is read across the stretch (`a new rush`); and no frame of it is read further off the flow- than before and at or over the limit. The first run taken ends the search. Returns the loop and the record (`frames`:- the frames shown otherwise than as cut)."""+ than a pixel past the largest step the stretch takes as the loop plays it (`drift_points`, the eased retime's bound,+ the body's point the torso: `torso`, the `Torso` of `frames` where none is given, recorded as `torso`; the body's+ mass is reported beside it, `drift.body_mass`);+ the part — the windows where the frames a cycle apart differ by OVERLAP_APART usual steps or more — steps no further+ than it did over the stretch (`no gain`); no window of the rest of the body steps further than its own largest step+ over the stretch as the loop plays it (`the rest faster`); no rush the loop did not have is read across the stretch+ (`a new rush`); and no frame of it is read further off the flow than before and at or over the limit. The first run+ taken ends the search. Returns the loop and the record (`frames`: the frames shown otherwise than as cut)."""n = len(frames)record: dict[str, Any] = {"seam": round(float(seam(frames)), 4), "seam_max": seam_max, "widths": list(OVERLAP_WIDTHS),"tries": [], "frames": [], "calls": 0}@@ -829,7 +912,6 @@ def overlap_wrap(frames: list[Image.Image], others: dict[str, dict[int, Image.Imkeys = list(images)at = {key: k for k, key in enumerate(keys)}states = flow_states([images[key] for key in keys], box)- points = {key: drift_points(images[key]) for key in keys}windows, scale = flow["windows"], flow["scale"]def between(a: np.ndarray, b: np.ndarray) -> np.ndarray:@@ -854,9 +936,13 @@ def overlap_wrap(frames: list[Image.Image], others: dict[str, dict[int, Image.Imif interpolate is None:record["skipped"] = "no interpolator"return frames, record+ torso = torso if torso is not None else Torso(frames)+ record["torso"] = torso.said()+ points = {key: drift_points(images[key], torso) for key in keys}rel = flow["step"] / scaleoff_before = (flow["off"] / scale).max(axis=1)grid = np.linspace(0.0, 1.0, OVERLAP_GRID + 1)+ made_at: dict[tuple[Any, ...], tuple[Image.Image, dict[str, Any]]] = {} # a frame at one weight, made once whatever the rundef touching(fl: dict[str, Any], steps_at: set[int]) -> list[dict[str, Any]]:return [x for x in _surges(fl) if {(x["d"] + i) % n for i in range(x["r"])} & steps_at]@@ -869,21 +955,13 @@ def overlap_wrap(frames: list[Image.Image], others: dict[str, dict[int, Image.Iminner = set(stretch[1:-1])late = [(side, q) if side == "after" and q in inner else ("loop", q) for q in stretch]early = [("before", q) if side == "before" and q in inner else ("loop", q) for q in stretch]- # the same stretch as the clip filmed it a cycle apart: the loop's own frame on the far side of the wrap- apart_at = set(overlap_run(side, width + 1, n))- filmed = [(side, q) if q in apart_at else ("loop", q) for q in stretch]- played = [("loop", q) for q in stretch]diff = np.stack([apart(side, q) for q in run]).max(axis=0)part = [w for w in range(len(windows)) if diff[w] >= OVERLAP_APART]rest = [w for w in range(len(windows)) if w not in part]steps_at = stretch[:-1]-- def run_steps(run_keys: list[tuple[str, int]]) -> np.ndarray:- return np.array([between(states[at[a]], states[at[b]]) for a, b in zip(run_keys, run_keys[1:])])-- filmed_step = run_steps(filmed)- step_bound = np.maximum(flow["step"][steps_at], filmed_step).max(axis=0) / scale- bound = np.max([np.abs(np.diff(np.array([points[key] for key in keys_]), axis=0)).max(axis=0) for keys_ in (played, filmed)], axis=0)+ # the bounds of the eased retime: the stretch as the loop plays it, the clip's frames a cycle apart no part of them+ step_bound = flow["step"][steps_at].max(axis=0) / scale+ bound = np.abs(np.diff(np.array([points["loop", q] for q in stretch]), axis=0)).max(axis=0)# the line between each position's two frames, a step at a time, on the weight grid (`overlap_weights`)L_ = [states[at[key]] for key in late]E_ = [states[at[key]] for key in early]@@ -920,20 +998,24 @@ def overlap_wrap(frames: list[Image.Image], others: dict[str, dict[int, Image.Imelif u >= 1.0:frame = belse:- frame = interpolate(a, b, u)- record["calls"] += 1- if frame.mode != "RGBA" or frame.size != b.size:- raise ValueError("repair interpolator must return an RGBA frame of the original size")- measure = {**smear(frame, a, b), "outline_shift": outline_shift(frame, a, b),- "ghost": ghost(frame) if reads else None, "crossfade": crossfade(frame, a, b, u)}- row.update(proposal=measure, faults=faults(measure) + ([] if frame.getchannel("A").getbbox() else ["empty"]),- look=looks(measure))+ key = (late[p], early[p], row["t"])+ if key not in made_at:+ made = interpolate(a, b, u)+ record["calls"] += 1+ if made.mode != "RGBA" or made.size != b.size:+ raise ValueError("repair interpolator must return an RGBA frame of the original size")+ measure = {**smear(made, a, b), "outline_shift": outline_shift(made, a, b),+ "ghost": ghost(made) if reads else None, "crossfade": crossfade(made, a, b, u)}+ made_at[key] = (made, {"proposal": measure, "look": looks(measure),+ "faults": faults(measure) + ([] if made.getchannel("A").getbbox() else ["empty"])})+ frame, said = made_at[key]+ row.update(said)made_rows.append(row)new[q] = frameshown = [q for q in run if new[q] is not frames[q]]after_flow = _flow(new, box, (flow["runs"], flow["hold"]))rel_after = after_flow["step"] / scale- moved = np.abs(np.diff(np.array([drift_points(new[q]) for q in stretch]), axis=0)).max(axis=0)+ moved = np.abs(np.diff(np.array([drift_points(new[q], torso) for q in stretch]), axis=0)).max(axis=0)over = bool(np.any(~np.isfinite(moved)) or np.any(moved > bound + DRIFT_PIXEL + 1e-9))part_before = float(rel[steps_at][:, part].max()) if part else 0.0part_after = float(rel_after[steps_at][:, part].max()) if part else 0.0@@ -960,7 +1042,8 @@ def overlap_wrap(frames: list[Image.Image], others: dict[str, dict[int, Image.Im"step_max_after": [round(float(v), 4) for v in rest_after],"faster": [[round(v, 4) for v in flow["fractions"][w]] for w in faster]},"drift": {"measures": list(DRIFT_MEASURES), "bound": [round(float(v), 3) for v in bound],- "moved": [round(float(v), 3) for v in moved], "over": over},+ "moved": [round(float(v), 3) for v in moved], "over": over,+ "body_mass": {"bound": mass_step([frames[q] for q in stretch]), "moved": mass_step([new[q] for q in stretch])}},"off_max": {"before": round(float(off_before[stretch].max()), 4), "after": round(float(off_after[stretch].max()), 4)},"rushes": rushes, "faults": wrong, "look": sorted({w for r in made_rows for w in r["look"]}),"outcome": "rejected" if rejected else "accepted"})@@ -1016,7 +1099,7 @@ def _give_way(frames: list[Image.Image], j: int, ghosts: dict[int, float], interdef repair_jumps(frames: list[Image.Image], interpolate: Interpolate | None, *, facing: str = "right",limit: float = FLOW_LIMIT, span: int = FLOW_SPAN, max_frames: int = MAX_REPAIRS,screen: dict[str, Any] | None = None, ease: bool = True,- overlapped: Iterable[int] = ()) -> tuple[list[Image.Image], dict[str, Any]]:+ overlapped: Iterable[int] = (), torso: Torso | None = None) -> tuple[list[Image.Image], dict[str, Any]]:"""Replace each filmed ghost the screen names, then take out each group of frames off the loop's flow andmake it again with RIFE between the frames either side, worst first (docs/loop-repair.md section 2).@@ -1041,7 +1124,8 @@ def repair_jumps(frames: list[Image.Image], interpolate: Interpolate | None, *,(`surges`, recorded as `surge`) is eased over a stretch of EASE_WIDTHS drawings either side, made from the framesas filmed (a frame the flow made inside it is made again, `supersedes`), each drawing at the time `ease_times`chooses and shown on every frame it was; the stretch is taken only where no made frame has a fault, no body- measure moves further than the stretch did and a pixel (`drift`), the part's largest step falls (`part`), no+ measure moves further than the stretch did and a pixel (`drift`, the body's point the torso, `torso` — the loop's+ `Torso` when not given, recorded as `torso`), the part's largest step falls (`part`), noframe is left further off the flow than the limit and before, no new rush appears in the rest of the body, andno window of the rest of the body steps further than its own largest step over the stretch as it played (`rest`)(`rejected_for` names what failed). Its calls are its own, outside `max_frames` (`ease_calls`). `surge_after`@@ -1122,7 +1206,8 @@ def repair_jumps(frames: list[Image.Image], interpolate: Interpolate | None, *,off_max_after=plan["off_max_before"])given = {j for j in replaced if j in ghosts}blocked = given | set(refused) | overlapped- out = _ease(frames, out, interpolate, box, blocked, set(replaced) - given, set(replaced) | overlapped, reads, record, ease)+ out = _ease(frames, out, interpolate, box, blocked, set(replaced) - given, set(replaced) | overlapped, reads, record, ease,+ torso)eased = [r for r in record["rounds"] if r["why"] == "ease" and r["outcome"] == "accepted"]if eased:record["replaced"] = [*replaced, *(t for t in eased[0]["replaced"] if t not in replaced)]diff --git a/tests/video/test_loop_ease.py b/tests/video/test_loop_ease.pyindex 9488c01..276e915 100644--- a/tests/video/test_loop_ease.py+++ b/tests/video/test_loop_ease.py@@ -1,7 +1,7 @@# SPDX-License-Identifier: Apache-2.0"""The eased retime (docs/loop-repair.md section 2, "The eased retime"): where a part rushes — a run of one ortwo steps far faster than the steps around it, going the way it was going — the frames either side are made-again at times the search chooses, so the part's speed rises and falls gradually; the body's feet, mass and+again at times the search chooses, so the part's speed rises and falls gradually; the body's feet, torso andground line move no further in a step than they did anywhere in that stretch, nor any window of the rest of thebody further than its own largest step there, read on the frames made; the loop keeps its length, and everyframe outside the stretch is the video's own. A frame flung against the way is the flow repair's, not a rush;@@ -71,15 +71,10 @@ class Lerp:return self.made[-1]-def _drift(frames: list[Image.Image], segment: list[int]) -> np.ndarray:- """The largest step over the segment's steps, in play order, of where the body stands: the foot line's centre- and the body's mass (`--anchor feet`'s drift reference) and the lowest solid row."""- def where(f: Image.Image) -> np.ndarray:- box = f.getchannel("A").point(lambda v: 255 if v >= 8 else 0).getbbox()- rows = np.nonzero((np.asarray(f.getchannel("A")) >= 128).any(axis=1))[0]- return np.array([loop_mod.foot_centre(f, box), loop_mod.body_centre(f, box), float(rows.max())])-- points = [where(frames[k]) for k in segment]+def _drift(frames: list[Image.Image], segment: list[int], torso: repair.Torso) -> np.ndarray:+ """The largest step over the segment's steps, in play order, of where the body stands: the foot line's centre,+ the torso (`torso`: the head and torso the motion anchor tracks) and the lowest solid row."""+ points = [repair.drift_points(frames[k], torso) for k in segment]return np.max(np.abs(np.diff(points, axis=0)), axis=0)@@ -134,9 +129,13 @@ def test_a_tail_that_rushes_on_at_the_wrap_is_eased_over_the_frames_either_side(# from step to step, and no rush is leftassert round_["part"]["step_max_after"] <= 3 / 4 * round_["part"]["step_max_before"]assert round_["accel"]["chosen"] < round_["accel"]["before"] / 2 and record["surge_after"] is None- # no drift: the feet, the body's mass and the ground line move no further in a step than they did there, to within- # the pixel they are read on; and the rest of the body no faster- assert np.all(_drift(out, segment) <= _drift(flow_only, segment) + repair.DRIFT_PIXEL)+ # no drift: the feet, the torso and the ground line move no further in a step than they did there, to within the pixel+ # they are read on — the torso read on the loop as filmed, as the round read it; the body's mass reported beside it;+ # and the rest of the body no faster+ torso = repair.Torso(frames)+ assert record["torso"] == torso.said() and record["torso"]["regions"]+ assert np.all(_drift(out, segment, torso) <= _drift(flow_only, segment, torso) + repair.DRIFT_PIXEL)+ assert round_["drift"]["measures"] == ["foot_centre", "torso_centre", "ground"] and set(round_["drift"]["body_mass"]) == {"bound", "moved"}_kept_rest(frames, flow_only, out, round_)changed = {k for k in round_["frames"] if out[k] is not frames[k]}assert round_["replaced"] == sorted(changed, key=round_["frames"].index) and len(changed) >= len(round_["frames"]) - 2diff --git a/tests/video/test_loop_overlap.py b/tests/video/test_loop_overlap.pyindex b81c707..258564e 100644--- a/tests/video/test_loop_overlap.py+++ b/tests/video/test_loop_overlap.py@@ -6,7 +6,8 @@ the loop passes the gate, still two steps, its body standing where it stood.The walker is seen from the front, 26 frames a cycle, its tail swinging round on a beat of 41 frames, in a 73-frame clip.The interpolator is a stand-in that draws the walker between two frames the way an optical-flow in-between does: the body-at the time between them, the tail's tip on the line between its two places. Synthetic frames only."""+at the time between them, the tail's tip on the line between its two places. A second walker, a big tuft bobbing on a+short tail, is carried over at the wrap with its torso where it stood, or with its torso sliding. Synthetic frames only."""from __future__ import annotations@@ -24,6 +25,10 @@ from tests.video.test_loop_repair import _no_rifeFRAMES, CYCLE, TAIL = 73, 26, 41REACH, LIFT, TUFT = 40, 14, 18 # the tail's tip swings round this far sideways and up and down, px; its tuft's radius+# The second walker: a tuft of BIG_TUFT px held at the hips, bobbing BOB px up and down every BOB_FRAMES frames — 2.6 bobs+# a cut, which starts it at the bottom of its bob and ends it at the top — and a cycle on carried ASIDE px a frame sideways;+# where its torso slides, the whole walker stands SLID px aside a cycle on (the clip walked on over the cycle).+BIG_TUFT, BOB, BOB_FRAMES, ASIDE, SLID = 30, 16, 10, 8, 3def _tip(k: float) -> tuple[float, float]:@@ -31,17 +36,22 @@ def _tip(k: float) -> tuple[float, float]:return REACH * math.sin(a), LIFT * math.cos(a)-def _walker(body: float, tip: tuple[float, float]) -> Image.Image:+def _bob(k: float) -> float:+ return BOB * math.cos(2 * math.pi * k / BOB_FRAMES)+++def _walker(body: float, tip: tuple[float, float], *, tuft: float = TUFT, hang: int = 72, aside: int = 0) -> Image.Image:"""The walker at `body` frames into its walk, its tail's tip at `tip`: legs side by side, the nearer foot drawn lower- each step, arms swinging opposite, and a tail from the hips ending in a tuft."""+ each step, arms swinging opposite, and a tail from the hips ending in a tuft of radius `tuft`, `hang` px below the head+ at rest; the whole walker `aside` px right of its place."""ph = 2 * math.pi * (body + 5) / CYCLEim = Image.new("RGBA", (300, 240))d = ImageDraw.Draw(im)- cx, y = 150, 40 + round(2 * math.cos(2 * ph))+ cx, y = 150 + aside, 40 + round(2 * math.cos(2 * ph))drop = round(6 * math.sin(ph))tx, ty = tip- d.line((cx, y + 60, cx + tx, y + 72 + ty), fill=(180, 120, 40, 255), width=18)- d.ellipse((cx + tx - TUFT, y + 72 + ty - TUFT, cx + tx + TUFT, y + 72 + ty + TUFT), fill=(200, 140, 60, 255))+ d.line((cx, y + 60, cx + tx, y + hang + ty), fill=(180, 120, 40, 255), width=18)+ d.ellipse((cx + tx - tuft, y + hang + ty - tuft, cx + tx + tuft, y + hang + ty + tuft), fill=(200, 140, 60, 255))d.rectangle((cx - 12, y + 80, cx - 1, y + 120 + drop), fill=(60, 60, 70, 255))d.rectangle((cx, y + 80, cx + 11, y + 120 - drop), fill=(60, 60, 70, 255))d.rectangle((cx - 16, y + 30, cx + 16, y + 84), fill=(200, 80, 80, 255))@@ -85,6 +95,62 @@ class Between:return out+def _bobbing(body: float, tip: tuple[float, float], aside: int = 0) -> Image.Image:+ """The second walker: the walker with a big tuft on a short tail, whose bob moves the picture and not the body's mass."""+ return _walker(body, tip, tuft=BIG_TUFT, hang=56, aside=aside)+++def _pixels(frame: Image.Image) -> str:+ return hashlib.sha256(frame.tobytes()).hexdigest()+++class Drawn:+ """A stand-in RIFE for frames drawn here (`draw`), each known by its pixels where it stands: between two of them at t,+ the walker at the second's time, its tail's tip and its place t of the way along the line between the two's. Records+ each call as (time of a, time of b, t)."""++ def __init__(self, walker):+ self.walker = walker+ self.of: dict[str, tuple[float, tuple[float, float], int]] = {}+ self.calls: list[tuple[float, float, float]] = []++ def draw(self, body: float, tip: tuple[float, float], aside: int = 0) -> Image.Image:+ frame = self.walker(body, tip, aside)+ self.of[_pixels(frame)] = (body, tip, aside)+ return frame++ def __call__(self, a: Image.Image, b: Image.Image, t: float) -> Image.Image:+ (ba, (xa, ya), sa), (bb, (xb, yb), sb) = self.of[_pixels(a)], self.of[_pixels(b)]+ self.calls.append((ba, bb, round(t, 4)))+ return self.draw(bb, (xa + t * (xb - xa), ya + t * (yb - ya)), round(sa + t * (sb - sa)))+++def _second(slid: int = 0) -> tuple[Drawn, list[Image.Image], dict[str, dict[int, Image.Image]]]:+ """The second walker's loop as cut, its tuft bobbing and the walker in its place; and the clip's frames a cycle after+ its first ones, the tuft carried on its bob and ASIDE px a frame sideways, the whole walker `slid` px aside."""+ drawn = Drawn(_bobbing)+ frames = [drawn.draw(q, (0.0, _bob(q))) for q in range(CYCLE)]+ after = {q: drawn.draw(q, (ASIDE * (q + 1), _bob(CYCLE + q)), slid) for q in range(max(repair.OVERLAP_WIDTHS) + 1)}+ return drawn, frames, {"after": after, "before": {}}+++def _overlapped(drawn: Drawn, frames: list[Image.Image], others: dict) -> tuple[list[Image.Image], dict]:+ """The overlapped wrap of the second walker's loop, its steps taken as two (the walker shows no crossings)."""+ return repair.overlap_wrap(frames, others, drawn, seam=loop.wrap_on_cells, steps=lambda f: {"verdict": "two"},+ seam_max=loop.SEAM_RATIO_MAX, reads=True)+++def _places(tried: dict, slid: int) -> list[int]:+ """Where the walker stands, px aside, on each frame of a try's stretch as it was shown: its place where the loop shows+ its own frame, and t of the way from SLID to it on a frame made at t."""+ made = {r["frame"]: r["t"] for r in tried["made"]}+ return [round((1 - made[q]) * slid) if q in made else 0 for q in tried["stretch"]]+++def _mass_step(frames: list[Image.Image]) -> float:+ return float(np.abs(np.diff([loop.body_centre(f, f.getbbox()) for f in frames])).max())++def _keyed(root: Path) -> Path:keyed = root / "keyed"keyed.mkdir(parents=True)@@ -120,9 +186,9 @@ def test_a_tail_on_its_own_beat_is_closed_at_the_wrap_with_the_clips_frames_a_cyassert taken["rest"]["faster"] == [] and taken["faults"] == [] and taken["rushes"] == []assert taken["part"]["step_max_after"] < taken["part"]["step_max_before"]# each frame of a run shown between the clip's frame a cycle apart and the cut's own, at the weight the search chose,- # the weights never going back toward the frame a cycle apart; RIFE asked only for a frame between the two- assert overlap["calls"] == len(between.calls) == sum(0 < r["t"] < 1 for t in overlap["tries"] for r in t.get("made", []))- calls = list(between.calls)+ # the weights never going back toward the frame a cycle apart; RIFE asked only for a frame between the two, and once+ # for a frame at one weight, whatever the run+ calls, asked = list(between.calls), set()for tried in overlap["tries"]:sign = 1 if tried["side"] == "after" else -1assert tried["frames"] == repair.overlap_run(tried["side"], tried["width"], L)@@ -131,9 +197,11 @@ def test_a_tail_on_its_own_beat_is_closed_at_the_wrap_with_the_clips_frames_a_cyfor r in tried.get("made", []):q = r["frame"]late, early = (s + q + L, s + q) if sign > 0 else (s + q, s + q - L)- if 0 < r["t"] < 1:+ if 0 < r["t"] < 1 and (tried["side"], q, r["t"]) not in asked:+ asked.add((tried["side"], q, r["t"]))ka, kb, t = calls.pop(0)assert (ka, kb) == (late, early) and abs(t - r["t"]) < 1e-3+ assert calls == [] and overlap["calls"] == len(between.calls) == len(asked)run = overlap["frames"]# every other frame is the clip's own, and nothing else was madeassert report["jump_repair"]["overlapped"] == run and report["jump_repair"]["replaced"] == []@@ -143,6 +211,60 @@ def test_a_tail_on_its_own_beat_is_closed_at_the_wrap_with_the_clips_frames_a_cyassert [filmed.get(_key(Image.open(p).convert("RGBA"))) for p in cells] == [None if q in run else s + q for q in range(L)]+def test_the_drift_bound_is_the_stretch_as_the_loop_plays_it_never_the_clips_frames_a_cycle_apart():+ """(a) The validator's counterexample, in synthetic form: the clip's own step into its frame a cycle on moves the body's+ mass further than any step of the stretch — the second walker's tuft carried 8 px aside a frame — and a run made near+ that frame was taken against a bound read off those frames. Every run's bound is the stretch's own, as the loop plays+ it: the foot line's and the ground's largest steps there, and the torso's, which stands where it stood (the walker is+ drawn in its place on every frame of the loop); the body's mass is reported beside it, its own largest step there."""+ drawn, frames, others = _second()+ new, record = _overlapped(drawn, frames, others)+ assert record["seam"] > loop.SEAM_RATIO_MAX+ made = [t for t in record["tries"] if "made" in t]+ assert made+ for tried in made:+ stretch = [frames[q] for q in tried["stretch"]]+ played = np.abs(np.diff([repair.drift_points(f) for f in stretch], axis=0)).max(axis=0) # the feet and the ground+ foot, torso, ground = tried["drift"]["bound"]+ assert (foot, ground) == pytest.approx((played[0], played[2]), abs=1e-3) and torso < 0.1+ assert tried["drift"]["body_mass"]["bound"] == pytest.approx(_mass_step(stretch), abs=1e-3)+++def test_a_torso_that_slides_is_refused_however_the_tail_swings():+ """(b) The second walker whose frames a cycle on stand SLID px aside as well as carrying the tuft over: the clip walked+ on over the cycle, and a frame made near those frames slides the torso. Read on the torso, no run moves the walker+ further in a step than the stretch's own largest step (it stands still there) and a pixel — its place on the frames+ shown, drawn again — so the frame next to the wrap is held toward the cut's own, off the ease; the wrap stays open and+ the cut is kept as filmed for the gate to refuse."""+ drawn, frames, others = _second(slid=SLID)+ new, record = _overlapped(drawn, frames, others)+ made = [t for t in record["tries"] if "made" in t]+ assert made+ for tried in made:+ assert np.abs(np.diff(_places(tried, SLID))).max() <= repair.DRIFT_PIXEL+ assert tried["made"][0]["t"] > tried["eased"][0] + 0.25+ assert record["frames"] == [] and all(a is b for a, b in zip(new, frames))+++def test_a_tail_carried_over_alone_is_taken_the_torso_within_its_pixel():+ """(c) The second walker with only its tuft carried over, the walker in its place: the run is taken near the ease and+ the loop passes the gate. Its torso moves within the stretch's own largest step and a pixel; the body's mass, which the+ tuft pulls, moves 2 px and more past its own, reported, not held: moving that part is what the run is for."""+ drawn, frames, others = _second()+ new, record = _overlapped(drawn, frames, others)+ assert record["frames"], [(t["width"], t.get("rejected_for")) for t in record["tries"]]+ taken = record["tries"][-1]+ assert taken["outcome"] == "accepted" and taken["seam"] <= loop.SEAM_RATIO_MAX+ assert taken["made"][0]["t"] <= taken["eased"][0] + 0.1+ (_, torso, _), (_, moved, _) = taken["drift"]["bound"], taken["drift"]["moved"]+ assert torso < 0.1 and moved <= torso + repair.DRIFT_PIXEL+ assert record["torso"]["regions"]+ stretch = taken["stretch"]+ assert _mass_step([new[q] for q in stretch]) > _mass_step([frames[q] for q in stretch]) + 2 * repair.DRIFT_PIXEL+ assert taken["drift"]["body_mass"] == pytest.approx({"bound": _mass_step([frames[q] for q in stretch]),+ "moved": _mass_step([new[q] for q in stretch])}, abs=1e-3)++def test_the_cut_as_filmed_is_refused_at_the_seam_with_the_repair_off(tmp_path):report = _cut(tmp_path, _keyed(tmp_path), repair_mode="off")assert report["status"] == "failed" and report["error"].startswith("video-loop: loop seam ratio")@@ -179,9 +301,10 @@ def test_a_made_frame_with_a_fault_refuses_the_run_and_the_wrap_is_cut_as_filmedoverlap = report["wrap_overlap"]assert overlap["frames"] == [] and [t["width"] for t in overlap["tries"]] == list(repair.OVERLAP_WIDTHS)assert all(t["outcome"] == "rejected" and "fault" in t["rejected_for"] for t in overlap["tries"])- # the overlapped wrap's calls first; the jump repair then reads the cut as filmed, its wrap off the flow- made = [r["t"] for t in overlap["tries"] for r in t["made"] if 0 < r["t"] < 1]- assert overlap["calls"] == len(made) and calls[:len(made)] == pytest.approx(made, abs=1e-3)+ # the overlapped wrap's calls first, once a frame and weight; the jump repair then reads the cut as filmed, its wrap off+ # the flow+ made = list(dict.fromkeys((t["side"], r["frame"], r["t"]) for t in overlap["tries"] for r in t["made"] if 0 < r["t"] < 1))+ assert overlap["calls"] == len(made) and calls[:len(made)] == pytest.approx([t for _, _, t in made], abs=1e-3)assert "the overlapped wrap was refused" in capsys.readouterr().err