Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
fix(align): keep a frame given way on the walk's beat, judge a limb seen through, and name a take that jumps or steps the same foot twice
Soohong Kim3d6f6d8530de
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 202cd3f..569ef88 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,194 @@All notable public changes to `sprite-gen` are recorded here. Versions track the `version:` field in `SKILL.md` and `pyproject.toml`.+## Unreleased++**Upgrading from 3.3.0: `video-cycle-align` now reads ghost bands in windows of the body to catch limbs+seen through, keeps frames given way on the beat under `--between auto` by making them again at clean+fractions or widening jolts across neighbouring frames, changing only alignment outputs whose beat broke+(a jolt of 0.25 beat or more) or where a made frame has a limb seen through (ghost window over 1.4 %);+loops keeping the beat, loops with no frame given way, and `video-loop` (and `video-set`) keep their+bytes for strip PNG, GIF, WebP, and cycle frames, while gaining `beat`, `ghost_window`, (on back and+back_diagonal views) `same_foot`, and `retake` reasons (`broken-beat`, `same-foot`) in alignment+`strip.json` and reports; every aligned loop's `strip.json` and report gain `screen`, and loops whose cut+jumps gain the reasons `filmed-jump` and `seam-jump`, frames unchanged; and `clip_feet` in `video-loop`'s+`strip.json` and reports for every walk or run cut; all outputs from `video-loop-compare` and+`video-loop-repair` are unchanged, bytes included, and `--same-foot` defaults to `warn` so nothing is+refused by default.**++- **New: a made frame's ghost band is now also read in windows of the body (`rife.ghost_window`, constant+ `rife.GHOST_BAND` = 0.10) to catch limbs seen through.** On frames the cycle alignment makes,+ `rife.ghost_window` counts the same part-covered pixels in regions at least `rife.GHOST_THICK` (5 px)+ thick that `rife.ghost` counts, but in windows a tenth of the body high sliding a quarter window at a+ time down the body, each as a share of the solid pixels in that window, reading the largest window's+ share and where it lies as fractions of the body from the top (`ghost_window_at`). Over+ `interpolation_quality.GHOST_WINDOW_WARN` = 0.014 (1.4 % of a window's solid pixels), the made frame has+ the fault `ghost` (though whole-body `ghost` stays under 0.3 %) and gives way, or is made again at another+ fraction, warning that it carries a limb seen through (for example: "carries a part-covered band over+ 2.40 % of the solid pixels in a band 10 % of its body high (60 to 70 % down it), at least 5 px thick,+ though 0.18 % of its whole body, a limb seen through, a ghost"). This catches RIFE blending coverages+ over a gap beside a limb; it is not read on `video-loop`'s jump repair frames or filmed frames.+- **New: `video-cycle-align` reads the loop's beat and keeps frames given way on it under+ `--between auto`, checks for the same foot stepping twice, and `video-loop` records whether each cut+ steps the same foot twice (`clip_feet`).** On every aligned loop, `video-cycle-align` reads the leg+ path over the lowest `LEG_PATH_BAND` = 0.10 of the figure box (`BLOCK` 8 x 8 px, `SEARCH` 12 px,+ `MATCH_BAD` 40 of 255, `READ_HEIGHT` 410 px) and measures the beat jolt across each gap (`BEAT_JOLT`+ = 0.25 beat). Under `--between auto` (the default), where a loop's beat breaks from frames given way+ to the nearer source frame, the frames given way are taken in runs of neighbouring frames and made+ again at clean fractions (`align.RETIME_T` = 0.15 to 0.85, step 0.05) within `BEAT_JOLT` of their+ times, or their jolt is spread over neighbouring frames (`align.WIDEN` = 2, then 3 frames each side)+ moved off their own times and made by RIFE. A frame made only to keep the beat is taken only where+ its window reading is under `align.RETIME_WINDOW_MAX` = 0.006, well under the 1.4 % fault limit,+ besides having no fault. Runs that cannot be kept stay on the nearer source frame, are named in+ `beat.named`, and carry the `broken-beat` reason under `--between auto` in the `retake` record when+ beat gaps remain at `BEAT_JOLT` or more. On views where feet stand side by side (`STEP_VIEWS` = back,+ back_diagonal), `video-cycle-align` reads whether the same foot steps twice in a row (`FOOT_ROWS` = 0.03,+ `LIFT_MIN` = 0.010, `LIFT_CELLS` = 2, `DOWN_MAX` = 0.006), recording reason `same-foot`, and warns+ under `--same-foot warn` (the default) or stops the set before anything is rewritten under+ `--same-foot refuse`. Each reason has one warning line replacing earlier separate beat and same-foot+ lines, naming what is likely to fix it ("retake", "recut", or "recut-or-retake"), and the report's+ `retake` list carries these loops like the others (under `--between nearest` a broken beat is recorded+ in `beat` but is no reason). `video-loop` reads every cut of the cut's length on keyed frames of+ walks and runs, recording for every cut whether that cut, looped, steps the same foot twice (`clip_feet`)+ in `strip.json` and its report.+- **New: `video-cycle-align` reads a jump the take films between two of its frames, or at the cut's seam,+ on the screen as well as the beat.** For each step of the cut's own frames (`cycle.source/`, step i+ from frame i to i + 1, the last step from the last frame to the first, which is the cut's seam),+ `cadence.screen_steps(frames)` reads the mean absolute luminance difference over white (0 to 255) of+ the box every frame's figure fits in (`whole`) and of its lowest `cadence.SCREEN_ROWS` = 0.30 (`legs`;+ a strip cell's lowest 125 of its 406 px), read at `READ_HEIGHT` 410 px. The beat reads only the leg+ path where the feet go (the lowest 10 % of the box); two drawings filmed a pose apart (legs wide apart+ in one, crossed in the next, the tail up) move the feet little and change the picture much, so the beat+ passes them, but the screen sees them. It is read on the cut's own frames, not on the aligned frames+ (an aligned frame spans two or three of the cut's frames, which spreads a jump over the drawing changes+ beside it and hides it), on every aligned loop whatever its view and whatever `--between`. Under+ `cadence.screen_record`, a step is a jump when, over the box or on its leg rows, it is at least+ `cadence.SCREEN_JUMP` = 2.0 times the cycle's typical step and at least `cadence.SCREEN_ALONE` = 1.3+ times every other step of the cycle. The typical step is the upper quartile of the cycle's steps: on+ ones every step is a drawing change, on twos or threes most steps change nothing and the upper quartile+ is a drawing change. A cycle whose drawing changes are all alike names none; so does a cycle with two+ steps alike however large (neither is 1.3 times the other). A jump inside the cut gives the `retake`+ reason `filmed-jump` (details `filmed_jump`: `steps`, `at`, `whole`, `legs`, `remedy`+ "recut-or-retake"), because the take jumps between two poses there and the alignment does not change+ the poses a take shows; where the clip films another cycle without the jump, a cut of the same clip+ from there removes it, and where it does not, a new take does. A jump at the seam gives `seam-jump`+ (details `seam_jump`, same keys, `remedy` "recut-or-retake"), because another cut of the clip may close+ on a pose it holds, or a new take may not need the cut to close there (limits `screen_jump`,+ `screen_alone`, `screen_rows`). Warning lines name what is likely to fix it (for example: "<loop>: cut+ it again or film this direction again (filmed-jump): the take jumps between two of its frames, from+ frame 30 to 31 of cycle.source/ the picture changes 22 of 255 over the figure's box and 36 on its legs,+ 2.10 and 2.50 times the cut's typical step and 1.50 and 1.80 times any other step (the loop's frames 13+ to 14); the alignment does not change the poses a take shows. Where the clip films another cycle+ without the jump, a cut there fixes it; where it does not, a new take does", or for a seam jump:+ "<loop>: cut it again or film this direction again (seam-jump): the cut's seam jumps, from frame ... ;+ another cut of the clip may close on a pose it holds, a new take may not need the cut to close there").+- **Report fields:** `cycle_align.beat` in `strip.json` and report row `beat` record `jolt`, `gap`,+ `over`, `jolts`, `limit` (0.25), `band` (0.1), and `path` (`read`, `on-time`, or `unread` with+ `why`). Each `smear` row (and a frame made again, under `retimed`) records `ghost_window` and+ `ghost_window_at` ([from, to] fractions of the body); both are `null` where the ghost screen does not+ read the loop. A retimed frame's row in `smear` has `method: "retimed"` (beside `rife` kept and+ `nearest` given way), keeps its first frame's measures and `faults`, and gains `retimed`: `t`,+ `from_t`, `off`, measures, `faults: []`, `look`. Every frame given way in a loop whose beat broke gains+ `retime`: `between`, `tried` (each fraction recording `ghost_window`, and `window_over` where it had no+ fault but read over the bar), `off_nearest`. Retimed frames count in `made_at` and `made_by_rife`, not+ `nearest_at` or `replaced`; the report gains a set-wide `retimed` count, and `beat.retimed` lists them+ per loop. Widened runs record in `beat.widened` (`run`, `width`, and `moved` with `at`, `off`, new+ source or pair and fraction); moved frames carry `smear` `method: "moved"` with `moved` and count in+ `made_at`. Runs kept on the nearer source frame record in `beat.named`. `cycle_align.same_foot` in+ `strip.json` and the report row records `read`, `order`, `steps` (`half`, `frames`, `peak`, `lift`),+ `twice`, and `clip`. `clip_feet` in `strip.json` and the `video-loop` report records `length`, `cuts`,+ `same_foot`, `alternate`, `unread`, `seam_in_step`, and `same_foot_at`. Each loop row and `strip.json`+ `cycle_align` gain `screen`: `whole` and `legs` (every step), `typical` (per region), `jumps` (each: `step`+ [i, i + 1] as frames of cycle.source/, `seam` true for the last step, `whole` and `legs` each [change, times+ the typical step, times the next largest step], `at` the gaps [k, k + 1] of the aligned (turned) loop that show+ it), and `limits` (`jump`, `alone`, `rows`). Under `--same-foot refuse`, a+ refused report is written with `applied: false`, `refused: "same-foot"`, and `same_foot`; the report's+ `same_foot` key names the mode. A loop's `retake` record (keeping its shape: `reason` the first,+ `reasons` all, details under each reason's snake_case key, `limits`) gains reasons `filmed-jump`+ (details `filmed_jump`: `steps`, `at`, `whole`, `legs`, `remedy`), `seam-jump` (details `seam_jump`: `steps`,+ `at`, `whole`, `legs`, `remedy`; limits `screen_jump`, `screen_alone`, `screen_rows`), `broken-beat` under+ `--between auto` (details `broken_beat`: `jolt`, `gap`, `over`, `named`, `remedy`; limit `beat_jolt`)+ and `same-foot` (details `same_foot`: `order`, `twice`, `clip` counting `length`, `cuts`, `same_foot`,+ `alternate`, `unread`, `seam_in_step`, or null, `remedy`; limits `lift_min`, `lift_cells`, `down_max`),+ in order: held-drawings, filmed-ghost, filmed-jump, seam-jump, broken-beat, same-foot; `remedy` is "retake",+ "recut", or "recut-or-retake", and the report's `retake` list carries these loops like the others.+- **Python callers:** new module `sprite_gen/video/cadence.py` with `leg_path`, `Beat`, `beat_record`,+ `turned`, `same_foot`, `clip_feet`, `view_reads_feet`, `screen_steps`, `screen_record` and constants+ `LEG_PATH_BAND` (0.10), `READ_HEIGHT` (410), `BLOCK` (8), `SEARCH` (12), `MATCH_BAD` (40.0),+ `BEAT_JOLT` (0.25), `STEP_VIEWS`, `FOOT_ROWS` (0.03), `LIFT_MIN` (0.010), `LIFT_CELLS` (2),+ `DOWN_MAX` (0.006), `SCREEN_ROWS` (0.30), `SCREEN_JUMP` (2.0), and `SCREEN_ALONE` (1.3); in+ `sprite_gen/video/rife.py` `ghost_window` and `GHOST_BAND` (0.10); in+ `sprite_gen/video/interpolation_quality.py` `GHOST_WINDOW_WARN` (0.014); in `sprite_gen/video/align.py`+ `measure_made(frame, a, b, t, reads=...)` (returning every measure a made frame is judged by),+ `retake(..., beat=None, feet=None, screen=None)`, `RETAKE_JUMP_REASON` ("filmed-jump"),+ `RETAKE_SEAM_REASON` ("seam-jump"), `RETAKE_BEAT_REASON`, `RETAKE_FEET_REASON`, `REMEDIES`,+ `RETIME_WINDOW_MAX` (0.006), `RETIME_T`, `WIDEN` (2, 3), `SAME_FOOT` ("warn", "refuse"),+ `align_set(..., same_foot="warn")`, and `resample` facts gaining `beat`.+- **Output changes:** under default `--between auto`, alignment outputs where frames given way broke the+ beat change when retimed or widened to keep the beat under `BEAT_JOLT` (0.25 beat), or where a made+ frame has a limb seen through (ghost window over 1.4 %) and gives way or is made again; loops whose+ frames given way keep the beat, loops with no frame given way or faulty made frame, and all outputs+ under `--between nearest` and `rife` keep their exact bytes across strip PNG, GIF, WebP, and cycle+ frames (gaining the `beat` record, `ghost_window`, `retake` reasons, and where `--view` is back or+ back_diagonal `same_foot` in `strip.json` and reports; under `--between rife` the alignment keeps the+ made frame and names it a ghost); every aligned loop's `strip.json` and report gain `screen`, and loops+ whose cut jumps gain the reasons, frames unchanged. For `video-loop` (and the loops `video-set` cuts),+ `strip.json` and report files gain `clip_feet` on every walk or run cut, while strip PNG, GIF, WebP,+ and cycle frames keep their exact bytes. All outputs from `video-loop-compare` and `video-loop-repair`+ are unchanged, bytes included.+- **Tests:** synthetic test suite in `tests/video/test_cycle_align_beat.py` uses figures with an+ outlined body over two outlined feet 16 px wide (two blocks) on the ground, sliding together by 8 px+ (a block) at each drawing forward half the cycle and back, with the interpolator drawing them at the+ fraction and smearing the body where told the pair breaks, and feet standing side by side lifting in+ turn. Tests cover: a cut of 54 frames on threes aligned to 24 where every fourth frame falls half way+ between drawings with RIFE smearing at fractions 0.45 to 0.55, the nearer source frame leaving a jolt+ of 2/3 of a beat (which 3.3.0 failed) and the fix making each again at 0.4 (0.13 of a beat early,+ largest jolt 0.13, nothing named); a fraction made again with no fault but a block the background shows+ through (its window between 0.6 % and 1.4 %) is passed over for the next clean fraction (0.6 instead of+ 0.4), its try recording `window_over`; a cut of 20 stretched to 30 with two neighbouring frames given+ way, where making each again nearest its own fraction jolts the gap between them 0.325 beat but the+ run's choice (0.55 and 0.2) keeps every gap under 0.25 beat (largest 0.2), and where 0.55 is not clean+ both stay on the nearer source frame (named, largest jolt 1.0); a frame whose pair breaks at every+ fraction within the limit, half a beat late on the nearer frame, where two frames each side are moved+ a third and a sixth of a beat late and made there (every gap jolting a sixth of a beat); a cut of 40+ squeezed to 24 with one frame given way a fifth of a beat off on the nearer frame delivered as before+ without remaking; every frame at its own time giving jolt 0 without reading legs; `--between nearest`+ recording the jolt it leaves; same foot detection on back loops reading "RRL" (twice) and alternating+ "RL" round the ring, dipping under `LIFT_MIN` without reaching `DOWN_MAX` reading one step and reaching+ `DOWN_MAX` reading two steps, front, front diagonal, side, and no view not read, one half stepping not+ read, the clip that steps the same foot twice every cycle reading 29 of its 49 cuts so and 20 with their+ seam inside a step, the alternating clip reading 33 cuts alternating and 16 with their seam inside a+ step, a cut shorter than the cycle whose seam joins two right lifts reads, as a loop, right then left+ (alternating), and a clip holding just that cut counts it apart (`seam_in_step` 1, neither alternating+ nor the same foot), and a cut 1.5 cycles long joining a step to the same foot's next; a loop whose+ beat still breaks and a loop that steps the same foot twice carrying reasons `broken-beat` and+ `same-foot` with remedies (`--between nearest` and a beat with no gap over being no reason);+ integration through `video-loop` and `video-cycle-align` recording `clip_feet`, `--same-foot refuse`+ stopping the set with strip untouched and report refused, and naming the same-foot loop "film this+ direction again (same-foot)", with `remedy` "retake" and the clip's counts. New synthetic test suite+ in `tests/video/test_inbetween_seen_through.py` uses a wide body over two legs, the near leg's outer+ 8 columns cut back over 60 rows in the first source frame (a gap open to the space between the legs)+ and whole in the second; the frame made between them has that strip at alpha 0.35 in the leg's colour:+ its whole-body ghost is under 0.3 % and its hole 0, so with no window reading (3.3.0) it has no fault;+ its window reads over 1.4 %, in the legs, and it is judged `ghost`; under `--between rife` the+ alignment keeps it and names it a ghost; a band at alpha just outside 0.1 to 0.9 is not read.+ In tests/video/test_inbetween_doubled.py the frame "drawn between, smeared along the step" (the mean+ of drawings from t 0.35 to 0.65) is no longer among the clean frames: its feet are part-covered over+ 4.5 % of their window, so it is now judged a ghost (smeared half as far it is not); and in+ tests/video/test_held_drawings.py and tests/video/test_ghost_retake.py, loops whose frames the stand-in+ interpolator cross-fades and gives way now also carry `broken-beat` among their `retake` reasons (a+ loop drawn every frame with frames given way, a held loop squeezed past on twos, the filmed-ghost+ loops), held-drawings and filmed-ghost staying first where they apply.+ New tests in `tests/video/test_screen_jump.py` exercise screen jumps synthetically with an outlined+ body over an outlined bar 80 px wide in the leg rows, sliding by the drawing: a cut on threes whose bar+ slides 4 px a drawing except one drawing change of 20 px names that one step a jump (not the seam);+ cuts whose drawing changes are all 4 px name none on ones, twos, and threes; a cut with two 20 px+ changes names none; a cut that slides out all the way and comes back in one step at the seam names a+ seam jump; retake records and warning lines are covered for both reasons; and through `video-loop` and+ `video-cycle-align` at the cut's own length, the jump is named with the aligned loop's frames that show+ it, recorded in `strip.json`, while a cut whose changes are alike names nothing. Also+ `tests/video/test_loop_prop_seam_held.py` now expects `screen` among `cycle_align`'s keys.+## v3.3.0 - PyTorch RIFE backend for CUDA and CPU, executor for a GPU on another machine, and Linux CPU and cloud T4 release lanes**Upgrading from 3.2.0: Defaults stay unchanged, cache keys update once, reports show the backend, install checks model hashes, and schemas are unchanged.** With `SPRITE_GEN_RIFE_BACKEND` unset (the default), RIFE is the `rife-ncnn-vulkan` binary as before. Its frames are the same bytes as 3.2.0. Measured: the binary's frames and sixteen-pass readings through the changed engine equal the old engine's, byte for byte. A `--between-cache` directory kept by 3.2.0 is made again once. The key now names the backend (`backend: "ncnn"`). The engine's `rife.py` changed, and its sha256 is part of the key anyway. Reports take `interpolator.kind` from what made the frames: `rife-ncnn-vulkan` as before for the binary, or `rife-torch` for the new backend. The overlapped wrap's and the seam bridge's records count `binary_calls` for the binary as before, or `runs` for the torch backend. `SPRITE_GEN_RIFE_EXECUTOR` (new) is unset by default, and RIFE runs in this process. `sprite-gen rife install` now checks the model's two files (`rife-v4.6/flownet.param`, `flownet.bin`) against pinned SHA-256 after unpacking, for either backend. A model that differs installs nothing. The line a missing RIFE is reported with (`install` in records, warnings) is `sprite-gen rife install` for the binary. Where the torch backend is chosen, that line is: `pip install "sprite-gen[torch]" && sprite-gen rife install --backend torch`. No command-line flags of `video-loop` / `video-cycle-align` / `video-set` change. No restoration schemas change: `source-restoration-v5`, repair report `schema_version` 4, comparison `schema_version` 6.diff --git a/docs/loop-repair.md b/docs/loop-repair.mdindex 0feff77..339bcf7 100644--- a/docs/loop-repair.md+++ b/docs/loop-repair.md@@ -1377,7 +1377,8 @@ same number of frames, starting on the same step.sprite-gen video-cycle-align --loop-dir set/front-walk/loop --loop-dir set/side-walk/loop \--loop-dir set/back-walk/loop [--view front --view side@right --view back] [--start-foot right] \[--between auto|rife|nearest] [--length N] [--cycles back-walk=2] [--multi-cycle fail|warn] \- [--foot side-walk=left] [--state walk] [--between-cache DIR] [--report set/walk.cycle-align.json]+ [--foot side-walk=left] [--state walk] [--between-cache DIR] [--same-foot warn|refuse] \+ [--report set/walk.cycle-align.json]```- **A loop whose steps are counted is one cycle.** A cut two steps long — taken so a held part@@ -1441,13 +1442,198 @@ sprite-gen video-cycle-align --loop-dir set/front-walk/loop --loop-dir set/side-which would remake every frame, is not offered (section 2).- **Between two source frames** (`--between`): `auto` (default) makes the frame with RIFE,measures it (below) and keeps it unless it has a fault, where the nearer source frame is taken- instead and named — the other one beside it where the nearer is a filmed ghost (below); `rife`- keeps every made frame and names the faulty ones; `nearest` takes the nearer source frame every- time (the other where the nearer is a filmed ghost), so nothing is made and no RIFE is needed, and the motion keeps- the filmed frames at up to half a frame off their time (a loop stretched longer shows a frame- twice, which the GIF and WebP hold as one frame of twice the delay). `video-set` passes- `--align-between`. `auto` runs RIFE for every frame between two source frames, as `rife` does,- and needs it installed the same way.+ instead and named (the other one beside it where the nearer is a filmed ghost, below); under `auto`+ a frame given way is kept on the loop's beat (the next bullets), so the nearer source frame is no+ longer always what is taken; `rife` keeps every made frame and names the faulty ones; `nearest` takes+ the nearer source frame every time (the other where the nearer is a filmed ghost), so nothing is made+ and no RIFE is needed, and the motion keeps the filmed frames at up to half a frame off their time+ (a loop stretched longer shows a frame twice, which the GIF and WebP hold as one frame of twice the+ delay). Under `nearest` the beat is recorded and not warned. `video-set` passes `--align-between`.+ `auto` runs RIFE for every frame between two source frames, as `rife` does, and needs it installed the+ same way.+- **The beat, read on every aligned loop**: the cycle's source frames (`cycle.source/`, as aligned)+ are read where the feet are: the lowest `LEG_PATH_BAND` = 0.10 of the box every frame's figure fits+ in (union of solid pixels, alpha 128 and up). Each 8 x 8 px block (`BLOCK`) holding a part of the+ figure there (a quarter of its pixels solid in this frame or the next) is looked for in the next+ frame within 12 px (`SEARCH`), with a small bias toward no shift so a flat block does not wander;+ the step from frame i to i + 1 is the blocks' mean shift length, in % of the box's height. A block+ that matches nowhere (mean |RGBA| difference over `MATCH_BAD` = 40 of 255) changed shape, a sole+ turning, and counts its residual (scaled to px) instead. Read at a scale where the first frame's+ figure ends at most 410 px down (`READ_HEIGHT`): a cut's frames are drawn about twice a strip's+ size, so a block and the search reach the same part of the figure as on a strip. A cape or tail+ held still over the band adds no shift, where a brightness difference would add its whole change.+ Summed from frame 0 the steps give each source frame a place M(i) on the path, and the cycle its+ length P = M(n). A frame made at fraction t between source frames i and i + 1 stands at+ M(i) + t (M(i + 1) - M(i)). A cycle of n source frames resampled to L frames asks frame k for the+ time k n / L (offset 0); standing there it would be at e_k = M(k n / L). beat = P / L. For every+ gap k to k + 1 (the last to the first): jolt_k = ((p_(k+1) - p_k) mod P - (e_(k+1) - e_k) mod P) /+ beat, in beats, where p_k is where frame k actually stands. It measures how much more (or less) the+ legs move from frame k to k + 1 than the even resample would move them. `BEAT_JOLT` = 0.25 beat: a+ jolt of 0.25 or more (absolute) is a broken beat, a skip into a frame and a halt out of it (or the+ other way). Why 0.25: an aligned frame may then move the legs into it or out of it by up to a quarter+ of a beat more than its own time would, so two even gaps beside it stay within 5 to 3 of each other.+ For example, a cut drawn on threes resampled so a frame falls half way between two drawings leaves+ the nearer source frame as the next drawing, two thirds of a beat early, a jolt of 0.67. Recorded on+ every aligned loop as `cycle_align.beat` in `strip.json` and in the report row's `beat`, as frames of+ the turned loop: `jolt` (largest, 3 decimals), `gap` ([k, k + 1] where it is), `over` (every gap at+ `BEAT_JOLT` or more), `jolts` (every gap's), `limit` (0.25), `band` (0.1), and `path`. `path` is+ `read`; or `on-time` where every frame stands at its own time (jolt 0, the legs not read at all, no+ cost); or `unread` (with `why`) where the legs do not move on the band (a path of no length has no+ beat; the frames given way are then left as before). Only what the alignment moved off its time+ counts: the cut's own rhythm does not, so drawings held two or three frames or one step quicker than+ the next give every jolt 0 when every frame is at its own time. Under `--between nearest` the beat is+ recorded, not warned, and under `rife` every made frame is at its own time.+- **A frame given way, kept on the beat** (`--between auto`): a loop whose frames given way keep the+ beat, and a loop with no frame given way, is delivered byte for byte as before (strip, GIF, WebP,+ every cycle frame; only its `beat` record and, where its `--view` is back or back_diagonal, its+ `same_foot` record are new). Otherwise the loop is kept on the beat in this order:+ - 1. The loop as before (every frame with a fault given way to the nearer source frame, or to the+ other frame beside its time where the nearer is a filmed ghost) is read for its beat. Where no+ gap jolts `BEAT_JOLT` = 0.25 beat or more, it is delivered as before, byte for byte (strip, GIF,+ WebP, every cycle frame; gaining the `beat` record and, where its `--view` is back or+ back_diagonal, the `same_foot` record).+ - 2. Otherwise the frames given way are taken in runs of neighbouring frames (a run across the last+ frame and the first is one run). Each frame of a run has these choices: the nearer source frame as+ before; or the same two source frames made again at another fraction from `align.RETIME_T` = 0.15,+ 0.20, ... 0.85 (step 0.05; the frame's own fraction is not made again), tried nearest its own+ fraction first, kept only where the frame made has no fault (the same readings and `faults()` as+ every made frame) and stands within `BEAT_JOLT` = 0.25 beat of its own time on the leg path+ (fractions further off are not made at all). Over the run, the engine takes the choice that keeps+ every gap from the frame before the run to the frame after it under `BEAT_JOLT`: the fewest+ frames made again, then those nearest their own fractions. Why the run and not each frame: two+ frames side by side each made again nearest its own fraction can each stand within `BEAT_JOLT` of+ its time and still jolt the gap between them past it. For example, one frame made again an eighth+ of a beat late (+0.125) and the next a fifth early (-0.2) jolt the gap between them -0.325, over+ the limit; the first made at another clean fraction instead (-0.175) keeps every gap under it.+ So the gaps are judged with the same definition over the choice, and the whole loop's beat is+ read again after it.+ - 3. A run no such choice keeps has its jolt spread over the frames beside it (`align._widen`,+ widths `align.WIDEN` = 2, then 3, frames on each side). The frames beside it must all stand at+ their own time and not be given way. The run takes, of the same choices (the nearer source frame+ however far off its time, or a fraction made again), the one whose largest jolt is least: inside+ the run, and the jolt from the frame width + 1 away on each side shared evenly over the width+ frames between. Each frame beside the run is moved off its own time by its share (a third and a+ sixth of the run's offset at width 2), to the time nearest its own where the leg path puts that+ place, and made there by RIFE (or taken where that time falls within 0.03 of a source frame). It+ is refused where that least jolt is `BEAT_JOLT` = 0.25 beat or more, a frame beside it would be a+ filmed ghost or is made with a fault, or the loop it leaves still jolts `BEAT_JOLT` or more+ anywhere between the two frames held. Why two or three frames and not one: moving one frame each+ side halves the jolt at best and moves that frame far toward the hard pair, where RIFE often loses+ its outline; two or three share it in smaller steps. For example, a frame whose pair breaks at+ every fraction within `BEAT_JOLT`, the nearer source frame half a beat late: two frames each side+ moved a third and a sixth of a beat late: every gap jolts a sixth of a beat. Recorded as+ `beat.widened`: each `run`, its `width`, and the frames `moved` (`at`, `off` in beats, and the+ source frame or the pair and fraction it now comes from). A moved frame's `smear` row is+ `method: "moved"` with `moved` (its new source or pair and fraction, its off, the new frame's+ measures); it counts in `made_at` when made.+ - 4. A run no choice keeps stays on the nearer source frame and is named: `beat.named` lists it+ (frames of the turned loop). Under `--between auto`, where the loop's beat still has gaps at+ `BEAT_JOLT` or more after the alignment kept what it could, `retake` carries the reason+ `broken-beat` (details `broken_beat`: `jolt`, `gap`, `over`, `named` for the frames that kept+ the nearer source frame, `remedy` "recut-or-retake"; limit `beat_jolt`); under `--between nearest`+ a broken beat is recorded in `beat` but is no reason (that choice takes the nearer frame on+ purpose). Each reason has one warning line, which replaces the earlier separate beat and same-foot+ lines: "<loop>: cut it again or film this direction again (broken-beat): its beat breaks, the legs+ jolt ...", giving the largest jolt, between which frames, every gap over, the frames that took+ the nearer source frame, and the remedy (another cut may land its times on frames RIFE can make;+ a new take may not need them made). The report's `retake` list carries these loops like the others;+ so a loop drawn every frame whose replaced frames break the beat is now named (`broken-beat`),+ where before only held loops and kept filmed ghosts were.+ Report fields: a frame made again has `smear` `method: "retimed"` (beside `rife` kept and+ `nearest` given way), keeps its first frame's measures and `faults` (why it was given way), and+ gains `retimed`: `t` (the fraction it was made at), `from_t` (its own), `off` (how far off its+ time, beats), the new frame's every measure, `faults: []`, `look`. Every frame given way in a loop+ whose beat broke gains `retime`: `between` (its pair of source frames), `tried` (each fraction made+ again, its `off`, its `faults`), `off_nearest` (the nearer source frame's off its time). It counts+ in `made_at` and `made_by_rife`, not `nearest_at` or `replaced`; the report's new `retimed` counts+ such frames over the set. `beat.retimed` lists them per loop. A warning line for it says RIFE's+ frame at its own fraction had these faults, "so the same two source frames were made again at <t>,+ the legs <off> of a beat off its time, where the nearer source frame broke the beat+ (--between auto)".+- **Same foot twice: named, refused when asked** (`--same-foot warn|refuse`): read only where the feet+ stand side by side and the stepping foot is drawn higher: `STEP_VIEWS` = back, back_diagonal (any+ facing). Seen from behind, the picture's left foot is the character's own left. Other views are a+ named gap (`read: false` with `why`): front is not read because the foot stepping toward the viewer+ is drawn lower, so the higher half is not the lifted foot (the same rule the engine's `strike_foot`+ uses), and a front walk whose feet cross one line reads the same half lifting twice when it+ alternates; side and front_diagonal are not read because the feet overlap one in front of the other,+ so a half is not a foot. It is also not read where only one half steps or neither does. Readings+ considered and not used: splitting the feet frame by frame at the middle of each frame's own foot+ band (a tail or a skirt over the band counts as a foot), lift against the loop's lowest row (a body+ that bobs reads its planted foot as lifted), and counting stride or reach peaks (the count is not+ steady from one view to another). The feet split at the middle of the solid columns of the box's+ lowest `FOOT_ROWS` = 0.03 over the loop. For each frame and half, its lift is how far the half's+ lowest solid row ends above the frame's own lowest row, as a fraction of the box's height. A step is+ a run of `LIFT_CELLS` = 2 or more frames (round the ring) lifted `LIFT_MIN` = 0.010 (1 %) or more. Two+ runs of one half are two steps only where its lift comes down to `DOWN_MAX` = 0.006 (0.6 %) or under+ between them (a foot that only dips is one step). Read only where both halves step; the steps in ring+ order by their highest frame; same foot twice where two neighbours on the ring (the last and the+ first among them) are one half. `video-cycle-align` reads it on every aligned loop whose `--view` is+ back or back_diagonal: report row and `cycle_align.same_foot` record `read`, `order` (for example+ "RRL", picture halves L and R), `steps` (each: `half`, `frames`, `peak`, `lift`), `twice` (pairs of+ neighbouring steps of one foot, by their highest frames), and `clip`. `video-loop` reads every cut of+ the cut's length the clip holds (after any lead-in), each as the loop it would make, on the keyed+ frames of every walk or run it cuts, and records it as `clip_feet` in `strip.json` and its report:+ `length`, `cuts`, `same_foot` (how many step the same foot twice), `alternate`, `unread`,+ `seam_in_step`, and `same_foot_at` (the first clip frame of each that does). A cut whose seam falls+ inside a step, one half lifted at both its last and its first frame, is counted apart, neither as+ alternating nor as stepping the same foot twice, and is not in `same_foot_at`; looped, it joins two+ lifts across its seam into one, so where the take lifts one foot twice it hides the second lift in a+ seam that jumps mid-step and reads as alternating; `same_foot`, `alternate` and `unread` count the+ other cuts. Recorded whatever the view; the alignment reads it where its view reads the feet. Under+ the default `--same-foot warn`, the warning says: "<loop>: film this direction again (same-foot):+ steps the same foot twice in a row: its own right foot lifts at frames a and b, no step of the other+ foot between (RRL round the loop ...); the alignment does not change the steps a take shows" (with+ "cut it again (same-foot)" where the remedy is recut, and "cut it again or film this direction+ again (same-foot)" where it is recut-or-retake) and then, from `clip`: every cut of its clip N frames+ long that reads steps so (S of C; J more with their seam inside a step, which hides the second lift+ in the seam): the take steps that foot twice every cycle, so cutting it again does not help, film this+ direction again (the part after the semicolon only when J is not 0); or: m of n cuts alternate, a cut+ elsewhere in the clip may alternate; or: the clip's cuts were not read (cut before video-loop recorded+ clip_feet), so whether another cut alternates is not known. Under `--same-foot refuse`, such a loop+ stops the set before anything is rewritten; the message names each+ loop as above plus "Stopped before anything was rewritten (--same-foot refuse)", and the report is+ written with `applied: false`, `refused: "same-foot"`, and `same_foot` (each loop's dir, name and+ reading). The default does not refuse because the app does not know this refusal yet and will turn it+ on with its retake rule. The report's `same_foot` key names the mode.+- **A take that jumps: named** (`cadence.screen_steps`, `cadence.screen_record`): for each step of the+ cut's own frames (`cycle.source/`, step `i` from frame `i` to `i + 1`, the last step from the last+ frame to the first, which is the cut's seam), `cadence.screen_steps(frames)` reads the mean absolute+ luminance difference over white (0 to 255) of the box every frame's figure fits in (`whole`) and of its+ lowest `cadence.SCREEN_ROWS` = 0.30 (`legs`; a strip cell's lowest 125 of its 406 px), read at+ `READ_HEIGHT` 410 px. Why: the beat reads only the leg path where the feet go (the lowest 10 % of the+ box); two drawings filmed a pose apart (legs wide apart in one, crossed in the next, the tail up) move+ the feet little and change the picture much, so the beat passes them, while the screen sees them. Jump+ rule (`cadence.screen_record`): a step is a jump when, over the box or on its leg rows, it is at least+ `cadence.SCREEN_JUMP` = 2.0 times the cycle's typical step and at least `cadence.SCREEN_ALONE` = 1.3+ times every other step of the cycle. The typical step is the upper quartile of the cycle's steps: on+ ones every step is a drawing change, on twos or threes most steps change nothing and the upper quartile+ is a drawing change. A cycle whose drawing changes are all alike names none; so does a cycle with two+ steps alike however large (neither is 1.3 times the other). Read where: on the cut's own frames, not on+ the aligned frames: an aligned frame spans two or three of the cut's frames, which spreads a jump over+ the drawing changes beside it and hides it. Read on every aligned loop, whatever its view and whatever+ `--between`. Record: each loop row and `strip.json` `cycle_align` gain `screen`: `whole` and `legs`+ (every step), `typical` (per region), `jumps` (each: `step` [i, i + 1] as frames of `cycle.source/`,+ `seam` true for the last step, `whole` and `legs` each [change, times the typical step, times the next+ largest step], `at` the gaps [k, k + 1] of the aligned (turned) loop that show it), and `limits`+ (`jump`, `alone`, `rows`). Reasons in `retake`: a jump inside the cut gives the reason `filmed-jump`+ (details `filmed_jump`: `steps`, `at`, `whole`, `legs`, `remedy` "recut-or-retake"): the take jumps+ between two poses there, and the alignment does not change the poses a take shows; where the clip films+ another cycle without the jump, a cut of the same clip from there removes it, and where it does not, a+ new take does. A jump at the seam gives `seam-jump` (details `seam_jump`, same keys, `remedy`+ "recut-or-retake"): another cut of the clip may close on a pose it holds; a new take may not need the+ cut to close there. Limits `screen_jump`, `screen_alone`, `screen_rows`. Order of reasons now:+ `held-drawings`, `filmed-ghost`, `filmed-jump`, `seam-jump`, `broken-beat`, `same-foot`. Warning lines:+ "<loop>: cut it again or film this direction again (filmed-jump): the take jumps between two of its+ frames, from frame 30 to 31 of cycle.source/ the picture changes 22 of 255 over the figure's box and 36+ on its legs, 2.10 and 2.50 times the cut's typical step and 1.50 and 1.80 times any other step (the+ loop's frames 13 to 14); the alignment does not change the poses a take shows. Where the clip films+ another cycle without the jump, a cut there fixes it; where it does not, a new take does". Seam:+ "<loop>: cut it again or film this direction again (seam-jump): the cut's seam jumps, from frame ... ;+ another cut of the clip may close on a pose it holds, a new take may not need the cut to close there".+ Python callers: `cadence.screen_steps`, `cadence.screen_record`, `cadence.SCREEN_ROWS` (0.30),+ `cadence.SCREEN_JUMP` (2.0), `cadence.SCREEN_ALONE` (1.3), `align.RETAKE_JUMP_REASON` ("filmed-jump"),+ `align.RETAKE_SEAM_REASON` ("seam-jump"), `align.retake(..., beat=None, feet=None, screen=None)`.- **Smear and melt, per made frame**: `cycle_align.smear` lists every frame RIFE made, with its`method` — `rife` (kept) or `nearest` (a source frame beside it taken instead) — its `faults`, itsown ghost reading (`ghost`, below; `null` where the screen does not read the loop), its cross-fade@@ -1534,10 +1720,40 @@ sprite-gen video-cycle-align --loop-dir set/front-walk/loop --loop-dir set/side-Taken at its own time it was delivered as filmed, never measured; a frame RIFE made beside itcarried the band, and measured against that neighbour it added nothing. So every frame thealignment delivers is read on its own coverage, not against its neighbours:- - `ghost`: part-covered pixels (alpha 0.1–0.9) inside regions at least **5 px** thick+ - `ghost`: part-covered pixels (alpha 0.1 to 0.9) inside regions at least **5 px** thick(`rife.GHOST_THICK`; an antialiased edge or a keyed strand of hair is a pixel or two wide anderodes away), as a fraction of the frame's solid pixels. Over **0.3 %**(`interpolation_quality.GHOST_WARN`) the frame is a ghost: on a made frame the fault `ghost`.+ - `ghost_window`: a made frame's ghost band is now also read in windows of the body (new+ `rife.ghost_window`, constant `rife.GHOST_BAND` = 0.10): the same part-covered pixels in regions+ at least `rife.GHOST_THICK` (5 px) thick that `rife.ghost` counts, but counted in windows a tenth+ of the body high, sliding a quarter window at a time down the body, each as a share of the solid+ pixels in that window; the reading is the largest window's share, and where that window lies as+ fractions of the body from its top. Over **1.4 %**+ (`interpolation_quality.GHOST_WINDOW_WARN` = 0.014, 1.4 % of a window's solid pixels) the made frame+ has the fault `ghost`, the same fault name as the whole-body reading, though its whole-body+ `ghost` stays under 0.3 %. Why: where one source frame has a gap beside a limb and the other has the limb+ there, RIFE can blend the two coverages, leaving the limb part-covered over the gap so the+ background shows through it (a "limb seen through", which reads as a hole in the leg at a strip's+ size); over the whole figure that band is a small share and passes the 0.3 % limit, and the hole+ reading excuses it as the first source frame's own gap; in the rows it lies in it is a large share.+ A faint band can read just under 1.4 %, so a frame near it is worth a look. It is read only on the+ frames the cycle alignment makes (the measure carries it), not on `video-loop`'s jump repair frames+ and not by the ghost screen of filmed frames. Each `smear` row (and a frame made again, under `retimed`)+ records `ghost_window` and `ghost_window_at` ([from, to] fractions of the body); both are `null` where+ the ghost screen does not read the loop. A frame judged a ghost by its window has a warning line saying+ "carries a part-covered band over 2.40 % of the solid pixels in a band 10 % of its body high (60 to 70 %+ down it), at least 5 px thick, though 0.18 % of its whole body, a limb seen through, a ghost" (an example+ in this form), and gives way, or is made again at another fraction, like any faulty made frame.+ Python callers: new `align.measure_made(frame, a, b, t, reads=...)` returns every measure a made+ frame is judged by. A frame made only to keep the beat (a fraction made again, or a frame moved+ for a spread) is taken only where its window reading is under `align.RETIME_WINDOW_MAX` = 0.006,+ well under the fault's 1.4 %, besides having no fault. Why: such a frame is optional, the nearer+ source frame (with the broken-beat reason and its warning line) is always there instead, and a frame+ seen through is worse than a beat that jolts; a fraction next to one refused for a limb seen through+ often carries the same patch with more of it wholly clear (alpha under 0.1, so not part-covered),+ which reads under 1.4 % and is seen all the same. Each fraction tried records `ghost_window`, and+ `window_over` (the bar) where it had no fault but read over the bar.- The screen reads the loop as filmed (`cycle.source/`): `ghost_screen` per loop row and in`cycle_align` — `limit`, `thick_px`, the loop's own `level` (its median frame's reading), `reads`,and `ghosts` (each `frame` of `cycle.source/` over the limit, with its reading). A loop whose@@ -2062,8 +2278,19 @@ sprite-gen video-cycle-align --loop-dir set/front-walk/loop --loop-dir set/side-line, kept.- **What `auto` costs**: a frame replaced shows the nearer source frame, so the motion theresteps as filmed, up to half a frame off its time, and the loop shows fewer distinct drawings a- second than `rife` — but no melted one. A clip drawn on twos has a long step between drawings- everywhere, so it is replaced most; the frames that land on a small step stay RIFE's.+ second than `rife` (but no melted one). A clip drawn on twos has a long step between drawings+ everywhere, so it is replaced most; the frames that land on a small step stay RIFE's. The legs are+ read for the beat only where a frame stands off its own time, costing nothing when every frame+ stands on time. For each frame given way in a loop whose beat broke, the engine tries every other+ fraction of `align.RETIME_T` (0.15 to 0.85 in steps of 0.05, fifteen fractions; the frame's own is+ not made again) whose place stands within `BEAT_JOLT` = 0.25 beat of the frame's own time, nearest+ its own fraction first, and makes each of those with RIFE. How many that is depends on how far the+ legs move between the two source frames against one beat: about ten where the pair's step is about+ one beat long, all fourteen others where it is much shorter than a beat. Fractions standing further+ off are not made. Where a spread is taken, frames beside a run are moved off their own times and+ made by RIFE. `--between-cache` keeps and reuses them like any made frame. The result: where the+ beat breaks, the alignment runs RIFE several times over for each frame given way, and takes longer;+ elsewhere it costs nothing more.- **Held drawings — a take to film again** (`retake`, reason `held-drawings`): a loop whoseclip shows each drawing for two or three frames has a gap between drawings two or three frameswide. Played at its own rate that is limited animation, 12 or 8 drawings a second. Made longer,@@ -2112,16 +2339,36 @@ sprite-gen video-cycle-align --loop-dir set/front-walk/loop --loop-dir set/side-`limit`, with `limits.ghost_kept_min`. Its line: "film this direction again (filmed-ghost) —frame(s) 5 show source frame(s) 10 of cycle.source/, filmed ghosts (…), and the source framesbeside each are filmed ghosts too …".- - **One record per loop**: `retake` is one object (or `null`). `reason` is the first reason- that applies, `held-drawings` before `filmed-ghost`, and `reasons` lists every one; the held- numbers (`hold`, `drawings`, …, `unmade`) stand only where `held-drawings` applies, `ghost`- only where `filmed-ghost` does, and `limits` carries each one's. A held loop that also keeps a- ghost reads `reason: "held-drawings"`, `reasons: ["held-drawings", "filmed-ghost"]`, with a- line for each — one new take fixes both.- - **Not named**: a held loop at its own length (nothing is made — on twos it plays at 12 a+ - **One record per loop**: `retake` is one object (or `null`). `reason` is the first reason that+ applies (order of reasons: `held-drawings`, `filmed-ghost`, `filmed-jump`, `seam-jump`,+ `broken-beat`, `same-foot`), and `reasons` lists every one; the held-drawings numbers (`hold`,+ `source`, `drawings`, `drawings_per_second_filmed`, `drawings_per_second`, `frames_per_drawing`,+ `unmade`) stand at the top level of the `retake` record, as before (only where `held-drawings`+ applies), details stand under each reason's snake_case key (`ghost` only where `filmed-ghost` does;+ `filmed_jump` with `steps`, `at`, `whole`, `legs`, `remedy`; `seam_jump` with `steps`, `at`, `whole`,+ `legs`, `remedy`; `broken_beat` with `jolt`, `gap`, `over`, `named`, `remedy`; `same_foot` with+ `order`, `twice`, `clip`, `remedy`), and `limits` carries each one's (`screen_jump`, `screen_alone`,+ `screen_rows` for `filmed-jump` and `seam-jump`; `beat_jolt` for `broken-beat`; `lift_min`,+ `lift_cells`, `down_max` for `same-foot`). `remedy` says what is likely to fix it: "retake" (film the+ direction again) where every cut of the clip that reads steps the same foot twice; "recut" (cut the+ loop again from the same clip) where some cut alternates; "recut-or-retake" for `seam-jump` (another+ cut of the clip may close on a pose it holds; a new take may not need the cut to close there), for+ `filmed-jump` (where the clip films another cycle without the jump, a cut of the same clip from there+ removes it; where it does not, a new take does), for a broken beat (another cut may land its times on+ frames RIFE can make; a new take may not need them made) and for the same foot where the clip's cuts+ were not read. Under `--between nearest` a broken beat is recorded in `beat` but is no reason (that+ choice takes the nearer frame on purpose). Each reason has one warning line, which replaces the+ earlier separate beat and same-foot lines, and the report's `retake` list carries these loops like+ the others. A held loop that also keeps a ghost reads `reason: "held-drawings"` with `filmed-ghost`+ among its `reasons`, with a line for each reason, one new take fixing both. Python callers:+ `align.retake(..., beat=None, feet=None, screen=None)`, `align.RETAKE_JUMP_REASON`,+ `align.RETAKE_SEAM_REASON`, `align.RETAKE_BEAT_REASON`, `align.RETAKE_FEET_REASON`, `align.REMEDIES`.+ - **Not named**: a held loop at its own length (nothing is made: on twos it plays at 12 asecond, as filmed), a held loop whose made frames all kept their outline, a held loop squeezed- to 13 drawings a second or more (its drawings come closer than on twos), and a loop drawn every- frame with a replaced frame (one soft step, not a gap the take cannot fill).+ to 13 drawings a second or more (its drawings come closer than on twos), a loop drawn every+ frame with a replaced frame whose beat does not break (one soft step, not a gap the take cannot+ fill; if replaced frames break the beat under `--between auto`, it is now named `broken-beat`),+ and under `--between nearest` a broken beat (recorded in `beat`, but no reason).- **Exit code and words** (both reasons): the set is still aligned and written (`applied: true`, exit 0) — theloop is the best this take allows, and the caller decides: a pipeline with a retake budgetfilms that direction again and aligns the set anew; one without delivers it with the warning.@@ -2207,12 +2454,13 @@ sprite-gen video-cycle-align --loop-dir set/front-walk/loop --loop-dir set/side-the strikes are read from `cycle.source/` resampled again — so it holds for every later alignmentat the same length, and like `--cycles` it is not remembered: the next alignment needs the same`--foot`. The algorithm that names feet is not changed by it.-- **Rebuilt in place**: `cycle/`, `<name>.strip.png` / `.strip.json`, `.gif`, `.webp` are- rewritten at the loop's own cell rules (`cell_height_cap`, body-height target, anchor), at the- loop's frame rate, so the aligned cycle lasts L*/fps seconds. `strip.json` gains- `cycle_align` (`from`, `to`, `between`, `taken`, `made_by_rife`, `made_at`, `smear` and/or- `nearest_at`, `ghost_screen`, `ghost_at`, `drawings`, `retake`, `turned_by`, `turned_on`, `view`, `start_foot`, `start_foot_source`, `strikes`, the seam ratio of the rebuilt- cells, `cells_from`, `origin`, and the re-verified GIF/WebP).+- **Rebuilt in place**: `cycle/`, `<name>.strip.png` / `.strip.json`, `.gif`, `.webp` are rewritten at the+ loop's own cell rules (`cell_height_cap`, body-height target, anchor), at the loop's frame rate, so the+ aligned cycle lasts L*/fps seconds. `strip.json` gains `cycle_align` (`from`, `to`, `between`, `taken`,+ `made_by_rife`, `made_at`, `smear` and/or `nearest_at`, `ghost_screen`, `ghost_at`, `drawings`, `beat`,+ `same_foot` (back and back_diagonal views), `screen`, `retake`, `turned_by`, `turned_on`, `view`,+ `start_foot`, `start_foot_source`, `strikes`, the seam ratio of the rebuilt cells, `cells_from`, `origin`,+ and the re-verified GIF/WebP).- **Where every cell is from**: `cycle_align.cells_from` holds, per cell of the rebuilt strip,`{"source": i}` — frame i of `cycle.source/`, taken as filmed (a turn, a snap, or the nearerframe), as many times as it is taken — or `{"between": [i, j], "t": t}`, a frame made betweendiff --git a/docs/video-pipeline.md b/docs/video-pipeline.mdindex 6df3e6c..6d66b65 100644--- a/docs/video-pipeline.md+++ b/docs/video-pipeline.md@@ -156,6 +156,15 @@ on its larger strike and is listed under the report's `unnamed_feet` with its tw`cycle/`: look at the first, say which own foot lands there, and run the same alignment again with`--foot <loop>=left|right` — that loop alone turns to start on the set's foot(`start_foot_source: "given"`).+Every aligned loop's report row (and its `strip.json`, under `cycle_align`) records its beat+(`beat`): how far the frames the alignment moved off their own time jolt the legs, in beats; under+`--between auto` a frame RIFE could not make cleanly is made again at another fraction of its two+source frames, or its jolt is shared by the frames beside it, where the nearer source frame would+break the beat; where nothing keeps it, the loop is named in the warnings. A loop whose `--view` is+`back` or `back_diagonal` is also read for stepping the same foot twice in a row (`same_foot`),+named in the warnings with whether any other cut of its clip would alternate; `--same-foot refuse`+stops the set before anything is rewritten instead (both are explained in+[loop repair](loop-repair.md) section 4).`video-prompt --json` also gives the duration (the state's own, as `video-set`), whether the clipends on the canvas (`last_frame`), the loop cut (`cycle`) and the canvas, clip, frames and loop@@ -384,6 +393,14 @@ inside a 24 fps clip, each drawing shown for two frames ("on twos", or three: "olimited animation. It matters when `video-cycle-align` stretches it ([loop repair](loop-repair.md)section 4, "Held drawings").+**Every cut's feet: recorded on every walk.** `video-loop` reads every cut of the cut's length the+clip holds (after any lead-in), each as the loop it would make, on the keyed frames of every walk or+run it cuts, and records it as `clip_feet` in `strip.json` and its report: `length`, `cuts`,+`same_foot` (how many step the same foot twice), `alternate`, `unread`, `seam_in_step` (cuts whose+seam falls inside a step, counted apart), and `same_foot_at` (the first clip frame of each that+does). This is recorded whatever the view; `video-cycle-align` reads it only where the view reads+the feet (back and back_diagonal; [loop repair](loop-repair.md) section 4, "Same foot twice").+### One-shot actions — `--cycle auto|periodic|one-shot`A video model asked to jump "over and over" sometimes jumps once and stands for thediff --git a/sprite_gen/video/align.py b/sprite_gen/video/align.pyindex 1a139fa..1c085bf 100644--- a/sprite_gen/video/align.py+++ b/sprite_gen/video/align.py@@ -100,12 +100,13 @@ from sprite_gen.gen import handedness as handed_modfrom sprite_gen.spec.runio import atomic_write_textfrom sprite_gen.util.gif_utils import save_clean_giffrom sprite_gen.video import sway as sway_mod+from sprite_gen.video import cadence as cadence_modfrom sprite_gen.video import held as held_modfrom sprite_gen.video import legs as legs_modfrom sprite_gen.video import loop as loop_modfrom sprite_gen.video import period as period_modfrom sprite_gen.video import rife as rife_mod-from sprite_gen.video.interpolation_quality import CROSSFADE_LOOK, SMEAR_WARN, OUTLINE_WARN, clean_beside, faults, ghost_screen, looks+from sprite_gen.video.interpolation_quality import CROSSFADE_LOOK, GHOST_WARN, SMEAR_WARN, OUTLINE_WARN, clean_beside, faults, ghost_screen, looksfrom sprite_gen.util.console import utf8_streamsSNAP = 0.03 # a sample time within this of a source frame takes that frame@@ -131,6 +132,23 @@ LOW_MARGIN = "low-margin" # how `foot_why` starts where the two strikes differCUE_RHYTHM = 0.25BETWEEN = ("auto", "rife", "nearest") # how a time between two source frames is filled (resample)DEFAULT_BETWEEN = "auto"+# Where a made frame gives way and the nearer source frame breaks the loop's beat (`_keep_the_beat`), the same pair is+# made again at these fractions, nearest its own first: a frame RIFE cannot make half way between two drawings is+# often clean nearer one of them (docs/loop-repair.md section 4).+RETIME_T = tuple(round(0.15 + 0.05 * j, 2) for j in range(15))+# A frame made only to keep the beat (made again at another fraction, or moved for a spread) is optional: the nearer+# source frame, and a line naming the broken beat, is always there instead, and a frame seen through is worse than a beat+# that jolts. So it is taken only where its ghost band reads under this in every window of its body (`rife.ghost_window`),+# a bar for frames seen as clean, well under the fault's (interpolation_quality.GHOST_WINDOW_WARN): a fraction near the+# one refused for a limb seen through often carries the same patch with more of it wholly clear, which reads under the+# fault's limit and is seen all the same (docs/loop-repair.md section 4).+RETIME_WINDOW_MAX = 0.006+# A run of frames given way that no choice of fractions keeps on the beat spreads its jolt over this many frames beside it+# on each side, moved off their own time by an even share of it and made there (`_widen`), the fewest first.+WIDEN = (2, 3)+# A loop that steps the same foot twice (`cadence.same_foot`): warn (default) names it in the report and the warnings,+# refuse stops the set before anything is rewritten.+SAME_FOOT = ("warn", "refuse")# A set with a loop the two-cycle screen suspects and no --cycles for it: fail (default) stops the# set before anything is rewritten, warn aligns it as it is and names the loop in the warnings.MULTI_CYCLE = ("fail", "warn")@@ -153,6 +171,20 @@ RETAKE_REASON = "held-drawings"RETAKE_GHOST_KEPT_MIN = 1RETAKE_GHOST_REASON = "filmed-ghost"KEPT_NO_CLEAN, KEPT_RIFE = "no-clean-frame", "between-rife"+# A loop aligned under auto whose beat still breaks — a run of frames given way that no fraction made again and no spread+# kept on the beat (`beat` over) — is named for whoever cuts or films it again, the reason `broken-beat`; a loop that steps+# the same foot twice (`same_foot` twice), the reason `same-foot`. Each reason's record says what is likely to fix it+# (`remedy`): `retake` where every cut of the clip reads the same (a new take), `recut` where some cut of the clip+# alternates, `recut-or-retake` where the cuts were not read or the beat breaks (another cut may land its times on frames+# RIFE can make; a new take may not need them made).+RETAKE_BEAT_REASON, RETAKE_FEET_REASON = "broken-beat", "same-foot"+# A cut whose own frames jump (`screen`, cadence.screen_record: one step changes the picture far more than its drawing+# changes do): between two frames inside the cut, the reason `filmed-jump` — the take jumps from one pose to another+# there, and neither another fraction nor another place on the beat removes it, but a cut of the same clip from a cycle+# it films without the jump does; at the cut's seam, its last frame to its first, the reason `seam-jump` — another cut+# of the clip may close on a pose it holds. Both `recut-or-retake`.+RETAKE_JUMP_REASON, RETAKE_SEAM_REASON = "filmed-jump", "seam-jump"+REMEDIES = ("retake", "recut", "recut-or-retake")def held_drawings(frames: list[Image.Image], *, fps: float, clip: dict[str, Any] | None = None,@@ -181,7 +213,9 @@ def held_drawings(frames: list[Image.Image], *, fps: float, clip: dict[str, Any]return {"source": "cycle", **held_mod.measure([float(D[k, (k + 1) % n]) for k in range(n)], fps=fps, cyclic=True)}-def retake(drawings: dict[str, Any], facts: dict[str, Any], ghost_at: list[dict[str, Any]], *, fps: float) -> dict[str, Any] | None:+def retake(drawings: dict[str, Any], facts: dict[str, Any], ghost_at: list[dict[str, Any]], *, fps: float,+ beat: dict[str, Any] | None = None, feet: dict[str, Any] | None = None,+ screen: dict[str, Any] | None = None) -> dict[str, Any] | None:"""The reasons to film a loop again, with their numbers, in one record, or None. `drawings` is thesource's `held_drawings`, `facts` its `resample` facts, `ghost_at` its cells where a filmed ghostgave way or was kept, as the loop's row records them (each cell where it now stands).@@ -192,6 +226,12 @@ def retake(drawings: dict[str, Any], facts: dict[str, Any], ghost_at: list[dict[only where it applies. `filmed-ghost`: RETAKE_GHOST_KEPT_MIN or more cells where the ghost itselfwas kept, neither frame beside its time clean (`kept` no-clean-frame) — `ghost` names them (`kept`),their frames of the source (`sources`), the highest reading (`ghost_max`) and the screen's `limit`.+ `filmed-jump` and `seam-jump` (`screen`, the loop's screen record): `filmed_jump` and `seam_jump` name each jump's+ step (frames of the source), the gaps of the loop that show it (`at`), its change and ratios per region, and the+ `remedy`. `broken-beat` (`beat`, the loop's turned beat record, under `--between auto`): gaps still at BEAT_JOLT or more —+ `broken_beat` names the largest jolt and its gap, every gap over, the frames that kept the nearer source frame+ (`named`) and the `remedy`. `same-foot` (`feet`, the loop's `same_foot` with its clip's cuts): `same_foot` names the+ steps' order, the pairs of one foot, the clip's counts and the `remedy`.`reason` is the first that applies, in that order, `reasons` all of them, `limits` each one's."""reasons: list[str] = []record: dict[str, Any] = {}@@ -211,13 +251,55 @@ def retake(drawings: dict[str, Any], facts: dict[str, Any], ghost_at: list[dict[record["ghost"] = {"kept": [g["at"] for g in kept], "sources": sorted({g["source"] for g in kept}),"ghost_max": max(g["ghost"] for g in kept), "limit": facts["ghost_screen"]["limit"]}limits["ghost_kept_min"] = RETAKE_GHOST_KEPT_MIN+ for reason, key, seam, remedy in ((RETAKE_JUMP_REASON, "filmed_jump", False, "recut-or-retake"),+ (RETAKE_SEAM_REASON, "seam_jump", True, "recut-or-retake")):+ jumps = [j for j in (screen or {}).get("jumps", []) if j["seam"] is seam]+ if jumps:+ reasons.append(reason)+ record[key] = {"steps": [j["step"] for j in jumps], "at": [j["at"] for j in jumps],+ "whole": [j["whole"] for j in jumps], "legs": [j["legs"] for j in jumps], "remedy": remedy}+ limits |= {"screen_jump": cadence_mod.SCREEN_JUMP, "screen_alone": cadence_mod.SCREEN_ALONE, "screen_rows": cadence_mod.SCREEN_ROWS}+ if beat and facts.get("between") == "auto" and beat.get("path") == "read" and beat.get("over"):+ reasons.append(RETAKE_BEAT_REASON)+ record["broken_beat"] = {"jolt": beat["jolt"], "gap": beat["gap"], "over": beat["over"],+ "named": sorted(k for run in beat.get("named", []) for k in run), "remedy": "recut-or-retake"}+ limits["beat_jolt"] = cadence_mod.BEAT_JOLT+ if feet and feet.get("read") and feet.get("twice"):+ clip = feet.get("clip") or {}+ remedy = ("retake" if clip.get("cuts") and clip.get("same_foot") and not clip.get("alternate")+ else "recut" if clip.get("alternate") else "recut-or-retake")+ reasons.append(RETAKE_FEET_REASON)+ record["same_foot"] = {"order": feet["order"], "twice": feet["twice"],+ "clip": ({k: clip[k] for k in ("length", "cuts", "same_foot", "alternate", "unread", "seam_in_step") if k in clip}+ if clip.get("cuts") else None), "remedy": remedy}+ limits |= {"lift_min": cadence_mod.LIFT_MIN, "lift_cells": cadence_mod.LIFT_CELLS, "down_max": cadence_mod.DOWN_MAX}if not reasons:return Nonereturn {"reason": reasons[0], "reasons": reasons, **record, "limits": limits}-def _retake_line(name: str, r: dict[str, Any], reason: str) -> str:- """A loop to film again for `reason` (one of its `reasons`), in words."""+def _retake_line(name: str, r: dict[str, Any], reason: str, row: dict[str, Any] | None = None) -> str:+ """A loop to film again for `reason` (one of its `reasons`), in words; `row` is its report row (the beat and the feet+ as read)."""+ if reason in (RETAKE_JUMP_REASON, RETAKE_SEAM_REASON):+ j = r["filmed_jump" if reason == RETAKE_JUMP_REASON else "seam_jump"]+ steps = "; ".join(+ f"from frame {a} to {b} of {SOURCE_DIR}/ the picture changes {w[0]:g} of 255 over the figure's box and {g[0]:g} on its legs, "+ f"{w[1]:.2f} and {g[1]:.2f} times the cut's typical step and {w[2]:.2f} and {g[2]:.2f} times any other step "+ f"(the loop's frames {', '.join(f'{k} to {k1}' for k, k1 in at)})"+ for (a, b), w, g, at in zip(j["steps"], j["whole"], j["legs"], j["at"]))+ if reason == RETAKE_JUMP_REASON:+ return (f"{name}: cut it again or film this direction again ({reason}): the take jumps between two of its frames — "+ f"{steps}; the alignment does not change the poses a take shows. Where the clip films another cycle without "+ "the jump, a cut there fixes it; where it does not, a new take does (docs/loop-repair.md section 4)")+ return (f"{name}: cut it again or film this direction again ({reason}): the cut's seam jumps — {steps}; another cut of "+ "the clip may close on a pose it holds, a new take may not need the cut to close there (docs/loop-repair.md section 4)")+ if reason == RETAKE_BEAT_REASON:+ return f"{name}: cut it again or film this direction again ({reason}): " + _beat_line(name, row)[len(name) + 2:] # type: ignore[arg-type]+ if reason == RETAKE_FEET_REASON:+ say = {"retake": "film this direction again", "recut": "cut it again",+ "recut-or-retake": "cut it again or film this direction again"}[r["same_foot"]["remedy"]]+ return f"{name}: {say} ({reason}): " + _same_foot_line(name, row)[len(name) + 2:] # type: ignore[arg-type]if reason == RETAKE_GHOST_REASON:g = r["ghost"]cells, sources = ", ".join(map(str, g["kept"])), ", ".join(map(str, g["sources"]))@@ -232,6 +314,18 @@ def _retake_line(name: str, r: dict[str, Any], reason: str) -> str:"fixes it; no interpolator draws legs that swap places across a gap this wide (docs/loop-repair.md section 4)")+def measure_made(frame: Image.Image, a: Image.Image, b: Image.Image, t: float, *, reads: bool) -> dict[str, Any]:+ """Everything a frame made between `a` and `b` at `t` is judged by (`faults`): what it added and the outline it lost+ (`rife.smear`, `rife.outline_shift`), its ghost band over the whole body and in windows of it (`rife.ghost`,+ `rife.ghost_window` with where that window lies, `ghost_window_at`; None where the ghost screen does not read the loop,+ `reads`), its cross-fade (`rife.crossfade`, named, not judged), its holes (`rife.hole`) and double outline+ (`rife.doubled`)."""+ window, at = rife_mod.ghost_window(frame) if reads else (None, None)+ return {**rife_mod.smear(frame, a, b), "outline_shift": rife_mod.outline_shift(frame, a, b),+ "ghost": rife_mod.ghost(frame) if reads else None, "ghost_window": window, "ghost_window_at": list(at) if at else None,+ "crossfade": rife_mod.crossfade(frame, a, b, t), "hole": rife_mod.hole(frame, a, b, t), "doubled": rife_mod.doubled(frame, a, b)}++def resample(frames: list[Image.Image], length: int, interpolate: rife_mod.Interpolate | None,*, between: str = DEFAULT_BETWEEN, cells_from: list[dict[str, Any]] | None = None) -> tuple[list[Image.Image], dict[str, Any]]:"""`frames` as one cycle, resampled to `length` frames at times k·L/length (offset 0). Where `cells_from` is a@@ -255,7 +349,11 @@ def resample(frames: list[Image.Image], length: int, interpolate: rife_mod.Interor the one before it; where it is the nearer frame, the other beside the time is — and rife keeps it.Each such cell is listed in `ghost_at`: `at`, the ghost `source` and its reading, and the frame`taken` — the ghost itself where rife kept it beside a clean frame (`kept` between-rife), or where- neither frame beside it is clean (`kept` no-clean-frame, under any `between`)."""+ neither frame beside it is clean (`kept` no-clean-frame, under any `between`).++ The loop's beat is read on the legs (`beat`, `_keep_the_beat`: how far each frame standing off its own time jolts+ the legs into it and out of it); under auto, where the nearer source frames taken break it, a frame given way is+ made again at another fraction of its pair where that keeps it (`smear` method retimed)."""count = len(frames)if length < 2:raise ValueError(f"cycle length {length} is too short")@@ -268,6 +366,13 @@ def resample(frames: list[Image.Image], length: int, interpolate: rife_mod.Internearest_at: list[int] = []smears: list[dict[str, Any]] = []ghost_at: list[dict[str, Any]] = []+ provenance: list[dict[str, Any]] = []+ gave_way: list[dict[str, Any]] = [] # under auto, each made frame given way to a source frame, for the beat++ def made(a: Image.Image, b: Image.Image, t: float) -> tuple[Image.Image, dict[str, Any], list[str]]:+ frame = interpolate(a, b, t) # type: ignore[misc]+ measure = measure_made(frame, a, b, t, reads=screen["reads"])+ return frame, measure, faults(measure)def clean(k: int, first: int, other: int | None) -> int:"""`first` where the screen passes it, else `other`, the clean frame beside it, where there is one@@ -295,22 +400,41 @@ def resample(frames: list[Image.Image], length: int, interpolate: rife_mod.Interif interpolate is None:raise ValueError(f"frame {k} of {length} falls between source frames and no interpolator is available")a, b = frames[i % count], frames[(i + 1) % count]- made = interpolate(a, b, frac)- measure = {**rife_mod.smear(made, a, b), "outline_shift": rife_mod.outline_shift(made, a, b),- "ghost": rife_mod.ghost(made) if screen["reads"] else None,- "crossfade": rife_mod.crossfade(made, a, b, frac), "hole": rife_mod.hole(made, a, b, frac),- "doubled": rife_mod.doubled(made, a, b)}- wrong = faults(measure)+ frame, measure, wrong = made(a, b, frac)keep = between == "rife" or not wrongtaken = ({"between": [i % count, (i + 1) % count], "t": round(frac, 4)} if keepelse {"source": clean(k, nearer, None if beside in ghosts else beside)})(made_at if keep else nearest_at).append(k)smears.append({"at": k, "method": "rife" if keep else "nearest", **measure, "faults": wrong, "look": looks(measure)})- out.append(made if "between" in taken else frames[taken["source"]])- if cells_from is not None:- cells_from.append(taken)+ if not keep:+ gave_way.append({"at": k, "pair": (i % count, (i + 1) % count), "t": frac, "smear": smears[-1]})+ out.append(frame if "between" in taken else frames[taken["source"]])+ provenance.append(taken)+ beat = _keep_the_beat(frames, out, provenance, gave_way, made, between=between, ghosts=ghosts)+ for g in beat.pop("retimed_at"):+ nearest_at.remove(g)+ made_at.append(g)+ ghost_at[:] = [entry for entry in ghost_at if entry["at"] != g]+ for m in (m for spread in beat.get("widened", []) for m in spread.pop("frames")):+ # a frame beside a run, moved off its own time to share the run's jolt: made there, or the source frame taken+ k = m["at"]+ entry = next((e for e in smears if e["at"] == k), None)+ if "between" in m["cell"] and k not in made_at:+ made_at.append(k)+ elif "source" in m["cell"] and k in made_at:+ made_at.remove(k)+ moved = {**m["cell"], "off": m["off"], **({"measure": m["measure"]} if "measure" in m else {})}+ if entry is not None:+ entry["method"], entry["moved"] = "moved", moved+ elif "measure" in m:+ smears.append({"at": k, "method": "moved", **m["measure"], "faults": [], "look": looks(m["measure"]), "moved": moved})+ smears.sort(key=lambda e: e["at"])+ made_at.sort()+ if cells_from is not None:+ cells_from.extend(provenance)facts: dict[str, Any] = {"from": count, "to": length, "between": between, "taken": length - len(made_at),- "made_by_rife": len(made_at), "made_at": made_at, "ghost_screen": screen, "ghost_at": ghost_at}+ "made_by_rife": len(made_at), "made_at": made_at, "ghost_screen": screen, "ghost_at": ghost_at,+ "beat": beat}if between != "rife":facts["nearest_at"] = nearest_atif between != "nearest":@@ -318,6 +442,225 @@ def resample(frames: list[Image.Image], length: int, interpolate: rife_mod.Interreturn out, facts+def _at_its_time(cell: dict[str, Any], k: int, count: int, length: int) -> bool:+ """Whether frame k of a loop of `length` resampled from `count` frames stands at its own time, k·count/length, as+ `cells_from` records it (a fraction to four decimals)."""+ time = k * count / length+ return (abs(cell["between"][0] + cell["t"] - time) < 1e-3) if "between" in cell else abs(cell["source"] - time) < 1e-9+++def _showing(step: int, cells: list[dict[str, Any]], count: int) -> list[int]:+ """The gaps k to k + 1 of a loop (`cells_from` of a cycle of `count` frames, before it is turned) that show the cut's+ step from frame `step` to the next: those whose time runs over some of it, the forward way round."""+ times = [c["source"] if "source" in c else c["between"][0] + c["t"] for c in cells]+ L = len(times)+ shown = []+ for k in range(L):+ span = (times[(k + 1) % L] - times[k]) % count+ into = (step - times[k]) % count+ if span > 0 and (into < span or into + 1 > count):+ shown.append(k)+ return shown+++def _runs(cells: list[int], length: int) -> list[list[int]]:+ """`cells` (frames of a loop of `length`, in order) as runs of neighbours, a run across the last frame and the first+ one run; the whole ring one run that starts at its first frame."""+ runs: list[list[int]] = []+ for k in cells:+ if runs and k == runs[-1][-1] + 1:+ runs[-1].append(k)+ else:+ runs.append([k])+ if len(runs) > 1 and runs[0][0] == 0 and runs[-1][-1] == length - 1:+ runs[0] = runs.pop() + runs[0]+ return runs+++def _assign(run: list[int], options: dict[int, list[dict[str, Any]]], places: list[float], beat: cadence_mod.Beat+ ) -> list[dict[str, Any]] | None:+ """One option for each frame of a run, of the least cost, that keeps every gap from the frame before the run to the+ frame after it under BEAT_JOLT, the frames beside the run where they stand (`places`); None where no choice does.+ A run that is the whole ring closes on itself. Each option's `place` is where it stands, its `cost` a pair added up+ over the run and compared in order."""+ L = beat.length+ ring = len(run) == L++ def ok(k: int, p: float, q: float) -> bool:+ return abs(beat.jolt(k, p, q)) < cadence_mod.BEAT_JOLT++ def add(c: tuple[float, float], d: tuple[float, float]) -> tuple[float, float]:+ return (c[0] + d[0], c[1] + d[1])++ def chain(first: list[int]) -> list[tuple[tuple[float, float], list[int]]]:+ """The cheapest choice ending on each option of the run's last frame, given the first frame's allowed options."""+ k0 = run[0]+ best = {j: (options[k0][j]["cost"], [j]) for j in first+ if ring or ok((k0 - 1) % L, places[(k0 - 1) % L], options[k0][j]["place"])}+ for a, b in zip(run, run[1:]):+ nxt: dict[int, tuple[tuple[float, float], list[int]]] = {}+ for j, o in enumerate(options[b]):+ cands = [(add(cost, o["cost"]), path + [j]) for i, (cost, path) in best.items() if ok(a, options[a][i]["place"], o["place"])]+ if cands:+ nxt[j] = min(cands, key=lambda c: c[0])+ best = nxt+ k1 = run[-1]+ return [(cost, path) for j, (cost, path) in best.items()+ if ok(k1, options[k1][j]["place"], options[run[0]][path[0]]["place"] if ring else places[(k1 + 1) % L])]++ found = ([c for j in range(len(options[run[0]])) for c in chain([j])] if ring+ else chain(list(range(len(options[run[0]])))))+ if not found:+ return None+ _, path = min(found, key=lambda c: c[0])+ return [options[k][j] for k, j in zip(run, path)]+++def _widen(run: list[int], width: int, options: dict[int, list[dict[str, Any]]], places: list[float], beat: cadence_mod.Beat,+ frames: list[Image.Image], fixed: set[int], ghosts: dict[int, float], made: Any) -> dict[str, Any] | None:+ """A run of frames given way that no choice keeps on the beat, with its jolt spread over `width` frames on each side:+ the run's choice (of its `options`: the nearer source frame, however far off its time, or a fraction made again)+ whose largest jolt — inside the run, and the jolt from the frame `width` + 1 before it (and after it) shared evenly+ over the `width` frames between — is the least; each frame beside it moved by its share off its own time (where the+ leg path puts that place, the nearest such time) and made there, or taken where that time is on a source frame. None where the frames beside it are not all at their own+ time and free (`fixed` names those that are not), the least jolt is BEAT_JOLT or more, a frame beside it would be a+ filmed ghost or is made with a fault, or the loop it leaves jolts BEAT_JOLT or more between the two frames held."""+ L, n = beat.length, len(frames)+ if len(run) + 2 * width + 2 > L:+ return None+ left = [(run[0] - d) % L for d in range(1, width + 1)]+ right = [(run[-1] + d) % L for d in range(1, width + 1)]+ if any(k in fixed for k in left + right):+ return None+ hold_l, hold_r = (run[0] - width - 1) % L, (run[-1] + width + 1) % L+ off_l, off_r = beat.off(hold_l, places[hold_l]), beat.off(hold_r, places[hold_r])+ share = width + 1+ # the least largest jolt over the run, chained frame by frame (minimax)+ first = run[0]+ best = {j: (abs(beat.off(first, o["place"]) - off_l) / share, [j]) for j, o in enumerate(options[first])}+ for a, b in zip(run, run[1:]):+ nxt = {}+ for j, o in enumerate(options[b]):+ nxt[j] = min(((max(v, abs(beat.jolt(a, options[a][i]["place"], o["place"]))), path + [j]) for i, (v, path) in best.items()),+ key=lambda c: c[0])+ best = nxt+ last = run[-1]+ worst, path = min(((max(v, abs(off_r - beat.off(last, options[last][j]["place"])) / share), p) for j, (v, p) in best.items()),+ key=lambda c: c[0])+ if worst >= cadence_mod.BEAT_JOLT:+ return None+ chosen = [options[k][j] for k, j in zip(run, path)]+ edge_l, edge_r = beat.off(first, chosen[0]["place"]), beat.off(last, chosen[-1]["place"])+ # each span of the leg path between two source frames, a cycle before and after too: the path climbs, a held drawing flat+ unwrapped = [(i + m * n, beat.M[i] + m * beat.P, beat.M[i + 1] + m * beat.P) for m in (-1, 0, 1) for i in range(n)]+ moved = []+ for cells, edge, hold in ((left, edge_l, off_l), (right, edge_r, off_r)):+ for d, k in enumerate(cells, start=1):+ off = hold + (edge - hold) * (share - d) / share+ target = beat.own(k) + off * beat.beat+ tau = k * n / L+ # the time nearest k's own whose place on the leg path is the target+ hits = [(i, lo, hi) for i, lo, hi in unwrapped if lo <= target <= hi]+ if not hits:+ return None+ i, lo, hi = min(hits, key=lambda h: abs(h[0] + 0.5 - tau))+ frac = float((target - lo) / (hi - lo)) if hi > lo else 0.0+ a, b = i % n, (i + 1) % n+ if frac < SNAP or frac > 1 - SNAP:+ source = a if frac < SNAP else b+ if source in ghosts:+ return None+ moved.append({"at": k, "cell": {"source": source}, "frame": frames[source], "place": beat.at(source), "off": round(off, 3)})+ continue+ frame, measure, wrong = made(frames[a], frames[b], frac)+ if wrong or (measure.get("ghost_window") or 0.0) >= RETIME_WINDOW_MAX:+ return None+ moved.append({"at": k, "cell": {"between": [a, b], "t": round(frac, 4)}, "frame": frame, "place": beat.at(a + frac),+ "off": round(off, 3), "measure": measure})+ after = list(places)+ for k, o in zip(run, chosen):+ after[k] = o["place"]+ for m in moved:+ after[m["at"]] = m["place"]+ span = [(hold_l + q) % L for q in range(len(run) + 2 * width + 1)]+ if any(abs(beat.jolt(k, after[k], after[(k + 1) % L])) >= cadence_mod.BEAT_JOLT for k in span):+ return None+ return {"chosen": chosen, "moved": moved, "width": width}+++def _keep_the_beat(frames: list[Image.Image], out: list[Image.Image], provenance: list[dict[str, Any]],+ gave_way: list[dict[str, Any]], made: Any, *, between: str, ghosts: dict[int, float]) -> dict[str, Any]:+ """The beat of the resampled loop (`cadence.beat_record`), and under `--between auto` the made frames given way kept on+ it: where the loop with the nearer source frame taken for each breaks its beat (a jolt of BEAT_JOLT or more), each run+ of frames given way side by side takes, frame by frame, either that source frame or the same pair made again at+ another fraction of RETIME_T, with no fault, its ghost band under RETIME_WINDOW_MAX in every window, and standing under+ BEAT_JOLT off its own time (a frame moved for a spread meets the same bars) — whichever choice over the+ run keeps every gap from the frame before it to the frame after it under BEAT_JOLT, the fewest made again and those+ nearest their own fraction. A run no choice keeps has its jolt spread over the frames beside it (`_widen`, WIDEN frames+ a side, recorded under `widened`); one that cannot stays on the nearer source frame and is named (`named`). `out` and+ `provenance` are rewritten where a frame is made again or moved; `retimed_at` lists the frames given way that are+ made again (docs/loop-repair.md section 4)."""+ L, count = len(out), len(frames)+ if all(_at_its_time(c, k, count, L) for k, c in enumerate(provenance)):+ return {**cadence_mod.beat_record(None, None), "retimed_at": []}+ beat = cadence_mod.Beat(cadence_mod.leg_path(frames), L)+ places = [beat.place(c) for c in provenance] if beat.reads else None+ record = cadence_mod.beat_record(beat, places)+ if not beat.reads or between != "auto" or not gave_way or not record["over"]:+ return {**record, "retimed_at": []}+ options: dict[int, list[dict[str, Any]]] = {}+ by_at = {g["at"]: g for g in gave_way}+ for k, g in by_at.items():+ i, j = g["pair"]+ nearer = {"how": "nearest", "place": places[k], "cost": (0, 0.0), "off": round(beat.off(k, places[k]), 3)}+ tries = []+ for t in sorted((t for t in RETIME_T if abs(t - g["t"]) > 1e-3), key=lambda t: (abs(t - g["t"]), t)): # not its own again+ place = beat.at(i + t)+ off = beat.off(k, place)+ if abs(off) >= cadence_mod.BEAT_JOLT:+ continue+ frame, measure, wrong = made(frames[i], frames[j], t)+ seen = (measure.get("ghost_window") or 0.0) >= RETIME_WINDOW_MAX # not clean enough to be made only for the beat+ tries.append({"t": t, "off": round(off, 3), "faults": wrong, "ghost_window": measure.get("ghost_window"),+ **({"window_over": RETIME_WINDOW_MAX} if seen and not wrong else {})})+ if not wrong and not seen:+ options.setdefault(k, []).append({"how": "retimed", "t": t, "place": place, "cost": (1, abs(t - g["t"])),+ "off": round(off, 3), "frame": frame, "measure": measure})+ options[k] = [nearer, *options.get(k, [])]+ g["smear"]["retime"] = {"between": [i, j], "tried": tries, "off_nearest": nearer["off"]}+ retimed: list[int] = []+ named: list[list[int]] = []+ widened: list[dict[str, Any]] = []+ runs = _runs(sorted(by_at), L)+ fixed = set(by_at) | {k for k, c in enumerate(provenance) if not _at_its_time(c, k, count, L)}+ for run in runs:+ chosen = _assign(run, options, places, beat)+ if chosen is None:+ spread = next((w for w in (_widen(run, width, options, places, beat, frames, fixed, ghosts, made) for width in WIDEN) if w), None)+ if spread is None:+ named.append(run)+ continue+ chosen = spread["chosen"]+ for m in spread["moved"]:+ out[m["at"]], provenance[m["at"]], places[m["at"]] = m["frame"], m["cell"], m["place"]+ fixed.add(m["at"])+ widened.append({"run": run, "width": spread["width"],+ "moved": [{"at": m["at"], "off": m["off"], **m["cell"]} for m in spread["moved"]],+ "frames": [{k: v for k, v in m.items() if k not in ("frame", "place")} for m in spread["moved"]]})+ for k, o in zip(run, chosen):+ if o["how"] != "retimed":+ continue+ i, j = by_at[k]["pair"]+ out[k], provenance[k], places[k] = o["frame"], {"between": [i, j], "t": round(o["t"], 4)}, o["place"]+ smear = by_at[k]["smear"]+ smear["method"] = "retimed"+ smear["retimed"] = {"t": o["t"], "from_t": round(by_at[k]["t"], 4), "off": o["off"], **o["measure"], "faults": [],+ "look": looks(o["measure"])}+ retimed.append(k)+ final = cadence_mod.beat_record(beat, places)+ return {**final, "retimed": sorted(retimed), "named": named, "widened": widened, "retimed_at": retimed}++strike_signals = legs_mod.strike_signals@@ -753,12 +1096,21 @@ def _fault_line(name: str, m: dict[str, Any], ghost: dict[str, Any] | None = Non*([f"lost its outline on {100 * m['outline_loss']:.2f} % of its edge beyond either source frame beside it"+ ("" if m["outline_shift"] is None else f", {100 * m['outline_shift']:.2f} % lighter than theirs at the same rank")+ " — a melted or ghost limb"] if "outline" in m["faults"] else []),- *([f"carries {_ghost_words(m['ghost'])} — a ghost"] if "ghost" in m["faults"] else []),+ *([f"carries {_ghost_words(m['ghost'])} — a ghost" if (m.get("ghost") or 0.0) > GHOST_WARN else+ f"carries a part-covered band over {100 * m['ghost_window']:.2f} % of the solid pixels in a band {100 * rife_mod.GHOST_BAND:g} % "+ f"of its body high ({100 * m['ghost_window_at'][0]:.0f} to {100 * m['ghost_window_at'][1]:.0f} % down it), at least "+ f"{rife_mod.GHOST_THICK} px thick, though {100 * (m.get('ghost') or 0.0):.2f} % of its whole body — a limb seen through, a ghost"]+ if "ghost" in m["faults"] else []),*([f"opened a transparent hole inside its outline over {100 * m['hole']:.2f} % of its body, at least "f"{rife_mod.HOLE_THICK} px thick, where neither source frame beside it has one — a gap through a limb"]if "hole" in m["faults"] else []),*([f"left a line one source frame beside it draws at part strength in its own place, over a run {100 * m['doubled']:.2f} % ""of its body high — a double outline"] if "doubled" in m["faults"] else [])]+ if m["method"] == "retimed":+ r = m["retimed"]+ return (f"{name}: frame {m['at']}: RIFE's frame at {r['from_t']:g} " + "; ".join(what)+ + f", so the same two source frames were made again at {r['t']:g}, the legs {r['off']:+.2f} of a beat off its "+ f"time, where the nearer source frame broke the beat (--between auto)")if m["method"] == "nearest":return (f"{name}: frame {m['at']}: RIFE's frame " + "; ".join(what)+ (", so the nearer source frame was taken there (--between auto)" if ghost is None else@@ -770,6 +1122,42 @@ def _fault_line(name: str, m: dict[str, Any], ghost: dict[str, Any] | None = Non+ "; see it in cycle/, or align with --between auto (the nearer source frame there) or --between nearest")+def _beat_line(name: str, r: dict[str, Any]) -> str:+ """A loop aligned under auto whose beat is broken (`beat` over), in words: where, how far, and the frames given way+ that no choice kept on it (`named`)."""+ b = r["beat"]+ gaps = ", ".join(f"{a}-{c}" for a, c in b["over"])+ named = sorted(k for run in b.get("named", []) for k in run)+ return (f"{name}: its beat breaks — the legs jolt {b['jolt']:.2f} of a beat between frames {b['gap'][0]} and {b['gap'][1]} "+ f"(at gaps {gaps}: {b['limit']} or more skips into a frame and halts out of it)"+ + (f"; frame(s) {', '.join(map(str, named))} took the nearer source frame, and neither it, nor the same two source "+ f"frames made again at a fraction standing within {b['limit']} of a beat of its time, nor its jolt spread over "+ "the frames beside them keeps the gaps beside them under it" if named else "")+ + " — look at it in cycle/, or film the direction again (docs/loop-repair.md section 4)")+++def _same_foot_line(name: str, r: dict[str, Any]) -> str:+ """A loop that steps the same foot twice in a row (`same_foot` twice), in words, with what its clip's cuts say."""+ f = r["same_foot"]+ foot = {s["peak"]: {"L": "left", "R": "right"}[s["half"]] for s in f["steps"]}+ pairs = "; ".join(f"its own {foot[a]} foot lifts at frames {a} and {b}" for a, b in f["twice"])+ clip = f.get("clip")+ if not clip or not clip.get("cuts"):+ tail = ("; its clip's cuts were not read (" + (clip.get("why") if clip else "cut before video-loop recorded `clip_feet`")+ + "), so whether another cut alternates is not known")+ elif clip["same_foot"] and not clip["alternate"]:+ joined = clip.get("seam_in_step", 0)+ tail = (f"; every cut of its clip {clip['length']} frames long that reads steps so ({clip['same_foot']} of {clip['cuts']}"+ + (f"; {joined} more with their seam inside a step, which hides the second lift in the seam" if joined else "")+ + "): the take steps that foot twice every cycle, so cutting it again does not help — film this direction again")+ else:+ tail = (f"; {clip['alternate']} of the {clip['cuts']} cuts of its clip {clip['length']} frames long alternate, "+ f"{clip['same_foot']} step so: a cut elsewhere in the clip may alternate")+ return (f"{name}: steps the same foot twice in a row — {pairs}, no step of the other foot between ({f['order']} round the "+ "loop, the picture's left foot its own left seen from behind); the alignment does not change the steps a take "+ f"shows{tail} (docs/loop-repair.md section 4)")++def _look_line(name: str, m: dict[str, Any]) -> str:"""A made frame kept that cross-fades two drawings inside its silhouette, in words."""return (f"{name}: frame {m['at']} (made by RIFE) may cross-fade two drawings inside its outline — where the source frames "@@ -791,7 +1179,8 @@ def _ghost_line(name: str, g: dict[str, Any]) -> str:def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate: rife_mod.Interpolate | None = None,report_path: Path | None = None, between: str = DEFAULT_BETWEEN, views: list[str | None] | None = None,start_foot: str = START_FOOT, multi_cycle: str = "fail", cycles: dict[str, int] | None = None,- state: str | None = None, feet: dict[str, str] | None = None, between_cache: Path | None = None) -> dict[str, Any]:+ state: str | None = None, feet: dict[str, str] | None = None, between_cache: Path | None = None,+ same_foot: str = "warn") -> dict[str, Any]:"""Resample every loop of a set to one length (default: the median), turned to a foot strike —where `views` (one per loop: `front`, `back`, `side@right`, `front_diagonal@left`, …) lets it,the strike of the same own foot (`start_foot`) in every loop.@@ -814,7 +1203,12 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:source frames, fraction and interpolator (its `identity()`, which an injected one must have). Thereport's `between_cache` counts the frames taken (`hits`), made (`misses`), kept but unreadable, andmade while what they are made from changed, so not kept (`not_kept`); it is None without a- directory, and nothing is kept."""+ directory, and nothing is kept.++ Every loop's beat is recorded (`beat`, `cadence.beat_record`, as frames of the turned loop), and a loop seen from the+ back or a back diagonal is read for the same foot stepping twice in a row (`same_foot`, `cadence.same_foot`, with the+ clip's every cut as `video-loop` read them, `clip`): `same_foot` warn names such a loop in the warnings, refuse stops+ the set before anything is rewritten (the report written with `applied` false, `refused` same-foot)."""if len(loop_dirs) < 1:raise SystemExit("video-cycle-align: at least one --loop-dir")if between_cache is not None and interpolate is not None and not callable(getattr(interpolate, "identity", None)):@@ -826,6 +1220,8 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:raise SystemExit(f"video-cycle-align: --start-foot must be left or right, not {start_foot!r}")if multi_cycle not in MULTI_CYCLE:raise SystemExit(f"video-cycle-align: --multi-cycle must be one of {', '.join(MULTI_CYCLE)}, not {multi_cycle!r}")+ if same_foot not in SAME_FOOT:+ raise SystemExit(f"video-cycle-align: --same-foot must be one of {', '.join(SAME_FOOT)}, not {same_foot!r}")for v in views or []:if v is not None:name, _, facing = v.partition("@")@@ -944,8 +1340,7 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:# the ghosts passed over or kept as frames of cycle.source/, each cell where it now standsghost_at = sorted(({**g, "at": (g["at"] - start) % target, "source": index[g["source"]], "taken": index[g["taken"]]}for g in facts["ghost_at"]), key=lambda g: g["at"])- again = retake(drawings, facts, ghost_at, fps=fps)- record = {**facts, "drawings": drawings, "retake": again, "turned_by": start, "turned_on": strike["by"], "view": view, "start_foot": strike["start_foot"],+ record = {**facts, "drawings": drawings, "retake": None, "turned_by": start, "turned_on": strike["by"], "view": view, "start_foot": strike["start_foot"],"start_foot_source": strike["start_foot_source"],# the two strikes as they stand in the rebuilt cycle/: the larger first"strikes": [(k - start) % target for k in strike["strikes"]],@@ -961,9 +1356,40 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:# the screen's frames as frames of cycle.source/record["ghost_screen"] = {**facts["ghost_screen"], "ghosts": [{**g, "frame": index[g["frame"]]} for g in facts["ghost_screen"]["ghosts"]]}record["ghost_at"] = ghost_at+ record["beat"] = {**cadence_mod.turned(facts["beat"], start),+ **({"retimed": sorted((k - start) % target for k in facts["beat"]["retimed"]),+ "named": [[(k - start) % target for k in run] for run in facts["beat"]["named"]],+ "widened": [{**w, "run": [(k - start) % target for k in w["run"]],+ "moved": [{**m, "at": (m["at"] - start) % target} for m in w["moved"]]}+ for w in facts["beat"]["widened"]]}+ if "retimed" in facts["beat"] else {})}+ # the cut's own frames read for a jump (cadence.screen_record), each jump with the gaps of the turned loop that show it+ screen = cadence_mod.screen_record(cadence_mod.screen_steps(frames))+ record["screen"] = {**screen, "jumps": [{**j, "step": [index[s] for s in j["step"]],+ "at": [[(k - start) % target, (k + 1 - start) % target]+ for k in _showing(j["step"][0], provenance, len(frames))]}+ for j in screen["jumps"]]}provenance = [{"source": index[p["source"]]} if "source" in p else {"between": [index[j] for j in p["between"]], "t": p["t"]}for p in provenance]- aligned.append((out[start:] + out[:start], record, provenance[start:] + provenance[:start]))+ out = out[start:] + out[:start]+ if cadence_mod.view_reads_feet(view):+ record["same_foot"] = {**cadence_mod.same_foot(out, view), "clip": loops[i][2].get("clip_feet")}+ record["retake"] = retake(drawings, facts, ghost_at, fps=fps, beat=record["beat"], feet=record.get("same_foot"),+ screen=record["screen"])+ aligned.append((out, record, provenance[start:] + provenance[:start]))+ twice = [(loops[i][0], loops[i][1], record) for i, (_, record, _) in enumerate(aligned)+ if (record.get("same_foot") or {}).get("twice")]+ if twice and same_foot == "refuse":+ shared = len({meta_path.name for _, meta_path, *_ in loops}) < len(loops)+ message = ("video-cycle-align: " + "; ".join(_same_foot_line(str(d) if shared else meta_path.name[: -len(".strip.json")], r)+ for d, meta_path, r in twice)+ + ". Stopped before anything was rewritten (--same-foot refuse)")+ if report_path is not None:+ loop_mod.write_loop_report(report_path.expanduser().resolve(), {+ "kind": "sprite-gen-video-cycle-align-report", "applied": False, "refused": "same-foot", "why": message,+ "same_foot": [{"dir": str(d), "name": meta_path.name[: -len(".strip.json")], **r["same_foot"]} for d, meta_path, r in twice],+ "lengths": [len(f) for f in sources], "fps": round(fps, 4)})+ raise SystemExit(message)rows = []for (d, meta_path, meta, _), (out, record, provenance), origin in zip(loops, aligned, origins):merged = _rebuild(d, meta_path, meta, out, fps, record, cells_from=provenance, origin=origin)@@ -974,6 +1400,8 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:warnings = [_fault_line(r["name"], m, next((g for g in r["ghost_at"] if g["at"] == m["at"]), None))for r in rows for m in r.get("smear", []) if m["faults"]]warnings += [_look_line(r["name"], m) for r in rows for m in r.get("smear", []) if m["method"] == "rife" and m["look"]]+ warnings += [_look_line(r["name"], {**m, **m["retimed"]}) for r in rows for m in r.get("smear", [])+ if m["method"] == "retimed" and m["retimed"]["look"]]retakes = [{"dir": r["dir"], "name": r["name"], **r["retake"]} for r in rows if r["retake"]]# A loop to film again is named by its directory where two loops share a strip name (each `walk`).shared = len({r["name"] for r in rows}) < len(rows)@@ -981,7 +1409,7 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:warnings += [f"{r['dir'] if shared else r['name']}: the ghost screen does not read it — {r['ghost_screen']['why']}; no frame of it ""is named a ghost or given way for one, so look at cycle/ (docs/loop-repair.md section 4)"for r in rows if not r["ghost_screen"]["reads"]]- warnings = cycle_warnings + [_retake_line(r["dir"] if shared else r["name"], r["retake"], reason)+ warnings = cycle_warnings + [_retake_line(r["dir"] if shared else r["name"], r["retake"], reason, r)for r in rows if r["retake"] for reason in r["retake"]["reasons"]] + warningsunnamed = [_unnamed_foot(r) for r in rows if r["start_foot"] is None]if len(rows) > 1 and views is None and unnamed:@@ -1003,7 +1431,9 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:{"kind": "injected"} if any(r.get("smear") for r in rows) else None),"between_cache": cache.record() if cache is not None else None,"made_by_rife": sum(r["made_by_rife"] for r in rows),- "replaced": sum(1 for r in rows for m in r.get("smear", []) if m["method"] == "nearest"), "loops": rows}+ "replaced": sum(1 for r in rows for m in r.get("smear", []) if m["method"] == "nearest"),+ "retimed": sum(1 for r in rows for m in r.get("smear", []) if m["method"] == "retimed"),+ "same_foot": same_foot, "loops": rows}if report_path is not None:loop_mod.write_loop_report(report_path.expanduser().resolve(), report)return report@@ -1042,6 +1472,11 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:"measured in the report (`smear`); under auto and nearest a filmed ghost frame gives way to a clean source ""frame beside it (`ghost_at`); a made frame kept that cross-fades two drawings inside its outline is kept ""and named to look at (`look`)")+ parser.add_argument("--same-foot", choices=SAME_FOOT, default="warn",+ help="a loop seen from the back or a back diagonal that steps the same foot twice in a row (the picture's "+ "halves of its feet lifting, read round the loop): warn (default) names it in the report (`same_foot`, "+ "with its clip's every cut as video-loop read them) and the warnings; refuse stops the set before "+ "anything is rewritten, the report naming it")parser.add_argument("--between-cache", type=Path, metavar="DIR",help="a directory every frame RIFE makes between two source frames is kept in, for aligning the same set ""again: a later alignment given the same DIR (the feet told, a retake in place of one loop) takes a "@@ -1083,7 +1518,8 @@ def run(**kwargs: object) -> int:start_foot=str(kwargs.get("start_foot") or START_FOOT),multi_cycle=str(kwargs.get("multi_cycle") or "fail"), cycles=parse_cycles(list(kwargs.get("cycles") or [])), # type: ignore[arg-type]state=kwargs.get("state"), feet=parse_feet(list(kwargs.get("foot") or [])), # type: ignore[arg-type]- between_cache=kwargs.get("between_cache")) # type: ignore[arg-type]+ between_cache=kwargs.get("between_cache"), # type: ignore[arg-type]+ same_foot=str(kwargs.get("same_foot") or "warn"))except rife_mod.RifeNotInstalled as exc:# Asked for by name, so no RIFE is a failure, never a quiet skip (video-set skips with a warning).raise SystemExit(f"video-cycle-align: {exc}; frames between source frames are made by RIFE — "diff --git a/sprite_gen/video/cadence.py b/sprite_gen/video/cadence.pynew file mode 100644index 0000000..60d431c--- /dev/null+++ b/sprite_gen/video/cadence.py@@ -0,0 +1,352 @@+# SPDX-License-Identifier: Apache-2.0+"""The beat an aligned walk keeps, and the feet it steps with, read off a loop's own frames (docs/loop-repair.md+section 4).++- The leg path (`leg_path`): how far the legs move from each frame of a cycle to the next, read where the feet are, the+ lowest LEG_PATH_BAND of the box every frame's figure fits in. Each BLOCK x BLOCK block holding a part of the figure+ there is looked for in the next frame within SEARCH px; the step is the blocks' mean shift, in % of the box's height.+ A cape or a tail held still over the band adds no shift, where a brightness difference would add its whole change; a+ block that matches nowhere changed shape (a sole turning) and counts its residual instead. Read at READ_HEIGHT: a cut's+ frames are drawn about twice a strip's size, and a block and the search reach the same part of the figure at the+ strip's. Summed from the first frame, the steps give each frame of the cycle a place on the path, M(i), and the cycle+ its length P = M(n); a frame made at fraction t between frames i and i + 1 stands at M(i) + t (M(i + 1) - M(i)).+- The beat jolt (`Beat`): a cycle of n frames resampled to L asks frame k for the time k n / L, and standing there it is+ at e_k = M(k n / L). A frame standing elsewhere — the nearer source frame taken for one that could not be made, a+ filmed ghost given way to the frame beside it — moves the legs more into it and less out of it, or the other way round:+ jolt_k = ((p_(k+1) - p_k) mod P - (e_(k+1) - e_k) mod P) / (P / L), in beats, p_k where frame k stands. Every frame at+ its own time leaves every jolt 0, whatever the cut's own rhythm (drawings held for two or three frames, one step+ quicker than the next). A jolt of BEAT_JOLT or more is a broken beat: a skip into a frame and a halt out of it.+- The screen step (`screen_steps`, `screen_record`): how much of the picture changes from each frame of the cut to the+ next, the mean |luminance difference| over white of the box (0..255) and of its lowest SCREEN_ROWS, where the leg+ path reads only where the feet go. Two drawings filmed a pose apart (the legs wide in one, crossed in the next) move+ the feet little and change the picture much; the beat cannot see it, the screen can. A step SCREEN_JUMP times the+ cycle's typical step (its upper quartile, a drawing change on ones, twos or threes) and SCREEN_ALONE times every+ other step is a jump: between two frames inside the cut, filmed so; the last step, the cut's seam.+- Same foot twice (`same_foot`, over a loop; `clip_feet`, over every cut of a clip): read where the feet stand side by+ side and the stepping foot is drawn higher (STEP_VIEWS). The feet split at the middle of the solid columns of the+ box's lowest FOOT_ROWS over the loop; for each frame and half, its lift is how far the half's lowest solid row ends+ above the frame's own lowest row, of the box's height. A step is a run of LIFT_CELLS or more frames (round the ring)+ lifted LIFT_MIN or more; two runs of one half are two steps only where its lift comes down to DOWN_MAX or under between+ them. Read only where both halves step: the steps in ring order by their highest frame, the same foot twice where two+ neighbours on the ring (the last and the first among them) are one half.+"""++from __future__ import annotations++from typing import Any++from PIL import Image++from sprite_gen._deps import np++LEG_PATH_BAND = 0.10 # the leg path is read on the lowest tenth of the loop's box: the feet and the shins+READ_HEIGHT = 410 # px the first frame's figure ends at, at most, where the path is read+BLOCK, SEARCH = 8, 12 # px: the blocks matched, and how far each is looked for in the next frame+MATCH_BAD = 40.0 # mean |RGBA| difference (0..255) over which a block matched nowhere: its residual is its motion+# A broken beat: a jolt of a quarter of a beat or more. An aligned frame may move the legs into it or out of it by up to a+# quarter of a beat more than its own time would, so two even gaps beside it stay within 5 to 3 of each other.+BEAT_JOLT = 0.25+SCREEN_ROWS = 0.30 # the screen's leg rows: the lowest 30 % of the box (a strip cell's lowest 125 of its 406 px)+# A jump: a step of the cut's frames that, over the box or on its leg rows, changes SCREEN_JUMP times as much of the+# picture as the cycle's typical step or more (its upper quartile: a drawing change, whether the cut is drawn on ones,+# twos or threes) and SCREEN_ALONE times as much as any other step of the cycle or more (a cycle whose drawing changes+# are all large has no one step that jumps).+SCREEN_JUMP = 2.0+SCREEN_ALONE = 1.3+STEP_VIEWS = ("back", "back_diagonal") # the views whose feet stand side by side, the stepping foot drawn higher+FOOT_ROWS = 0.03 # the feet split at the middle of the solid columns of the box's lowest 3 % over the loop+LIFT_MIN = 0.010 # a half lifted by 1 % of the box's height or more is in a step ...+LIFT_CELLS = 2 # ... held for two frames or more+DOWN_MAX = 0.006 # two lifts of one half are two steps where it comes down to 0.6 % or under between them+++def _premultiplied(frame: Image.Image) -> np.ndarray:+ a = np.asarray(frame.convert("RGBA"), dtype=np.float32)+ out = a.copy()+ out[..., :3] *= a[..., 3:4] / 255.0+ return out+++def _box(solid: list[np.ndarray]) -> tuple[int, int, int, int]:+ """(top, bottom, left, right) of the union of the frames' solid pixels, the bottom and right exclusive."""+ union = np.any(np.stack(solid), axis=0)+ rows, cols = np.nonzero(union.any(axis=1))[0], np.nonzero(union.any(axis=0))[0]+ return int(rows[0]), int(rows[-1]) + 1, int(cols[0]), int(cols[-1]) + 1+++def _block_flow(a: np.ndarray, b: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:+ """Per block of `a` (premultiplied RGBA), the shift to its best match in `b` within SEARCH px, that match's mean+ |difference| and whether the block holds a part of the figure (a quarter of its pixels solid, in `a` or `b`)."""+ H, W = a.shape[:2]+ pad = np.pad(b, ((SEARCH, SEARCH), (SEARCH, SEARCH), (0, 0)))+ nby, nbx = H // BLOCK, W // BLOCK+ A = a[: nby * BLOCK, : nbx * BLOCK]+ best = np.full((nby, nbx), np.inf, dtype=np.float32)+ shift = np.zeros((nby, nbx, 2), dtype=np.float32)+ for dy in range(-SEARCH, SEARCH + 1):+ for dx in range(-SEARCH, SEARCH + 1):+ B = pad[SEARCH + dy : SEARCH + dy + nby * BLOCK, SEARCH + dx : SEARCH + dx + nbx * BLOCK]+ diff = np.abs(A - B).mean(axis=2).reshape(nby, BLOCK, nbx, BLOCK).mean(axis=(1, 3))+ diff = diff + 0.02 * (abs(dy) + abs(dx)) # a flat block does not wander+ better = diff < best+ best = np.where(better, diff, best)+ shift[better] = (dy, dx)+ solid_a = (a[: nby * BLOCK, : nbx * BLOCK, 3] >= 128).reshape(nby, BLOCK, nbx, BLOCK).mean(axis=(1, 3))+ solid_b = (b[: nby * BLOCK, : nbx * BLOCK, 3] >= 128).reshape(nby, BLOCK, nbx, BLOCK).mean(axis=(1, 3))+ return shift, best, (solid_a >= 0.25) | (solid_b >= 0.25)+++def _step(a: np.ndarray, b: np.ndarray, height: int) -> float:+ shift, best, keep = _block_flow(a, b)+ if not keep.any():+ return 0.0+ length = np.hypot(shift[..., 0], shift[..., 1])+ length = np.where(best > MATCH_BAD, np.maximum(length, best / MATCH_BAD * SEARCH), length)+ return float(length[keep].mean() / height * 100.0)+++def leg_path(frames: list[Image.Image]) -> list[float]:+ """How far the legs move from each frame of a cycle to the next, the last to the first: the steps of the leg path,+ in % of the box's height (the module's docstring)."""+ bottom = (frames[0].getchannel("A").point(lambda v: 255 if v >= 128 else 0).getbbox() or (0, 0, 0, 0))[3]+ scale = min(1.0, READ_HEIGHT / max(1, bottom))+ if scale < 1.0:+ size = (round(frames[0].width * scale), round(frames[0].height * scale))+ frames = [f.convert("RGBA").resize(size, Image.LANCZOS) for f in frames]+ pm = [_premultiplied(f) for f in frames]+ y0, y1, x0, x1 = _box([p[..., 3] >= 128 for p in pm])+ height = y1 - y0+ top = y1 - round(height * LEG_PATH_BAND)+ legs = [p[top:y1, x0:x1] for p in pm]+ n = len(legs)+ return [round(_step(legs[k], legs[(k + 1) % n], height), 4) for k in range(n)]+++def screen_steps(frames: list[Image.Image]) -> dict[str, list[float]]:+ """How much of the picture changes from each frame of a cycle to the next, the last to the first: the mean+ |luminance difference| over white (0..255) of the box every frame's figure fits in (`whole`) and of its lowest+ SCREEN_ROWS (`legs`), read at READ_HEIGHT (the module's docstring)."""+ bottom = (frames[0].getchannel("A").point(lambda v: 255 if v >= 128 else 0).getbbox() or (0, 0, 0, 0))[3]+ scale = min(1.0, READ_HEIGHT / max(1, bottom))+ if scale < 1.0:+ size = (round(frames[0].width * scale), round(frames[0].height * scale))+ frames = [f.convert("RGBA").resize(size, Image.LANCZOS) for f in frames]+ rgba = [np.asarray(f.convert("RGBA"), dtype=np.float32) for f in frames]+ y0, y1, x0, x1 = _box([a[..., 3] >= 128 for a in rgba])+ top = y1 - round((y1 - y0) * SCREEN_ROWS)+ luma = np.array([0.299, 0.587, 0.114], dtype=np.float32)+ lum = [(a[y0:y1, x0:x1, :3] * (a[y0:y1, x0:x1, 3:4] / 255.0) + 255.0 * (1 - a[y0:y1, x0:x1, 3:4] / 255.0)) @ luma for a in rgba]+ n = len(lum)+ diffs = [np.abs(lum[(k + 1) % n] - lum[k]) for k in range(n)]+ return {"whole": [round(float(d.mean()), 3) for d in diffs], "legs": [round(float(d[top - y0 :].mean()), 3) for d in diffs]}+++def screen_record(steps: dict[str, list[float]]) -> dict[str, Any]:+ """The jumps among a cycle's screen steps (`screen_steps` of the frames as cut; step i from frame i to i + 1, the last+ step the cut's seam): each step that, over the box or on its leg rows, is SCREEN_JUMP times the cycle's typical step+ (`typical`, the upper quartile) or more and SCREEN_ALONE times every other step or more. A jump names its step,+ whether it is the seam, and per region its change and the two ratios ([change, of typical, of the next largest])."""+ n = len(steps["whole"])+ typical = {r: float(np.percentile(steps[r], 75)) for r in ("whole", "legs")}+ jumps = []+ for i in range(n):+ ratios = {}+ for r in ("whole", "legs"):+ g = steps[r]+ rest = max(g[:i] + g[i + 1 :], default=0.0)+ ratios[r] = [round(g[i], 2), round(g[i] / typical[r], 3) if typical[r] > 0 else 0.0, round(g[i] / rest, 3) if rest > 0 else 0.0]+ if any(of >= SCREEN_JUMP and alone >= SCREEN_ALONE for _, of, alone in ratios.values()):+ jumps.append({"step": [i, (i + 1) % n], "seam": i == n - 1, **ratios})+ return {**steps, "typical": {r: round(v, 3) for r, v in typical.items()}, "jumps": jumps,+ "limits": {"jump": SCREEN_JUMP, "alone": SCREEN_ALONE, "rows": SCREEN_ROWS}}+++class Beat:+ """A cycle's leg path (`leg_path` steps) and the beat of a loop of `length` frames resampled from it."""++ def __init__(self, steps: list[float], length: int):+ self.n, self.length = len(steps), length+ self.M = np.concatenate([[0.0], np.cumsum(steps)])+ self.P = float(self.M[-1])+ self.beat = self.P / length++ @property+ def reads(self) -> bool:+ """Whether the legs move at all on the band: a path of no length has no beat."""+ return self.P > 0++ def at(self, tau: float) -> float:+ """The place on the path of the source's time `tau` (cyclic)."""+ tau %= self.n+ i = int(np.floor(tau))+ return float(self.M[i] + (tau - i) * (self.M[i + 1] - self.M[i]))++ def place(self, cell: dict[str, Any]) -> float:+ """Where a frame of the loop stands, as `cells_from` records it: a source frame, or one made between two."""+ return self.at(cell["source"]) if "source" in cell else self.at(cell["between"][0] + cell["t"])++ def own(self, k: int) -> float:+ """Where frame k of the loop would stand at its own time, k n / L."""+ return self.at(k * self.n / self.length)++ def off(self, k: int, place: float) -> float:+ """How far `place` is from frame k's own, in beats, the shorter way round the path."""+ return (((place - self.own(k)) + self.P / 2) % self.P - self.P / 2) / self.beat++ def jolt(self, k: int, p: float, q: float) -> float:+ """The jolt from frame k at place p to frame k + 1 at place q, in beats."""+ L = self.length+ return (((q - p) % self.P) - ((self.own((k + 1) % L) - self.own(k)) % self.P)) / self.beat++ def jolts(self, places: list[float]) -> list[float]:+ L = len(places)+ return [self.jolt(k, places[k], places[(k + 1) % L]) for k in range(L)]+++def beat_record(beat: Beat | None, places: list[float] | None, *, why: str | None = None) -> dict[str, Any]:+ """The beat of a loop whose frames stand at `places` (frames of the cycle before it is turned): its largest jolt and+ the gap it is in (`gap`: frames k and k + 1), every gap at BEAT_JOLT or more (`over`), the limit and the band.+ `places` None: every frame at its own time, every jolt 0 (`path` on-time, nothing read). `beat` None or a path of+ no length: not read (`path` unread, `why`)."""+ record: dict[str, Any] = {"limit": BEAT_JOLT, "band": LEG_PATH_BAND}+ if places is None:+ return {"jolt": 0.0, "gap": None, "over": [], **record, "path": "on-time"}+ if beat is None or not beat.reads:+ return {"jolt": None, "gap": None, "over": [], **record, "path": "unread",+ "why": why or "the legs do not move on the band: the leg path has no length"}+ jolts = beat.jolts(places)+ L = len(jolts)+ worst = max(range(L), key=lambda k: abs(jolts[k]))+ return {"jolt": round(abs(jolts[worst]), 3), "gap": [worst, (worst + 1) % L],+ "over": [[k, (k + 1) % L] for k in range(L) if abs(jolts[k]) >= BEAT_JOLT], **record, "path": "read",+ "jolts": [round(j, 3) for j in jolts]}+++def turned(record: dict[str, Any], start: int) -> dict[str, Any]:+ """A `beat_record` read on the cycle before it was turned to start at frame `start`, as frames of the turned loop."""+ L = len(record["jolts"]) if record.get("jolts") else None+ if L is None:+ return record+ at = lambda k: (k - start) % L # noqa: E731+ return {**record, "gap": [at(k) for k in record["gap"]], "over": sorted([at(a), at(b)] for a, b in record["over"]),+ "jolts": [record["jolts"][(k + start) % L] for k in range(L)]}+++def _profiles(frames: list[Image.Image]) -> list[dict[str, Any]]:+ """Per frame, its solid pixels' extent and, per column, the lowest solid row in it (-1 where none)."""+ out = []+ for f in frames:+ solid = np.asarray(f.convert("RGBA").getchannel("A")) >= 128+ rows = np.nonzero(solid.any(axis=1))[0]+ cols = solid.any(axis=0)+ low = np.where(cols, solid.shape[0] - 1 - np.argmax(solid[::-1], axis=0), -1)+ out.append({"top": int(rows[0]) if rows.size else None, "bottom": int(rows[-1]) if rows.size else None, "low": low})+ return out+++def _read_feet(profiles: list[dict[str, Any]], *, seam: bool = False) -> dict[str, Any]:+ """Same foot twice over a loop of these frames (`_profiles`), read as a ring (the module's docstring); with `seam`,+ also the halves lifted LIFT_MIN or more at both the loop's last frame and its first (`seam_in_step`)."""+ drawn = [p for p in profiles if p["top"] is not None]+ if len(drawn) < len(profiles) or not drawn:+ return {"read": False, "why": "a frame has no solid pixel"}+ y0, y1 = min(p["top"] for p in drawn), max(p["bottom"] for p in drawn) + 1+ h = y1 - y0+ rows = max(1, round(h * FOOT_ROWS))+ low = np.any(np.stack([p["low"] >= y1 - rows for p in profiles]), axis=0)+ xs = np.nonzero(low)[0]+ split = (xs[0] + xs[-1]) / 2+ cols = np.arange(low.size)+ lifts = []+ for p in profiles:+ row = []+ for half in (cols < split, cols >= split):+ lowest = p["low"][half]+ lowest = lowest[lowest >= 0]+ row.append((p["bottom"] - int(lowest.max())) / h if lowest.size else 0.0)+ lifts.append(row)+ n = len(profiles)+ joined = {"seam_in_step": [half for hi, half in enumerate("LR") if min(lifts[0][hi], lifts[-1][hi]) >= LIFT_MIN]} if seam else {}+ steps: list[dict[str, Any]] = []+ for hi, half in enumerate("LR"):+ v = [lifts[k][hi] for k in range(n)]+ up = [x >= LIFT_MIN for x in v]+ if not any(up) or all(up):+ continue+ first = next(k for k in range(n) if not up[k])+ runs: list[list[int]] = []+ cur: list[int] = []+ for j in range(1, n + 1):+ k = (first + j) % n+ if up[k]:+ cur.append(k)+ elif cur:+ runs.append(cur)+ cur = []+ if cur:+ runs.append(cur)++ def down_between(a: list[int], b: list[int]) -> bool:+ k = (a[-1] + 1) % n+ while k != b[0]:+ if v[k] <= DOWN_MAX:+ return True+ k = (k + 1) % n+ return False++ merged: list[list[int]] = []+ for r in runs:+ if merged and not down_between(merged[-1], r):+ merged[-1] = merged[-1] + r+ else:+ merged.append(r)+ if len(merged) > 1 and not down_between(merged[-1], merged[0]):+ merged[0] = merged[-1] + merged[0]+ merged.pop()+ steps += [{"half": half, "frames": r, "peak": max(r, key=lambda k: v[k]), "lift": round(max(v[k] for k in r), 4)}+ for r in merged if len(r) >= LIFT_CELLS]+ halves = {s["half"] for s in steps}+ if halves != {"L", "R"}:+ return {"read": False, "why": (f"only the picture's {'left' if halves == {'L'} else 'right'} half steps" if halves+ else "neither half steps") + f" (a run of {LIFT_CELLS} or more frames lifted "+ f"{LIFT_MIN:g} of the height or more)", "steps": steps, **joined}+ steps.sort(key=lambda s: s["peak"])+ twice = [[steps[i]["peak"], steps[(i + 1) % len(steps)]["peak"]] for i in range(len(steps))+ if steps[i]["half"] == steps[(i + 1) % len(steps)]["half"]]+ return {"read": True, "order": "".join(s["half"] for s in steps), "steps": steps, "twice": twice, **joined}+++def view_reads_feet(view: str | None) -> bool:+ return bool(view) and view.partition("@")[0] in STEP_VIEWS+++def same_foot(frames: list[Image.Image], view: str | None) -> dict[str, Any]:+ """Whether a loop steps the same foot twice in a row (the module's docstring): `read`, the steps in ring order as+ the picture's halves (`order`, L and R; seen from the back or a back diagonal the picture's left foot is the+ character's own left), each step's frames, highest frame and lift, and the pairs of neighbouring steps of one foot+ (`twice`, by their highest frames). Not read in a view whose feet are not side by side (`why`)."""+ if not view_reads_feet(view):+ return {"read": False, "why": f"the {(view or 'unnamed').partition('@')[0]} view: its feet are not side by side with "+ f"the stepping one drawn higher (read in {', '.join(STEP_VIEWS)})"}+ return _read_feet(_profiles(frames))+++def clip_feet(frames: list[Image.Image], length: int, *, first: int = 0) -> dict[str, Any]:+ """Same foot twice over every cut of `length` frames a clip holds, each read as the loop it would make (the+ module's docstring, whatever the view: the alignment reads it where the view does): how many cuts there are+ (`cuts`), how many step the same foot twice, alternate, or do not read, and the first frame of each that steps the+ same foot twice (`same_foot_at`, a clip frame where `frames` start at its frame `first`). A cut whose seam falls+ inside a step — a half lifted at both its last frame and its first — is counted apart (`seam_in_step`), neither+ alternating nor the same foot twice: looped, it joins the end of one lift to the start of another across the seam,+ so where the take lifts one foot twice the loop hides the second lift in its seam and reads as alternating. Every+ other cut that reads stepping the same foot twice is a take that steps so every cycle: no cut of it alternates."""+ n = len(frames)+ if length < 2 or n < length:+ return {"length": length, "cuts": 0, "why": f"the clip holds {n} frames, no cut of {length}"}+ profiles = _profiles(frames)+ readings = [_read_feet(profiles[s : s + length], seam=True) for s in range(n - length + 1)]+ joined = [s for s, r in enumerate(readings) if r.get("seam_in_step")]+ kept = [(s, r) for s, r in enumerate(readings) if not r.get("seam_in_step")]+ same = [first + s for s, r in kept if r["read"] and r["twice"]]+ return {"length": length, "cuts": len(readings), "same_foot": len(same), "alternate": sum(1 for _, r in kept if r["read"] and not r["twice"]),+ "unread": sum(1 for _, r in kept if not r["read"]), "seam_in_step": len(joined), "same_foot_at": same}diff --git a/sprite_gen/video/interpolation_quality.py b/sprite_gen/video/interpolation_quality.pyindex 43c7929..4a9443d 100644--- a/sprite_gen/video/interpolation_quality.py+++ b/sprite_gen/video/interpolation_quality.py@@ -23,6 +23,12 @@ OUTLINE_WARN = 0.05# model leaves between two held drawings (and the frames made beside them) and the frames seen as clean# (docs/loop-repair.md section 4).GHOST_WARN = 0.003+# A made frame whose ghost band, read in windows rife.GHOST_BAND of its body high (`rife.ghost_window`), is over this share+# of a window's solid pixels is a ghost too, though the whole figure's share stays under GHOST_WARN: a band through one+# limb, where one neighbour's gap beside the limb and the other's limb there are blended and the background shows through.+# Set from the made frames of the cycle alignment, clean and seen through (docs/loop-repair.md section 4). Read only+# where the measure carries it — the frames the cycle alignment makes.+GHOST_WINDOW_WARN = 0.014# A made frame whose `rife.crossfade` is over this is named to look at, never given way for: on drawn# walks only the frame seen cross-faded read over it, but on synthetic legs a clean drawing between two# far-apart drawings outlined in grey reads over it too, and a cross-fade drawn without outlines mostly@@ -62,12 +68,15 @@ def faults(measure: dict[str, float | None]) -> list[str]:(`torn`, the overlapped wrap's frames: `rife.passes`, `rife.torn`). A hole through a limb whereit carries the holes the frame opened that neither neighbour has (`hole`, the cycle alignment'sframes: `rife.hole`). A double outline where it carries how far a line one neighbour draws runs at- part strength in its own place (`doubled`, the cycle alignment's frames: `rife.doubled`)."""+ part strength in its own place (`doubled`, the cycle alignment's frames: `rife.doubled`). A ghost too+ where it carries the band read in windows of the body (`ghost_window`, the cycle alignment's frames:+ `rife.ghost_window`) and that is over GHOST_WINDOW_WARN."""shift = measure.get("outline_shift")outline = measure["outline_loss"] if shift is None else min(measure["outline_loss"], shift)return ([*(["smear"] if measure["dark_excess"] > SMEAR_WARN else []),*(["outline"] if outline > OUTLINE_WARN else []),- *(["ghost"] if (measure.get("ghost") or 0.0) > GHOST_WARN else []),+ *(["ghost"] if ((measure.get("ghost") or 0.0) > GHOST_WARN+ or (measure.get("ghost_window") or 0.0) > GHOST_WINDOW_WARN) else []),*(["torn"] if (measure.get("torn") or 0.0) > TORN_WARN else []),*(["hole"] if (measure.get("hole") or 0.0) > HOLE_WARN else []),*(["doubled"] if (measure.get("doubled") or 0.0) > DOUBLED_WARN else [])])diff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.pyindex 28cda9b..fffb4fb 100644--- a/sprite_gen/video/loop.py+++ b/sprite_gen/video/loop.py@@ -49,6 +49,7 @@ from sprite_gen.spec.runio import atomic_write_text, new_stage, refuse_overlapfrom sprite_gen.util.gif_utils import save_clean_giffrom sprite_gen.util.resample import resize_cellfrom sprite_gen.video import motion_anchor, auto_motion, local_cycle, gait_fallback, nonloop, effect+from sprite_gen.video import cadence as cadence_modfrom sprite_gen.video import crossings as crossings_modfrom sprite_gen.video import held as held_modfrom sprite_gen.video import legs as legs_mod@@ -2087,6 +2088,10 @@ def _cut_loop(cycle["coverage"] = round((n - skip - L) / L, 4)# The same, over the cut alone: a clip held for part of its length is held where the cut is.report_base["cycle_drawings"] = held_mod.measure_cycle(clip_steps, start=i, length=L, fps=fps)+ if gait_frames is not None:+ # Every cut of the cut's length the clip holds, read for the same foot stepping twice in a row (sprite_gen/video/+ # cadence.py): `video-cycle-align` says from it whether cutting a loop that does so again could help.+ report_base["clip_feet"] = cadence_mod.clip_feet(gait_frames[skip:], L, first=skip)# playback density, not a fixed count: a long cycle gets more frames so every state plays at# ~gif_fps (a fixed 12 made a 2.5 s jump hold each frame 210 ms while a 1.1 s walk held 90 ms)if n_out is None:@@ -2343,6 +2348,8 @@ def _cut_loop(strip_meta["drawings"] = {k: report_base["drawings"][k] for k in ("hold", "drawings_per_second", "contrast", "frames")}strip_meta["cycle_drawings"] = {k: report_base["cycle_drawings"][k] for k in ("start", "length", "steps", "hold", "drawings_per_second", "contrast")} | ({"why": report_base["cycle_drawings"]["why"]} if "why" in report_base["cycle_drawings"] else {})+ if "clip_feet" in report_base:+ strip_meta["clip_feet"] = report_base["clip_feet"]# A cut frame that is no longer the frame as filmed for a filmed ghost, and one kept with no clean frame beside# it: `cycle/` is the alignment's material (`cycle.source/`), whose screen no longer sees a ghost given way, so the# strip says it, and an alignment carries it over (frames of the cut).diff --git a/sprite_gen/video/rife.py b/sprite_gen/video/rife.pyindex 2c10b54..9691c3f 100644--- a/sprite_gen/video/rife.py+++ b/sprite_gen/video/rife.py@@ -137,6 +137,9 @@ OUTLINED = 0.75# antialiased edge or a keyed strand of hair is a pixel or two wide and erodes away; the band a video# model leaves between two drawings, or a flow carries from it, does not.GHOST_THICK = 5+# `ghost_window`: the same band read in windows this share of the body high, each against the solid pixels in it, so a+# band on one limb counts against that limb's part of the body and not the whole figure's (docs/loop-repair.md section 4).+GHOST_BAND = 0.10# `hole`: a pixel under solid (alpha under 0.5) that the outside of the picture cannot reach without crossing the solid# body is a hole; a made frame's is its neighbours' where either of them is under solid within HOLE_REACH pixels of where# it lay at that neighbour's time — in place, or carried with the whole figure (a gap between an arm and the body or@@ -682,6 +685,31 @@ def ghost(frame: Image.Image) -> float:return round(float(thick.sum()) / max(1, int((alpha >= 0.5).sum())), 5)+def ghost_window(frame: Image.Image) -> tuple[float, tuple[float, float]]:+ """The ghost band (`ghost`: part-covered pixels in regions at least GHOST_THICK pixels thick) read in windows+ GHOST_BAND of the body high, sliding a quarter window at a time down the body: the largest share of a window's solid+ pixels, and where that window lies, as fractions of the body from its top. A band through one limb — the gap one+ neighbour has beside a limb blended with the limb the other has there, so the background shows through it — is a+ small share of a whole figure and a large one of the rows it lies in (docs/loop-repair.md section 4)."""+ alpha = np.asarray(frame.convert("RGBA").getchannel("A"), dtype=np.float32) / 255.0+ lo, hi = PARTIAL_ALPHA+ thick = _mask((alpha > lo) & (alpha < hi), GHOST_THICK, ImageFilter.MinFilter)+ solid = alpha >= 0.5+ rows = np.nonzero(solid.any(axis=1))[0]+ if not rows.size:+ return 0.0, (0.0, 0.0)+ top, bottom = int(rows[0]), int(rows[-1])+ height = bottom - top + 1+ win = max(8, round(height * GHOST_BAND))+ thick_rows, solid_rows = thick.sum(axis=1), solid.sum(axis=1)+ best, at = 0.0, top+ for y in range(top, bottom - win + 2, max(1, win // 4)):+ s = int(solid_rows[y:y + win].sum())+ if s and thick_rows[y:y + win].sum() / s > best:+ best, at = float(thick_rows[y:y + win].sum()) / s, y+ return round(best, 5), (round((at - top) / height, 3), round((at + win - top) / height, 3))++def _enclosed(solid: np.ndarray) -> np.ndarray:"""The pixels off `solid` that the outside of the picture cannot reach without crossing it (8-connected)."""ys, starts, stops, pieces, _ = _components(~solid, diagonal=True)diff --git a/tests/video/test_crossfade.py b/tests/video/test_crossfade.pyindex d9c973a..4ada549 100644--- a/tests/video/test_crossfade.py+++ b/tests/video/test_crossfade.py@@ -164,7 +164,9 @@ def test_alignment_gives_a_crossfaded_frame_way_as_a_double_outline_and_names_it"""Resampled 8 to 12 through a RIFE whose colour run blends and whose coverage run is the union:every frame it makes across the legs' long steps leaves both drawings' lines at half inside thesilhouette, a double outline (`rife.doubled`, tests/video/test_inbetween_doubled.py), so auto gives- it way, each named in a warning line, and names it to look at all the same. Before the double+ it way — to the nearer source frame, or to its pair made again at a fraction with no fault where+ the nearer frame breaks the beat (`retimed`) — each named in a warning line, and names it to look+ at all the same. Before the doubleoutline was read they were kept: the cross-fade reading names and never judges, as a clean drawingbetween far-apart drawings reads over it too, and it still does. Under rife they are kept, eachnamed in a warning line to look at."""@@ -172,7 +174,8 @@ def test_alignment_gives_a_crossfaded_frame_way_as_a_double_outline_and_names_itreport = align.align_set([tmp_path / "E"], length=12, interpolate=lambda a, b, t: _made(a, b, t, _union), multi_cycle="warn")looked = [m for m in report["loops"][0]["smear"] if m["look"]]assert looked and all(m["look"] == ["crossfade"] and m["crossfade"] > CROSSFADE_LOOK for m in looked)- assert all(m["method"] == "nearest" and "doubled" in m["faults"] for m in looked)+ assert all(m["method"] in ("nearest", "retimed") and "doubled" in m["faults"] for m in looked)+ assert all(m["retimed"]["faults"] == [] for m in looked if m["method"] == "retimed")assert all(any(f"frame {m['at']}: RIFE's frame" in w and "a double outline" in w for w in report["warnings"]) for m in looked)_cut(_keyed(tmp_path, "R", 8), tmp_path / "R", 8)report = align.align_set([tmp_path / "R"], length=12, interpolate=lambda a, b, t: _made(a, b, t, _union), multi_cycle="warn",diff --git a/tests/video/test_cycle_align.py b/tests/video/test_cycle_align.pyindex a37fb04..ad30dcf 100644--- a/tests/video/test_cycle_align.py+++ b/tests/video/test_cycle_align.py@@ -49,8 +49,9 @@ def test_resample_keeps_every_frame_that_lands_on_a_source_frame():frames = [_walker(2 * math.pi * k / 6) for k in range(6)]rec = Recorder()out, facts = align.resample(frames, 12, rec, between="rife")- assert {k: v for k, v in facts.items() if k not in ("smear", "ghost_screen")} == {+ assert {k: v for k, v in facts.items() if k not in ("smear", "ghost_screen", "beat")} == {"from": 6, "to": 12, "between": "rife", "taken": 6, "made_by_rife": 6, "made_at": [1, 3, 5, 7, 9, 11], "ghost_at": []}+ assert facts["beat"]["path"] == "on-time" and facts["beat"]["jolt"] == 0.0 # every frame at its own timeassert [m["at"] for m in facts["smear"]] == [1, 3, 5, 7, 9, 11]assert all(out[2 * k] is frames[k] for k in range(6)) and rec.calls == [0.5] * 6same, facts = align.resample(frames, 6, None) # already that long: untouched, nothing madediff --git a/tests/video/test_cycle_align_beat.py b/tests/video/test_cycle_align_beat.pynew file mode 100644index 0000000..3dc2d72--- /dev/null+++ b/tests/video/test_cycle_align_beat.py@@ -0,0 +1,398 @@+# SPDX-License-Identifier: Apache-2.0+"""The beat an aligned walk keeps, and the feet it steps with (docs/loop-repair.md section 4, sprite_gen/video/cadence.py).++A frame `--between auto` cannot make gives way to the nearer source frame. Where a cut holds its drawings for three+frames and the set's length puts a frame half way between two drawings, the nearer one is the next drawing: the legs+skip into that frame and halt out of it, the beat jolts. Where the jolt is BEAT_JOLT or more the same two source frames+are made again at another fraction: the one nearest the frame's own, with no fault and within BEAT_JOLT of its time, of+the choices over a run of such frames side by side that keep every gap under BEAT_JOLT. Two frames side by side each+made again nearest its own fraction can jolt the gap between them past it, so the choice is the run's, not each+frame's. A run no choice keeps has its jolt spread over two (or three) frames on each side, moved off their own time by+an even share of it and made there; one that cannot stays on the nearer source frame, named in the report and the+warnings. A loop whose frames given way already keep the beat is delivered as before.++Seen from the back the feet stand side by side and the stepping foot is drawn higher: a loop that lifts one foot twice+with no step of the other between steps the same foot twice, named — or, with `--same-foot refuse`, the set stopped —+with what every cut of its clip (`video-loop`'s `clip_feet`) says.++Synthetic figures only: an outlined body over two outlined feet. For the beat the feet slide along the ground together+by a block's width at each drawing (so every step reads alike); the interpolator draws them where the fraction puts them,+and smears the body where it is told the frame breaks. For the feet they stand still and lift in turn."""++from __future__ import annotations++import json+from pathlib import Path++import numpy as np+import pytest+from PIL import Image, ImageDraw++from sprite_gen.video import align, cadence+from sprite_gen.video.interpolation_quality import GHOST_WINDOW_WARN+from sprite_gen.video import loop as loop_mod++H = 120+LINE, BODY, FOOT = (0, 0, 0, 255), (230, 230, 230, 255), (150, 90, 60, 255)+STEP = 8 # px the feet slide at each drawing: a block's width, so every step's blocks read alike+++def _box(d: ImageDraw.ImageDraw, x0: int, y0: int, x1: int, y1: int, fill: tuple[int, ...]) -> None:+ d.rectangle([x0, y0, x1 - 1, y1 - 1], fill=LINE)+ d.rectangle([x0 + 2, y0 + 2, x1 - 3, y1 - 3], fill=fill)+++def _figure(width: int, left: float, right: float, *, lift: tuple[int, int] = (0, 0), smear: bool = False,+ height: int = H) -> Image.Image:+ """A body from row 10 over two feet 16 px wide (two blocks) and 10 high on the ground 10 px above the bottom, the left+ from column `left`, the right from `right`, each `lift` px off the ground; `smear` paints a dark blot inside the body,+ as RIFE smears a frame it cannot follow."""+ im = Image.new("RGBA", (width, height), (0, 0, 0, 0))+ d = ImageDraw.Draw(im)+ ground = height - 10+ _box(d, 60, 10, 120, ground - 15, BODY)+ for x, up in ((left, lift[0]), (right, lift[1])):+ x = round(x)+ _box(d, x, ground - 10 - up, x + 16, ground - up, FOOT)+ if smear:+ d.rectangle([80, 40, 87, 47], fill=(20, 20, 20, 255))+ return im+++def _slide(drawing: int, drawings: int) -> int:+ """Where the feet stand at a drawing of a cycle of `drawings`: forward a step a drawing for half of it, then back."""+ half = drawings // 2+ return STEP * (drawing if drawing <= half else drawings - drawing)+++class Walk:+ """A cut of `frames` frames, each drawing held `hold` frames (the first drawing beginning at frame `first`), the feet+ sliding a step at each drawing; and its interpolator, which draws the feet where the fraction puts them and smears+ the frame of a pair `breaks(i, t)` names."""++ def __init__(self, frames: int, hold: int, *, first: int = 0, width: int = 200, breaks=lambda i, t: False):+ self.count, self.width, self.breaks = frames, width, breaks+ drawings = frames // hold+ self.at = [_slide(((f - first) // hold) % drawings, drawings) for f in range(frames)]+ self.frames = [self._drawn(x) for x in self.at]+ self.calls: list[tuple[int, float]] = []++ def _drawn(self, x: float, smear: bool = False) -> Image.Image:+ return _figure(self.width, 8 + x, 96 + x, smear=smear)++ def __call__(self, a: Image.Image, b: Image.Image, t: float) -> Image.Image:+ i = next(k for k, f in enumerate(self.frames) if f is a)+ self.calls.append((i, round(t, 4)))+ x = self.at[i] + t * (self.at[(i + 1) % self.count] - self.at[i])+ return self._drawn(x, smear=self.breaks(i, round(t, 4)))+++def _jolt(walk: Walk, cells: list[dict], length: int) -> float:+ """The largest beat jolt of a loop whose frames come from `cells` (`cadence.Beat`, the definition)."""+ beat = cadence.Beat(cadence.leg_path(walk.frames), length)+ return max(abs(j) for j in beat.jolts([beat.place(c) for c in cells]))+++def test_a_frame_half_way_between_two_held_drawings_is_made_again_where_the_nearer_drawing_breaks_the_beat():+ """A cut of 54 frames on threes (18 drawings) aligned to 24: a frame every 2.25 source frames, and every fourth is+ half way between two drawings, where RIFE smears. The nearer source frame there is the next drawing, two thirds of a+ beat early: the legs skip into it and halt out of it. Made again at 0.4 of its pair it stands 0.13 of a beat early."""+ walk = Walk(54, 3, first=-1, breaks=lambda i, t: abs(t - 0.5) < 0.08 and walk.at[i] != walk.at[(i + 1) % 54])+ steps = cadence.leg_path(walk.frames)+ assert {round(s, 3) for k, s in enumerate(steps) if walk.at[k] == walk.at[(k + 1) % 54]} == {0.0}+ assert len({round(s, 3) for k, s in enumerate(steps) if walk.at[k] != walk.at[(k + 1) % 54]}) == 1+ cells: list[dict] = []+ out, facts = align.resample(walk.frames, 24, walk, cells_from=cells)+ half_way = [2, 6, 10, 14, 18, 22] # source times 4.5, 13.5, ... 49.5: a drawing ends at 4, the next begins at 5+ assert _jolt(walk, cells, 24) < cadence.BEAT_JOLT+ assert [cells[k] for k in half_way] == [{"between": [i, i + 1], "t": 0.4} for i in (4, 13, 22, 31, 40, 49)]+ nearer = [dict(c) for c in cells]+ for k, i in zip(half_way, (5, 14, 23, 32, 41, 50)):+ nearer[k] = {"source": i}+ assert _jolt(walk, nearer, 24) == pytest.approx(2 / 3, abs=0.01) # as the nearer drawing left it+ assert facts["beat"]["jolt"] == pytest.approx(_jolt(walk, cells, 24), abs=1e-3) == pytest.approx(0.4 / 3, abs=0.01)+ assert facts["beat"]["over"] == [] and facts["beat"]["named"] == [] and facts["beat"]["retimed"] == half_way+ assert facts["nearest_at"] == [] and set(half_way) <= set(facts["made_at"]) and facts["made_by_rife"] == 18+ smear = {m["at"]: m for m in facts["smear"]}+ for k in half_way:+ assert smear[k]["method"] == "retimed" and smear[k]["faults"] == ["smear"]+ assert smear[k]["retimed"]["t"] == 0.4 and smear[k]["retimed"]["off"] == pytest.approx(-0.4 / 3, abs=0.01)+ assert [x["t"] for x in smear[k]["retime"]["tried"]] == [0.45, 0.55, 0.4, 0.6, 0.35, 0.65]+ assert [x["faults"] for x in smear[k]["retime"]["tried"]] == [["smear"], ["smear"], [], [], [], []]+ assert all(out[k] is not walk.frames[cells[k]["between"][0]] for k in half_way)+++class SeenThrough(Walk):+ """A Walk whose frames made at `t` carry a block of the body 6 x 7 px at alpha 0.5: no fault (its ghost band is 0.1 %+ of the body, its window about 1.1 %, under GHOST_WINDOW_WARN), but over RETIME_WINDOW_MAX."""++ def __init__(self, *args, t: float, **kw):+ super().__init__(*args, **kw)+ self.seen_at = t++ def __call__(self, a: Image.Image, b: Image.Image, t: float) -> Image.Image:+ frame = super().__call__(a, b, t)+ if abs(t - self.seen_at) < 1e-6:+ px = np.asarray(frame).copy()+ px[50:57, 80:86, 3] = 128+ frame = Image.fromarray(px, "RGBA")+ return frame+++def test_a_fraction_made_again_is_taken_only_where_it_reads_clean_in_every_window():+ """As the first case, but the frames made at 0.4 carry a block the background shows through: no fault, yet over+ RETIME_WINDOW_MAX in its window. Made only to keep the beat, it is passed over for the next clean fraction, 0.6."""+ walk = SeenThrough(54, 3, first=-1, t=0.4, breaks=lambda i, t: abs(t - 0.5) < 0.08 and walk.at[i] != walk.at[(i + 1) % 54])+ cells: list[dict] = []+ _, facts = align.resample(walk.frames, 24, walk, cells_from=cells)+ half_way = [2, 6, 10, 14, 18, 22]+ assert [cells[k] for k in half_way] == [{"between": [i, i + 1], "t": 0.6} for i in (4, 13, 22, 31, 40, 49)]+ smear = {m["at"]: m for m in facts["smear"]}+ for k in half_way:+ (passed,) = [x for x in smear[k]["retime"]["tried"] if x["t"] == 0.4]+ assert passed["faults"] == [] and align.RETIME_WINDOW_MAX < passed["ghost_window"] < GHOST_WINDOW_WARN+ assert passed["window_over"] == align.RETIME_WINDOW_MAX and smear[k]["retimed"]["t"] == 0.6+ assert facts["beat"]["over"] == [] and facts["beat"]["jolt"] == pytest.approx(0.4 / 3, abs=0.01)+++def _stretched(clean: dict[tuple[int, int], set[float]]) -> Walk:+ """A cut of 20 frames, one drawing each, stretched to 30: frames 1 and 2 stand at source times 0.67 and 1.33, two+ thirds and a third of their pairs, where RIFE smears except at the fractions `clean` names for the pair."""+ return Walk(20, 1, width=208, breaks=lambda i, t: i in (0, 1) and t not in clean[(i, i + 1)])+++def test_two_frames_side_by_side_are_made_again_as_a_run_whose_gaps_keep_the_beat():+ """Frame 1 made again nearest its own fraction (0.75, an eighth of a beat late) and frame 2 nearest its own (0.2, a+ fifth of a beat early) each stand within BEAT_JOLT of their time, but the gap between them jolts by a third of a beat.+ Frame 1 made at 0.55 instead keeps every gap under it."""+ walk = _stretched({(0, 1): {0.55, 0.75}, (1, 2): {0.2}})+ cells: list[dict] = []+ _, facts = align.resample(walk.frames, 30, walk, cells_from=cells)+ each_nearest = [*cells[:1], {"between": [0, 1], "t": 0.75}, {"between": [1, 2], "t": 0.2}, *cells[3:]]+ assert _jolt(walk, each_nearest, 30) == pytest.approx(0.325, abs=0.01) # over BEAT_JOLT+ assert cells[1:3] == [{"between": [0, 1], "t": 0.55}, {"between": [1, 2], "t": 0.2}]+ assert _jolt(walk, cells, 30) == pytest.approx(0.2, abs=0.01) and facts["beat"]["over"] == []+ assert facts["beat"]["retimed"] == [1, 2] and facts["beat"]["named"] == []+++def test_a_run_no_choice_keeps_on_the_beat_stays_on_the_nearer_frame_and_is_named():+ """With 0.55 not clean either, every choice for the two frames jolts a gap past BEAT_JOLT: both keep the nearer+ source frame, the run named."""+ walk = _stretched({(0, 1): {0.75}, (1, 2): {0.2}})+ cells: list[dict] = []+ _, facts = align.resample(walk.frames, 30, walk, cells_from=cells)+ assert cells[1:3] == [{"source": 1}, {"source": 1}]+ assert facts["nearest_at"] == [1, 2] and facts["beat"]["named"] == [[1, 2]] and facts["beat"]["retimed"] == []+ assert facts["beat"]["jolt"] == pytest.approx(1.0, abs=0.01) and [0, 1] in facts["beat"]["over"]+ assert {m["at"]: m["method"] for m in facts["smear"] if m["faults"]} == {1: "nearest", 2: "nearest"}+++def test_a_frame_no_fraction_keeps_spreads_its_jolt_over_the_frames_beside_it():+ """Frame 4 of the cut of 20 stretched to 30 stands at source time 2.67, two thirds of the pair 2 and 3, where RIFE+ smears from 0.4 on: no fraction within BEAT_JOLT of its time is clean, and the nearer source frame stands half a beat+ late. Two frames each side move a third and a sixth of a beat late, made there, and every gap jolts a sixth of a beat:+ the frame keeps the nearer source frame, its jolt shared."""+ walk = Walk(20, 1, width=208, breaks=lambda i, t: i == 2 and t >= 0.4)+ cells: list[dict] = []+ _, facts = align.resample(walk.frames, 30, walk, cells_from=cells)+ assert cells[4] == {"source": 3} and facts["nearest_at"] == [4] and facts["beat"]["named"] == []+ (spread,) = facts["beat"]["widened"]+ assert spread["run"] == [4] and spread["width"] == 2+ assert {m["at"]: round(m["off"], 2) for m in spread["moved"]} == {3: 0.33, 2: 0.17, 5: 0.33, 6: 0.17}+ assert [cells[k]["between"] for k in (2, 3, 5, 6)] == [[1, 2], [2, 3], [3, 4], [4, 5]]+ assert [cells[k]["t"] for k in (2, 3, 5, 6)] == pytest.approx([4 / 9, 2 / 9, 5 / 9, 1 / 9], abs=2e-4)+ assert all(type(cells[k]["t"]) is float for k in (2, 3, 5, 6)) # a number JSON writes as it reads+ assert facts["beat"]["jolt"] == pytest.approx(1 / 6, abs=0.01) and facts["beat"]["over"] == []+ assert _jolt(walk, cells, 30) == pytest.approx(1 / 6, abs=0.01)+ smear = {m["at"]: m for m in facts["smear"]}+ assert all(smear[k]["method"] == "moved" and smear[k]["moved"]["t"] == cells[k]["t"] for k in (2, 3, 5, 6))+ assert {3, 6} <= set(facts["made_at"]) # source frames before, made now+++def test_frames_given_way_that_keep_the_beat_are_delivered_as_before():+ """A cut of 40 frames squeezed to 24: a frame given way stands a fifth of a beat off its time on the nearer source+ frame, under BEAT_JOLT. Nothing is made again, and the loop is the one the nearer frame makes."""+ walk = Walk(40, 1, width=290, breaks=lambda i, t: i == 1)+ cells: list[dict] = []+ out, facts = align.resample(walk.frames, 24, walk, cells_from=cells)+ assert cells[1] == {"source": 2} and out[1] is walk.frames[2] and facts["nearest_at"] == [1]+ assert [c for c in walk.calls if c[0] == 1] == [(1, round(5 / 3 - 1, 4))] # made once, never again+ assert facts["beat"]["jolt"] == pytest.approx(0.2, abs=0.01) and facts["beat"]["over"] == []+ assert "retimed" not in facts["beat"] and "retime" not in facts["smear"][0]+++def test_a_loop_every_frame_of_which_stands_at_its_own_time_reads_no_jolt_without_reading_the_legs(monkeypatch):+ walk = Walk(20, 1, width=208)+ monkeypatch.setattr(cadence, "leg_path", lambda frames: pytest.fail("the legs read"))+ _, facts = align.resample(walk.frames, 30, walk)+ assert facts["beat"] == {"jolt": 0.0, "gap": None, "over": [], "limit": cadence.BEAT_JOLT, "band": cadence.LEG_PATH_BAND,+ "path": "on-time"}+++def test_between_nearest_records_the_beat_it_leaves():+ walk = Walk(54, 3, first=-1)+ _, facts = align.resample(walk.frames, 24, None, between="nearest")+ assert facts["beat"]["path"] == "read" and facts["beat"]["jolt"] == pytest.approx(2 / 3, abs=0.01)+ assert "retimed" not in facts["beat"]+++def _back(lifts: list[tuple[int, int]], *, height: int = H) -> list[Image.Image]:+ """A loop seen from the back: the feet side by side, the left from column 50, the right from 110, each lifted as+ `lifts` says frame by frame (px of a box `height` - 20 px high)."""+ return [_figure(180, 50, 110, lift=up, height=height) for up in lifts]+++def _lifted(frames: int, steps: list[tuple[int, int, int]], *, px: int = 2) -> list[tuple[int, int]]:+ """Per frame, the lift of each foot: each step (foot 0 left or 1 right, first frame, frames) rises `px` a frame to+ its middle and comes down the same way."""+ out = [[0, 0] for _ in range(frames)]+ for foot, first, span in steps:+ for j in range(span):+ out[(first + j) % frames][foot] = px * (min(j, span - 1 - j) + 1)+ return [tuple(x) for x in out] # type: ignore[misc]+++SAME_FOOT = [(1, 2, 5), (1, 9, 3), (0, 15, 5)] # the right foot, down, the right again, then the left+ALTERNATE = [(1, 2, 5), (0, 14, 5)]+++def test_a_loop_that_lifts_one_foot_twice_with_no_step_of_the_other_between_steps_the_same_foot_twice():+ same = cadence.same_foot(_back(_lifted(24, SAME_FOOT)), "back")+ assert same["read"] and same["order"] == "RRL" and same["twice"] == [[4, 10]]+ assert [(s["half"], s["frames"]) for s in same["steps"]] == [("R", [2, 3, 4, 5, 6]), ("R", [9, 10, 11]), ("L", [15, 16, 17, 18, 19])]+ alternate = cadence.same_foot(_back(_lifted(24, ALTERNATE)), "back_diagonal@left")+ assert alternate["read"] and alternate["order"] == "RL" and alternate["twice"] == []+ # read round the ring: turned to start mid-step, the same steps+ turned = _back(_lifted(24, SAME_FOOT))+ assert cadence.same_foot(turned[10:] + turned[:10], "back")["order"] == "RLR"+ assert cadence.same_foot(turned[10:] + turned[:10], "back")["twice"] == [[18, 0]]+++def test_a_foot_down_between_two_lifts_of_it_makes_them_two_steps_and_a_foot_only_dipping_one():+ """A box 250 px high: 3 px a frame is over LIFT_MIN, 2 px between it and DOWN_MAX, 1 px under DOWN_MAX."""+ held = _lifted(24, [(1, 2, 10), (0, 15, 5)], px=3)+ held[6] = (0, 2) # the right foot dips under LIFT_MIN between two lifts, not down to DOWN_MAX: one step+ assert cadence.same_foot(_back(held, height=270), "back")["order"] == "RL"+ held[6] = (0, 1) # down to DOWN_MAX: two+ assert cadence.same_foot(_back(held, height=270), "back")["order"] == "RRL"++[email protected]("view", ["front", "front_diagonal@right", "side@left", None])+def test_the_feet_are_read_only_where_they_stand_side_by_side_seen_from_behind(view):+ reading = cadence.same_foot(_back(_lifted(24, SAME_FOOT)), view)+ assert not reading["read"] and "not side by side" in reading["why"]+++def test_a_loop_one_foot_of_which_never_steps_does_not_read():+ reading = cadence.same_foot(_back(_lifted(24, [(1, 2, 5), (1, 12, 5)])), "back")+ assert not reading["read"] and "only the picture's right half steps" in reading["why"]+++def test_every_cut_of_a_clip_that_steps_one_foot_twice_every_cycle_steps_so():+ clip = _back(_lifted(24, SAME_FOOT) * 3)+ reading = cadence.clip_feet(clip, 24, first=2)+ # a cut starting inside a step (its last frame and its first lifted) is counted apart: 10 of every 24 starts here+ inside = {3, 4, 5, 6, 10, 11, 16, 17, 18, 19}+ assert reading == {"length": 24, "cuts": 49, "same_foot": 29, "alternate": 0, "unread": 0, "seam_in_step": 20,+ "same_foot_at": [2 + s for s in range(49) if s % 24 not in inside]}+ walk = cadence.clip_feet(_back(_lifted(24, ALTERNATE) * 3), 24)+ assert walk["alternate"] == 33 and walk["same_foot"] == 0 and walk["seam_in_step"] == 16+ # a cut a cycle and a half long of a walk that alternates joins a step to the same foot's next+ assert cadence.clip_feet(_back(_lifted(24, ALTERNATE) * 3), 36)["same_foot"] > 0+ assert cadence.clip_feet(clip[:10], 24) == {"length": 24, "cuts": 0, "why": "the clip holds 10 frames, no cut of 24"}+++def test_a_cut_whose_seam_joins_two_lifts_of_one_foot_is_not_a_cut_that_alternates():+ """A cut shorter than the cycle, from inside the second right lift to inside the first right lift of the next cycle:+ looped, its seam joins the two lifts into one, so it reads right then left, alternating, the second lift hidden in a+ seam that jumps mid-step. The clip's cuts count it apart, neither alternating nor the same foot twice."""+ clip = _back(_lifted(24, SAME_FOOT) * 3)+ looped = cadence.same_foot(clip[10:31], "back")+ assert looped["read"] and looped["twice"] == [] and sorted(looped["order"]) == ["L", "R"]+ assert cadence.clip_feet(clip[10:31], 21) == {"length": 21, "cuts": 1, "same_foot": 0, "alternate": 0, "unread": 0,+ "seam_in_step": 1, "same_foot_at": []}+++def _cut(tmp_path: Path, steps: list[tuple[int, int, int]]) -> Path:+ keyed = tmp_path / "keyed"+ keyed.mkdir()+ for k, f in enumerate(_back(_lifted(24, steps) * 2)):+ f.save(keyed / f"{k:04d}.png")+ out = tmp_path / "back"+ loop_mod.run_loop(keyed, out, fps=24.0, state="walk", min_len=None, max_len=None, n_out=None, seam_max=1000.0,+ name="walk", report_path=None, cycle_mode="fixed", start=0, length=24, anchor="none", repair="off")+ return out+++def test_an_aligned_loop_that_steps_the_same_foot_twice_is_named_and_with_refuse_the_set_is_stopped(tmp_path):+ d = _cut(tmp_path, SAME_FOOT)+ meta = json.loads((d / "walk.strip.json").read_text())+ inside = {3, 4, 5, 6, 10, 11, 16, 17, 18, 19}+ assert meta["clip_feet"] == {"length": 24, "cuts": 25, "same_foot": 15, "alternate": 0, "unread": 0, "seam_in_step": 10,+ "same_foot_at": [s for s in range(25) if s not in inside]}+ before = (d / "walk.strip.json").read_bytes()+ report = tmp_path / "set.cycle-align.json"+ with pytest.raises(SystemExit, match="steps the same foot twice in a row .* film this direction again .*--same-foot refuse"):+ align.align_set([d], views=["back"], report_path=report, same_foot="refuse")+ refused = json.loads(report.read_text())+ assert refused["applied"] is False and refused["refused"] == "same-foot" and refused["same_foot"][0]["twice"]+ assert (d / "walk.strip.json").read_bytes() == before+ done = align.align_set([d], views=["back"])+ row = done["loops"][0]+ assert row["same_foot"]["twice"] and row["same_foot"]["clip"]["same_foot"] == 15+ assert any(w.startswith("walk: film this direction again (same-foot): steps the same foot twice in a row")+ and "every cut of its clip 24 frames long that reads steps so (15 of 25; 10 more with their seam inside a step" in w+ for w in done["warnings"])+ assert row["retake"]["reasons"] == ["same-foot"] and row["retake"]["same_foot"]["remedy"] == "retake"+ assert row["retake"]["same_foot"]["clip"] == {"length": 24, "cuts": 25, "same_foot": 15, "alternate": 0, "unread": 0, "seam_in_step": 10}+ assert done["retake"] == [{"dir": row["dir"], "name": "walk", **row["retake"]}]+ assert json.loads((d / "walk.strip.json").read_text())["cycle_align"]["same_foot"] == row["same_foot"]+ assert row["beat"]["path"] == "on-time" and done["same_foot"] == "warn"+++def test_an_aligned_loop_that_alternates_its_feet_is_not_named(tmp_path):+ d = _cut(tmp_path, ALTERNATE)+ done = align.align_set([d], views=["back"], same_foot="refuse")+ assert done["loops"][0]["same_foot"]["order"] in ("RL", "LR") and done["loops"][0]["same_foot"]["twice"] == []+ assert not any("same foot" in w for w in done["warnings"])+++def _retake(beat=None, feet=None, between="auto"):+ return align.retake({"hold": 1}, {"between": between, "to": 24, "nearest_at": [], "smear": []}, [], fps=24.0, beat=beat, feet=feet)+++def test_a_beat_still_broken_and_the_same_foot_twice_are_reasons_to_cut_or_film_again():+ broken = {"path": "read", "jolt": 0.5, "gap": [5, 6], "over": [[4, 5], [5, 6]], "named": [[5, 6], [12]], "limit": cadence.BEAT_JOLT}+ r = _retake(beat=broken)+ assert r == {"reason": "broken-beat", "reasons": ["broken-beat"],+ "broken_beat": {"jolt": 0.5, "gap": [5, 6], "over": [[4, 5], [5, 6]], "named": [5, 6, 12], "remedy": "recut-or-retake"},+ "limits": {"beat_jolt": cadence.BEAT_JOLT}}+ assert _retake(beat=broken, between="nearest") is None # nearest takes the nearer frame by choice: recorded, not named+ assert _retake(beat={**broken, "over": []}) is None and _retake(beat={"path": "on-time", "over": []}) is None+ feet = {"read": True, "order": "RLR", "twice": [[14, 3]]}+ every = {"length": 20, "cuts": 40, "same_foot": 30, "alternate": 0, "unread": 0, "seam_in_step": 10, "same_foot_at": [0]}+ assert _retake(feet={**feet, "clip": every})["same_foot"] == {"order": "RLR", "twice": [[14, 3]], "clip": {k: v for k, v in every.items() if k != "same_foot_at"},+ "remedy": "retake"}+ assert _retake(feet={**feet, "clip": {**every, "alternate": 3}})["same_foot"]["remedy"] == "recut"+ assert _retake(feet={**feet, "clip": None})["same_foot"] == {"order": "RLR", "twice": [[14, 3]], "clip": None, "remedy": "recut-or-retake"}+ both = _retake(beat=broken, feet={**feet, "clip": every})+ assert both["reasons"] == ["broken-beat", "same-foot"] and set(both["limits"]) == {"beat_jolt", "lift_min", "lift_cells", "down_max"}+ assert _retake(feet={**feet, "twice": []}) is None and _retake(feet={"read": False}) is None+++def test_the_beat_breaks_named_in_the_warnings_in_words():+ row = {"beat": {"jolt": 0.55, "gap": [11, 12], "over": [[7, 8], [11, 12]], "limit": cadence.BEAT_JOLT, "named": [[12]]}}+ line = align._beat_line("walk-back", row)+ assert line.startswith("walk-back: its beat breaks — the legs jolt 0.55 of a beat between frames 11 and 12 (at gaps 7-8, 11-12")+ assert "frame(s) 12 took the nearer source frame" in line and "film the direction again" in line+ retake = align.retake({"hold": 1}, {"between": "auto", "to": 27}, [], fps=24.0, beat={**row["beat"], "path": "read"})+ said = align._retake_line("walk-back", retake, "broken-beat", row)+ assert said.startswith("walk-back: cut it again or film this direction again (broken-beat): its beat breaks — the legs jolt 0.55")+++def test_the_turned_beat_names_frames_of_the_turned_loop():+ record = {"jolt": 0.5, "gap": [1, 2], "over": [[0, 1], [1, 2]], "jolts": [0.3, -0.5, 0.1, 0.1], "limit": 0.25}+ assert cadence.turned(record, 1) == {**record, "gap": [0, 1], "over": [[0, 1], [3, 0]], "jolts": [-0.5, 0.1, 0.1, 0.3]}+ assert np.isclose(sum(record["jolts"]), sum(cadence.turned(record, 3)["jolts"]))diff --git a/tests/video/test_ghost_retake.py b/tests/video/test_ghost_retake.pyindex d015ee8..7315068 100644--- a/tests/video/test_ghost_retake.py+++ b/tests/video/test_ghost_retake.py@@ -76,9 +76,12 @@ def test_a_ghost_kept_at_a_whole_time_is_a_take_to_film_again(tmp_path, capsys):(kept,) = _kept(e)assert kept["source"] == 10 and kept["kept"] == "no-clean-frame"assert rife.ghost(_cell(e, kept["at"])) > GHOST_WARN # the cell shows the ghost- assert e["retake"] == {"reason": "filmed-ghost", "reasons": ["filmed-ghost"],- "ghost": {"kept": [kept["at"]], "sources": [10], "ghost_max": kept["ghost"], "limit": GHOST_WARN},- "limits": {"ghost_kept_min": 1}}+ # the ghosts given way to the frames beside them stand off their times, and the beat they break is a reason too+ assert {k: v for k, v in e["retake"].items() if k != "broken_beat"} == {+ "reason": "filmed-ghost", "reasons": ["filmed-ghost", "broken-beat"],+ "ghost": {"kept": [kept["at"]], "sources": [10], "ghost_max": kept["ghost"], "limit": GHOST_WARN},+ "limits": {"ghost_kept_min": 1, "beat_jolt": 0.25}}+ assert e["retake"]["broken_beat"]["named"] == [] and e["retake"]["broken_beat"]["remedy"] == "recut-or-retake"assert "hold" not in e["retake"] and s["retake"] is None # the held numbers only where that reason appliesassert report["retake"] == [{"dir": e["dir"], "name": "walk", **e["retake"]}]assert json.loads(captured.out)["retake"] == report["retake"]@@ -102,9 +105,10 @@ def _check_made_time(report: dict) -> None:assert kept["source"] == 5 and kept["kept"] == "no-clean-frame"made = next(m for m in e["smear"] if m["at"] == kept["at"])assert made["method"] == "nearest" and "ghost" in made["faults"]- assert e["drawings"]["hold"] == 1 and "hold" not in e["retake"] and e["retake"]["reasons"] == ["filmed-ghost"]+ assert e["drawings"]["hold"] == 1 and "hold" not in e["retake"] and e["retake"]["reasons"] == ["filmed-ghost", "broken-beat"]assert e["retake"]["ghost"]["kept"] == [kept["at"]] and e["retake"]["ghost"]["sources"] == [5]- assert [r["reason"] for r in report["retake"]] == ["filmed-ghost"]+ assert [r["reason"] for r in report["retake"] if r["dir"] == e["dir"]] == ["filmed-ghost"]+ assert all(r["reasons"] == ["broken-beat"] for r in report["retake"] if r["dir"] != e["dir"])# The fault line says what became of the cell: kept, the nearer frame a ghost and the other too — not# that the nearer source frame was taken, as if that settled it. (Both loops are `walk`: E's line is# the one that reads its made frame's ghost.)@@ -139,8 +143,12 @@ def test_real_rife_a_ghost_kept_at_a_made_time_is_a_take_to_film_again(tmp_path)def beside_a_ghost(a: Image.Image, b: Image.Image, t: float) -> Image.Image:return real(a, b, t) if max(rife.ghost(a), rife.ghost(b)) > GHOST_WARN else tg._follow(a, b, t)- _check_made_time(_made_time(tmp_path, beside_a_ghost))- assert real.made == 3 # E's frames made between source frames 4 and 5, 5 and 6, 6 and 7+ report = _made_time(tmp_path, beside_a_ghost)+ _check_made_time(report)+ # E's frames made between source frames 4 and 5, 5 and 6, 6 and 7, and each tried again at another fraction of its+ # pair where the frames given way break the beat (`retime`)+ again = [m["retime"] for m in _row(report, "E")["smear"] if "retime" in m and set(m["retime"]["between"]) & {5, 6}]+ assert real.made == 3 + sum(len(r["tried"]) for r in again)def test_a_held_loop_that_keeps_a_ghost_carries_both_reasons_held_drawings_first(tmp_path):@@ -156,7 +164,7 @@ def test_a_held_loop_that_keeps_a_ghost_carries_both_reasons_held_drawings_firstreport = align.align_set([tmp_path / "NE", th._cut(tmp_path, "S", 24, 1)], interpolate=th._cross_fade, length=24)ne = _row(report, "NE")again = ne["retake"]- assert again["reason"] == "held-drawings" and again.get("reasons") == ["held-drawings", "filmed-ghost"] # before: held alone+ assert again["reason"] == "held-drawings" and again.get("reasons") == ["held-drawings", "filmed-ghost", "broken-beat"]kept = _kept(ne)assert kept and all(g["kept"] == "no-clean-frame" for g in kept)assert again["hold"] == 2 and again["drawings"] == 8 and again["drawings_per_second"] == pytest.approx(8.0)@@ -164,8 +172,8 @@ def test_a_held_loop_that_keeps_a_ghost_carries_both_reasons_held_drawings_first"ghost_max": max(g["ghost"] for g in kept), "limit": GHOST_WARN}assert again["ghost"]["sources"] == [7, 8, 9] # 6 gives way to the clean 5; 9 to the clean 10 at one of its cellsassert again["limits"] == {"drawings_per_second_min": align.RETAKE_DRAWINGS_MIN, "unmade_min": align.RETAKE_UNMADE_MIN,- "ghost_kept_min": align.RETAKE_GHOST_KEPT_MIN}- assert [(r["reason"], r["reasons"]) for r in report["retake"]] == [("held-drawings", ["held-drawings", "filmed-ghost"])]+ "ghost_kept_min": align.RETAKE_GHOST_KEPT_MIN, "beat_jolt": 0.25}+ assert [(r["reason"], r["reasons"]) for r in report["retake"]] == [("held-drawings", ["held-drawings", "filmed-ghost", "broken-beat"])]assert _row(report, "S")["retake"] is Nonefor reason in ("held-drawings", "filmed-ghost"):assert len([w for w in report["warnings"] if f"film this direction again ({reason})" in w]) == 1@@ -174,11 +182,13 @@ def test_a_held_loop_that_keeps_a_ghost_carries_both_reasons_held_drawings_firstassert lines and all(w.endswith("being filmed ghosts too (--between auto)") for w in lines)-def test_a_held_loop_with_no_ghost_carries_its_one_reason(tmp_path):+def test_a_held_loop_with_no_ghost_carries_no_ghost_reason(tmp_path):report = align.align_set([th._cut(tmp_path, "NE", 16, 2), th._cut(tmp_path, "S", 24, 1)], interpolate=th._cross_fade, length=24)again = _row(report, "NE")["retake"]- assert again["reason"] == "held-drawings" and again.get("reasons") == ["held-drawings"] and "ghost" not in again- assert again["limits"] == {"drawings_per_second_min": align.RETAKE_DRAWINGS_MIN, "unmade_min": align.RETAKE_UNMADE_MIN}+ # its frames given way (the cross-fade stand-in at every fraction) break its beat too, as in A3 above+ assert again["reason"] == "held-drawings" and again.get("reasons") == ["held-drawings", "broken-beat"] and "ghost" not in again+ assert again["limits"] == {"drawings_per_second_min": align.RETAKE_DRAWINGS_MIN, "unmade_min": align.RETAKE_UNMADE_MIN,+ "beat_jolt": 0.25}def test_a_ghost_rife_keeps_beside_a_clean_frame_is_no_reason(tmp_path):diff --git a/tests/video/test_ghost_screen.py b/tests/video/test_ghost_screen.pyindex 8e91829..b83ab16 100644--- a/tests/video/test_ghost_screen.py+++ b/tests/video/test_ghost_screen.py@@ -143,8 +143,11 @@ def _cut(keyed: Path, out: Path, length: int) -> dict:@pytest.mark.slowdef test_alignment_delivers_no_filmed_ghost_and_names_each_cell_it_passed_over(tmp_path):- """Set length 22: S (20) lands on its ghost at a whole time, E (24) makes a frame next to its- ghost, which carries it, and the nearer frame is that ghost. Both take the frame after it."""+ """Set length 22: S (20) lands on its ghost at a whole time and takes the frame after it. E (24)+ makes a frame next to its ghost, which carries it, and the nearer frame is that ghost: the frame+ after it would stand half a beat late (docs/loop-repair.md section 4, the beat), so the pair is+ made again at a fraction that keeps the beat and carries no ghost (this stand-in draws the nearer+ frame whole: from half way on, frame 6). E passes over no ghost."""dirs = []for name, length, ghost in (("S", 20, 10), ("E", 24, 5)):_cut(_keyed(tmp_path, name, length, (ghost,)), tmp_path / name, length)@@ -154,14 +157,16 @@ def test_alignment_delivers_no_filmed_ghost_and_names_each_cell_it_passed_over(tfor name, ghost in (("S", 10), ("E", 5)):row = by[name]assert [g["frame"] for g in row["ghost_screen"]["ghosts"]] == [ghost]- assert [(g["source"], g["taken"]) for g in row["ghost_at"]] == [(ghost, ghost + 1)]- assert row["cells_from"][row["ghost_at"][0]["at"]] == {"source": ghost + 1}cells = [Image.open(p) for p in sorted((Path(row["dir"]) / "cycle").glob("frame-*.png"))]assert max(rife.ghost(c) for c in cells) <= GHOST_WARN- e = by["E"]- assert next(m for m in e["smear"] if m["at"] == e["ghost_at"][0]["at"])["faults"] == ["ghost"]+ s, e = by["S"], by["E"]+ assert [(g["source"], g["taken"]) for g in s["ghost_at"]] == [(10, 11)]+ assert s["cells_from"][s["ghost_at"][0]["at"]] == {"source": 11}+ (m,) = [m for m in e["smear"] if m["method"] == "retimed"]+ assert m["faults"] == ["ghost"] and m["retimed"]["faults"] == [] and m["retime"]["between"] == [5, 6]+ assert e["ghost_at"] == [] and e["cells_from"][m["at"]] == {"between": [5, 6], "t": m["retimed"]["t"]} and m["retimed"]["t"] >= 0.5named = [w for w in report["warnings"] if "is a filmed ghost" in w]- assert len(named) == 2 and any(w.startswith(f"{e['dir']}: frame {e['ghost_at'][0]['at']}: source frame 5 ") for w in named)+ assert len(named) == 1 and named[0].startswith(f"{s['dir']}: frame {s['ghost_at'][0]['at']}: source frame 10 ")def test_jump_repair_rejects_a_proposal_that_carries_a_ghost(monkeypatch):diff --git a/tests/video/test_held_drawings.py b/tests/video/test_held_drawings.pyindex 73ee712..86ba79b 100644--- a/tests/video/test_held_drawings.py+++ b/tests/video/test_held_drawings.py@@ -147,10 +147,11 @@ def test_a_held_loop_stretched_past_what_an_interpolator_bridges_is_named_for_a_assert retake["reason"] == "held-drawings" and retake["hold"] == 2 and retake["source"] == "span" and retake["drawings"] == 8assert retake["drawings_per_second"] == pytest.approx(8.0) and retake["frames_per_drawing"] == pytest.approx(3.0)assert retake["unmade"] == len(by["NE"]["nearest_at"]) > 0- # on twos at its own length nothing is made; drawn every frame, a replaced frame is no reason to film again+ # on twos at its own length nothing is made; drawn every frame, a replaced frame is no held drawing to film again,+ # but the frames this stand-in cross-fades all take the nearer source frame, and the beat they break is a reasonassert by["SW"]["retake"] is None and by["SW"]["made_by_rife"] == 0- assert by["E"]["retake"] is None and len(by["E"]["nearest_at"]) > 0- assert [(r["name"], r["reason"]) for r in report["retake"]] == [("walk", "held-drawings")]+ assert by["E"]["retake"]["reasons"] == ["broken-beat"] and len(by["E"]["nearest_at"]) > 0+ assert [(r["name"], r["reason"]) for r in report["retake"]] == [("walk", "held-drawings"), ("walk", "broken-beat")]assert Path(report["retake"][0]["dir"]) == dirs[0]lines = [w for w in report["warnings"] if "film this direction again (held-drawings)" in w]assert len(lines) == 1 and "8 drawings a second" in lines[0] and lines[0].startswith(f"{dirs[0]}: ") # every strip is `walk`@@ -185,7 +186,7 @@ def test_a_held_loop_squeezed_past_on_twos_is_not_named(tmp_path):report = align.align_set(dirs, interpolate=_cross_fade, length=24, cycles={"A": 1}) # the bob reads as two cyclesrow = next(r for r in report["loops"] if Path(r["dir"]).name == "A")assert row["drawings"]["hold"] == 2 and row["drawings"]["drawings"] == pytest.approx(16, abs=0.5)- assert len(row["nearest_at"]) > 0 and row["retake"] is None+ assert len(row["nearest_at"]) > 0 and row["retake"]["reasons"] == ["broken-beat"] # no held drawings; the beat breaks@pytest.mark.slow@@ -244,8 +245,8 @@ def test_a_clip_held_for_part_of_its_length_is_read_where_it_was_cut(tmp_path, hif named:assert row["retake"]["reason"] == "held-drawings" and row["retake"]["source"] == "span"assert row["retake"]["drawings"] == 8 and row["retake"]["drawings_per_second"] == pytest.approx(8.0)- else:- assert row["retake"] is None and report["retake"] == []+ else: # no held drawings to film again; the beat the stand-in's cross-fades break is the one reason+ assert row["retake"]["reasons"] == ["broken-beat"] and [r["reasons"] for r in report["retake"]] == [["broken-beat"]]def test_the_cut_is_read_on_the_clips_steps_into_the_frame_after_it():@@ -302,5 +303,6 @@ def test_video_set_carries_the_retake_into_its_record(tmp_path):rows.append({"item": f"{direction}-walk", "direction": direction, "state": "walk", "dir": str(item), "ok": True,"loop": {"n_out": cycle}})out = batch.align_gaits(rows, tmp_path, "auto", interpolate=_cross_fade)- assert out["walk"]["applied"] and [r["reason"] for r in out["walk"]["retake"]] == ["held-drawings"]- assert rows[0]["loop"]["cycle_align"]["retake"]["reason"] == "held-drawings" and rows[1]["loop"]["cycle_align"]["retake"] is None+ assert out["walk"]["applied"] and [r["reason"] for r in out["walk"]["retake"]] == ["held-drawings", "broken-beat"]+ assert rows[0]["loop"]["cycle_align"]["retake"]["reason"] == "held-drawings"+ assert rows[1]["loop"]["cycle_align"]["retake"]["reasons"] == ["broken-beat"] # squeezed, its cross-fades given waydiff --git a/tests/video/test_inbetween_doubled.py b/tests/video/test_inbetween_doubled.pyindex b841de6..d168f17 100644--- a/tests/video/test_inbetween_doubled.py+++ b/tests/video/test_inbetween_doubled.py@@ -13,8 +13,9 @@ outline too.The fixtures are synthetic: a coat over two legs in boots, outlined 3 px in near-black, with a hand beside the coat; thenear boot lifted 18 px in the first source frame and planted in the second. The frame drawn between, and the same with a-source frame's near-boot lines laid over it at part strength; blurred, smeared along the step; a hand moving 60 px over-the coat; boots drawn with a second line; a hem drawn with two lines and softened; a crease one source frame draws. And+source frame's near-boot lines laid over it at part strength; blurred, smeared along the step (a ghost by its window+reading, its feet part-covered); a hand moving 60 px over the coat; boots drawn with a second line; a hem drawn with two+lines and softened; a crease one source frame draws. Andthe walker of tests/video/test_crossfade.py: its drawing between far-apart drawings, and its cross-fades."""from __future__ import annotations@@ -187,7 +188,6 @@ def _clean() -> dict[str, tuple[Image.Image, Image.Image, Image.Image]]:return {"drawn between": (_step(0), _step(1), _step(0.5)),"drawn between, soft": (_step(0), _step(1), _soft(_step(0.5), 1.5)),- "drawn between, smeared along the step": (_step(0), _step(1), _smeared(_step, 0.5, 0.15)),"a hand moving 60 px over the coat": (_hand(0), _hand(1), _hand(0.5)),"the hand, soft": (_hand(0), _hand(1), _soft(_hand(0.5), 1.5)),"the hand, smeared along its way": (_hand(0), _hand(1), _smeared(_hand, 0.5, 0.15)),@@ -197,9 +197,21 @@ def _clean() -> dict[str, tuple[Image.Image, Image.Image, Image.Image]]:}+def test_feet_smeared_along_the_step_read_no_double_outline_and_are_a_ghost_in_their_window():+ """The drawing between smeared along the step (the mean of drawings from t 0.35 to 0.65): no double outline, but the+ feet are left part-covered over a band 4.5 % of the solid pixels in the feet's tenth of the body, so the frame is a+ ghost by its window reading (`rife.ghost_window`) though 0.25 % of the whole body; smeared half as far, it is not."""+ a, b = _step(0), _step(1)+ made = _smeared(_step, 0.5, 0.15)+ assert rife.doubled(made, a, b) == 0+ m = align.measure_made(made, a, b, 0.5, reads=True)+ assert m["ghost"] < 0.003 < 0.014 < m["ghost_window"] and m["ghost_window_at"][0] > 0.85 and faults(m) == ["ghost"]+ assert faults(align.measure_made(_smeared(_step, 0.5, 0.075), a, b, 0.5, reads=True)) == []++@pytest.mark.parametrize("name", list(_clean()))def test_a_clean_soft_or_source_drawn_frame_reads_no_double_outline_and_keeps_its_bytes(name):- """The drawing between, blurred, or smeared along the step; a hand moving fast over the coat, drawn, soft or smeared;+ """The drawing between, or blurred; a hand moving fast over the coat, drawn, soft or smeared;boots both source frames draw with two lines; a hem both draw with two lines, softened to 60 % in the frame between (aline both draw is theirs at any strength); a light crease one draws, carried at its own strength: each reads 0, passesevery fault and is delivered as the very frame made."""diff --git a/tests/video/test_inbetween_seen_through.py b/tests/video/test_inbetween_seen_through.pynew file mode 100644index 0000000..6ef4723--- /dev/null+++ b/tests/video/test_inbetween_seen_through.py@@ -0,0 +1,72 @@+# SPDX-License-Identifier: Apache-2.0+"""A limb seen through (docs/loop-repair.md section 4): a frame made between two source frames where one has a gap beside a+limb and the other has the limb there can blend the two coverages, so the limb is left part-covered over the gap and the+background shows through it. Over the whole figure the band is a small share and `rife.ghost` reads under GHOST_WARN; the+hole reading does not see it either (the band is open to the gap beside the limb, the first source frame's own); read in+windows a tenth of the body high (`rife.ghost_window`) it is a large share of the rows it lies in, and the alignment's+made frame is judged a ghost.++Synthetic figures only: a wide body over two legs, the near leg's outer side cut back in the first source frame (a gap+open to the space between the legs) and whole in the second; the frame made between them has the cut-back strip+part-covered in the leg's colour."""++from __future__ import annotations++import numpy as np+import pytest+from PIL import Image++from sprite_gen.video import align, rife+from sprite_gen.video.interpolation_quality import GHOST_WARN, GHOST_WINDOW_WARN, faults++W, H = 400, 420+BODY, LEG = (210, 180, 150, 255), (150, 110, 90, 255) # light enough that no pixel counts as a dark line+++def _figure(*, cut: bool = False, seen_through: float | None = None) -> Image.Image:+ """A body 300 px wide over two legs 50 px wide; `cut` takes the near leg's outer 8 columns out over 60 rows (a gap+ open to the space between the legs); `seen_through` leaves them at that alpha in the leg's colour instead."""+ a = np.zeros((H, W, 4), dtype=np.uint8)+ a[20:260, 50:350] = BODY+ a[260:400, 110:160] = LEG # far leg+ a[260:400, 240:290] = LEG # near leg+ if cut:+ a[300:360, 240:248] = 0+ if seen_through is not None:+ a[300:360, 240:248] = (*LEG[:3], round(255 * seen_through))+ return Image.fromarray(a, "RGBA")+++def test_a_limb_seen_through_reads_under_the_whole_body_ghost_and_over_the_window():+ a, b, made = _figure(cut=True), _figure(), _figure(seen_through=0.35)+ m = align.measure_made(made, a, b, 0.4, reads=True)+ assert m["ghost"] < GHOST_WARN and m["hole"] == 0.0 # the whole figure's band, and no hole: what 3.3.0 judged by+ assert faults({k: v for k, v in m.items() if not k.startswith("ghost_window")}) == []+ assert m["ghost_window"] > GHOST_WINDOW_WARN and faults(m) == ["ghost"]+ lo, hi = m["ghost_window_at"]+ assert 0.6 < lo < hi < 1.0 # the window lies in the legs+ # the same frame whole is clean in every window+ assert rife.ghost_window(b)[0] == 0.0 and faults(align.measure_made(b, a, b, 0.4, reads=True)) == []+++def test_the_alignment_judges_a_made_frame_with_a_limb_seen_through_a_ghost():+ """Two source frames resampled to four: the frame made between the first and the second is the limb seen through.+ Under rife it is kept and named a ghost (3.3.0 kept it with no fault)."""+ a, b, made = _figure(cut=True), _figure(), _figure(seen_through=0.35)+ out, facts = align.resample([a, b], 4, lambda x, y, t: made.copy() if x is a else y.copy(), between="rife")+ row = next(m for m in facts["smear"] if m["at"] == 1)+ assert row["method"] == "rife" and row["faults"] == ["ghost"] and row["ghost"] < GHOST_WARN < GHOST_WINDOW_WARN < row["ghost_window"]+++def test_a_ghost_read_in_a_window_says_so_in_its_warning():+ m = {"at": 7, "method": "nearest", "faults": ["ghost"], "ghost": 0.0018, "ghost_window": 0.024, "ghost_window_at": [0.6, 0.7],+ "dark_excess": 0.0, "outline_loss": 0.0, "outline_shift": 0.0, "hole": 0.0, "doubled": 0.0}+ line = align._fault_line("walk", m)+ assert "2.40 % of the solid pixels in a band 10 % of its body high (60 to 70 % down it)" in line+ assert "though 0.18 % of its whole body — a limb seen through, a ghost" in line and "nearer source frame was taken" in line++[email protected]("band", [25 / 255, 230 / 255])+def test_a_band_at_the_edges_of_part_cover_is_not_part_covered(band):+ """Alpha 25 and 230 of 255 lie just outside PARTIAL_ALPHA (0.1, 0.9): no band."""+ assert rife.ghost_window(_figure(seen_through=band))[0] == 0.0diff --git a/tests/video/test_loop_prop_seam_held.py b/tests/video/test_loop_prop_seam_held.pyindex 9476763..a07daf5 100644--- a/tests/video/test_loop_prop_seam_held.py+++ b/tests/video/test_loop_prop_seam_held.py@@ -401,6 +401,9 @@ CYCLE_ALIGN_KEYS_2350 = {"between", "cycle_screen", "cycles_given", "drawings",CORRESPONDENCE_KEYS_2410 = {"cells_from", "origin"}# 2.43.0: the ghost screen of the loop as filmed, and each cell where a filmed ghost gave way or was keptGHOST_KEYS_2430 = {"ghost_screen", "ghost_at"}+# Unreleased: every cut of the cut's length the clip holds, read for the same foot twice (video-loop), and the aligned+# loop's beat and its cut's screen steps (docs/loop-repair.md section 4)+CLIP_FEET_KEYS, BEAT_KEYS = {"clip_feet"}, {"beat", "screen"}def test_cycle_align_writes_a_loop_without_a_held_part_as_before(tmp_path, staffless):@@ -422,8 +425,8 @@ def test_cycle_align_writes_a_loop_without_a_held_part_as_before(tmp_path, staffassert all("cycles_kept" not in row and "steps" not in row for row in out["loops"])for d in dirs:meta = json.loads((d / "loop.strip.json").read_text())- assert set(meta) == STRIP_KEYS_2350 | SOURCE_KEYS_2390- assert set(meta["cycle_align"]) == CYCLE_ALIGN_KEYS_2350 | CORRESPONDENCE_KEYS_2410 | GHOST_KEYS_2430+ assert set(meta) == STRIP_KEYS_2350 | SOURCE_KEYS_2390 | CLIP_FEET_KEYS+ assert set(meta["cycle_align"]) == CYCLE_ALIGN_KEYS_2350 | CORRESPONDENCE_KEYS_2410 | GHOST_KEYS_2430 | BEAT_KEYS# The cut's source stays as the cut wrote it: `cycle_align` says the cells were turned after it, so it# no longer names each cell's frame (docs/loop-comparison.md). The rebuilt strip names its own cells —# the same frames, turned, under the same crop.diff --git a/tests/video/test_screen_jump.py b/tests/video/test_screen_jump.pynew file mode 100644index 0000000..6443c70--- /dev/null+++ b/tests/video/test_screen_jump.py@@ -0,0 +1,140 @@+# SPDX-License-Identifier: Apache-2.0+"""A take that jumps (docs/loop-repair.md section 4, sprite_gen/video/cadence.py `screen_record`).++Two drawings filmed a pose apart move the feet little and change the picture much: the beat, read on the leg path, does+not see it. The screen step does: how much of the picture changes from one frame of the cut to the next, over the box and+on its leg rows. A step SCREEN_JUMP times the cycle's typical step (its upper quartile: a drawing change, whether the+cut is on ones or threes) and SCREEN_ALONE times every other step is a jump — inside the cut the take's own+(`filmed-jump`), at its seam the cut's (`seam-jump`); either is cut again from a cycle the clip films without it, or+filmed again. A cycle whose drawing+changes are all alike has none, nor one with two steps alike however large.++Synthetic figures only: an outlined body over an outlined bar 80 px wide in the leg rows, which slides along by the+drawing; a step changes the picture in proportion to how far the bar slides."""++from __future__ import annotations++import json+from pathlib import Path++import pytest+from PIL import Image, ImageDraw++from sprite_gen.video import align, cadence+from sprite_gen.video import loop as loop_mod++W, H = 220, 160+LINE, BODY, BAR = (0, 0, 0, 255), (230, 230, 230, 255), (150, 90, 60, 255)+++def _frame(x: float) -> Image.Image:+ """A body over a bar from column 10 + `x` in the leg rows (rows 104 to 149, the lowest 30 % of the box from row 10)."""+ im = Image.new("RGBA", (W, H), (0, 0, 0, 0))+ d = ImageDraw.Draw(im)+ d.rectangle([60, 10, 139, 99], fill=LINE)+ d.rectangle([62, 12, 137, 97], fill=BODY)+ x = 10 + round(x)+ d.rectangle([x, 104, x + 79, 149], fill=LINE)+ d.rectangle([x + 2, 106, x + 77, 147], fill=BAR)+ return im+++def _cut(places: list[float], hold: int = 3) -> list[Image.Image]:+ """A cut drawn on `hold`s: drawing d with the bar at `places[d]`."""+ return [_frame(x) for x in places for _ in range(hold)]+++EVEN = [4 * min(d, 18 - d) for d in range(18)] # 4 px a drawing out and back: every drawing change alike+JUMP = [0, 4, 8, 12, 16, 36, 40, 44, 48, 52] + [round(52 - 52 * k / 9, 2) for k in range(1, 9)] # 20 px from drawing 4 to 5+TWICE = [0, 4, 8, 28, 32, 36, 56, 60, 64, 68] + [round(68 - 68 * k / 9, 2) for k in range(1, 9)] # 20 px twice+SEAM = [4 * d for d in range(18)] # out all the way, back in one step at the seam+++def test_a_step_far_larger_than_the_cuts_drawing_changes_and_than_any_other_is_a_jump():+ rec = cadence.screen_record(cadence.screen_steps(_cut(JUMP)))+ assert [(j["step"], j["seam"]) for j in rec["jumps"]] == [([14, 15], False)] # drawing 4 ends at frame 14, 5 begins at 15+ jump = rec["jumps"][0]+ for region in ("whole", "legs"):+ change, of_typical, alone = jump[region]+ assert of_typical >= cadence.SCREEN_JUMP and alone >= cadence.SCREEN_ALONE+ assert rec["typical"]["legs"] > 0 and rec["limits"] == {"jump": cadence.SCREEN_JUMP, "alone": cadence.SCREEN_ALONE,+ "rows": cadence.SCREEN_ROWS}+ assert len(rec["whole"]) == len(rec["legs"]) == 54++[email protected]("hold", [1, 2, 3])+def test_a_cut_whose_drawing_changes_are_all_alike_has_no_jump_whatever_it_is_drawn_on(hold):+ """On twos and threes most steps change nothing; the typical step is the upper quartile, a drawing change."""+ rec = cadence.screen_record(cadence.screen_steps(_cut(EVEN, hold)))+ assert rec["jumps"] == []+++def test_two_steps_alike_however_large_are_no_jump():+ rec = cadence.screen_record(cadence.screen_steps(_cut(TWICE)))+ steps = rec["legs"]+ big = sorted(range(len(steps)), key=lambda k: -steps[k])[:2]+ assert sorted(big) == [8, 17] and min(steps[k] for k in big) / rec["typical"]["legs"] >= cadence.SCREEN_JUMP+ assert rec["jumps"] == [] # each is no more than SCREEN_ALONE times the other+++def test_a_jump_at_the_cuts_last_step_is_its_seam():+ rec = cadence.screen_record(cadence.screen_steps(_cut(SEAM)))+ assert [(j["step"], j["seam"]) for j in rec["jumps"]] == [([53, 0], True)]+++def _retake(screen):+ return align.retake({"hold": 1}, {"between": "auto", "to": 24, "nearest_at": [], "smear": []}, [], fps=24.0, screen=screen)+++def test_a_jump_inside_the_cut_and_one_at_its_seam_are_cuts_to_make_again_or_takes_to_film_again():+ filmed = {"step": [30, 31], "seam": False, "whole": [22.0, 2.1, 1.5], "legs": [36.0, 2.5, 1.8], "at": [[13, 14]]}+ seam = {"step": [53, 0], "seam": True, "whole": [30.0, 2.5, 2.0], "legs": [41.0, 2.6, 2.1], "at": [[3, 4]]}+ limits = {"screen_jump": cadence.SCREEN_JUMP, "screen_alone": cadence.SCREEN_ALONE, "screen_rows": cadence.SCREEN_ROWS}+ assert _retake({"jumps": [filmed]}) == {+ "reason": "filmed-jump", "reasons": ["filmed-jump"],+ "filmed_jump": {"steps": [[30, 31]], "at": [[[13, 14]]], "whole": [[22.0, 2.1, 1.5]], "legs": [[36.0, 2.5, 1.8]], "remedy": "recut-or-retake"},+ "limits": limits}+ both = _retake({"jumps": [filmed, seam]})+ assert both["reasons"] == ["filmed-jump", "seam-jump"] and both["seam_jump"]["remedy"] == "recut-or-retake"+ assert both["seam_jump"]["steps"] == [[53, 0]] and both["limits"] == limits+ assert _retake({"jumps": []}) is None and _retake(None) is None+ line = align._retake_line("walk-front_diagonal", both, "filmed-jump")+ assert line.startswith("walk-front_diagonal: cut it again or film this direction again (filmed-jump): the take jumps between two of its frames")+ assert line.endswith("Where the clip films another cycle without the jump, a cut there fixes it; where it does not, a new take does "+ "(docs/loop-repair.md section 4)")+ assert ("from frame 30 to 31 of cycle.source/ the picture changes 22 of 255 over the figure's box and 36 on its legs, "+ "2.10 and 2.50 times the cut's typical step and 1.50 and 1.80 times any other step (the loop's frames 13 to 14)") in line+ assert align._retake_line("walk-front_diagonal", both, "seam-jump").startswith(+ "walk-front_diagonal: cut it again or film this direction again (seam-jump): the cut's seam jumps")+++def _loop(tmp_path: Path, places: list[float]) -> Path:+ keyed = tmp_path / "keyed"+ keyed.mkdir()+ for k, f in enumerate(_cut(places) * 2):+ f.save(keyed / f"{k:04d}.png")+ out = tmp_path / "walk"+ loop_mod.run_loop(keyed, out, fps=24.0, state="walk", min_len=None, max_len=None, n_out=None, seam_max=1000.0,+ name="walk", report_path=None, cycle_mode="fixed", start=0, length=54, anchor="none", repair="off")+ return out+++def test_an_aligned_loop_whose_take_jumps_is_named_with_the_frames_that_show_it(tmp_path):+ """Aligned at its own length (nothing made): the jump stands between the frames the cut's step 14 to 15 lands in."""+ d = _loop(tmp_path, JUMP)+ done = align.align_set([d], multi_cycle="warn")+ row = done["loops"][0]+ jumps = row["screen"]["jumps"]+ assert [(j["step"], j["seam"]) for j in jumps] == [([14, 15], False)]+ start = row["turned_by"]+ assert jumps[0]["at"] == [[(14 - start) % 54, (15 - start) % 54]]+ assert row["retake"]["reasons"] == ["filmed-jump"] and row["retake"]["filmed_jump"]["remedy"] == "recut-or-retake"+ assert sum("cut it again or film this direction again (filmed-jump)" in w for w in done["warnings"]) == 1+ assert json.loads((d / "walk.strip.json").read_text())["cycle_align"]["screen"]["jumps"][0]["step"] == [14, 15]+++def test_an_aligned_loop_whose_drawing_changes_are_alike_names_no_jump(tmp_path):+ done = align.align_set([_loop(tmp_path, EVEN)], multi_cycle="warn")+ assert done["loops"][0]["screen"]["jumps"] == [] and done["loops"][0]["retake"] is None