Skip to content

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

fix(video-loop): the seam pop is a gate — a walk's or run's loop whose top jumps into its first frame more than --seam-pop-max times its median step (default 10) is refused after the seam and step gates, a cut fixed by hand as one motion-auto chooses, and motion-auto reads its cuts before it cuts as the gate reads the loop and takes the next the gate passes; --seam-max does not lift it, --seam-pop-max off does, and a top that cannot be read is not refused and is said

Soohong Kim1c1d6b9ecbbb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c599f7d..49ce3c8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -318,6 +318,14 @@ To get the 2.45.3 frames back, pass:
- **Known limits: Measuring between drawings allows cuts from a third of the stride short to a sixth long on twos, and from a third short to a quarter long on threes, to pass.** On synthetic 24-frame stride walks standing in place, cuts of 16 to 28 frames on twos (ratio 1.02 to 1.67; 30 refused at 2.06) and 16 to 30 frames on threes (0.95 to 1.48) pass the seam gate, whereas drawn on ones cuts of 16 to 22, 28, and 30 are refused (2.38 to 4.07). A shifted final drawing passes up to 2 px on twos (1.66; 3 px refused) and up to 4 px on threes (1.73; 6 px refused). Under `--anchor body` sliding 0.2 px a frame, cuts of 16 to 28 frames pass on twos and 16 to 30 on threes, tolerating shifts of 2 px on twos and 6 px on threes. The step gate already passed these cuts (largest step 1.26 to 1.86), while the earlier frame-by-frame seam gate refused them all. For full synthetic limits and ramp discretization behavior, see `docs/loop-review.md` section "The body anchor and the seam gate".
- **Tests:** `tests/video/test_held_walk_seam.py`: a held walk cut between its drawings passes the seam gate on twos and threes; a walk drawn a frame each is read on every frame and its ratio is the frames' own; a held walk whose last drawing is moved 10 px is refused between its drawings; a held sliding walk passes on the drawings the ramp plays, and a jump the ramp moves into a held walk is refused as the source frames refuse it; a held walk motion-auto cuts passes on its cells between their drawings (a side walk on twos, a side walker on threes); motion-auto's seam gate reads a held cut between its drawings, and a last drawing with a band of its body gone is over the limit. `tests/video/test_walk_steps.py`: the walker on threes with a tail on its own beat records its tried two-step cut within the seam gate between drawings, declined as out of phase; the search's cut stands as before.
+**Upgrading from 3.0.0: walk and run loops whose seam pop exceeds the bound are now refused by default.** The check is governed by `--seam-pop-max BOUND|off` (default 10). The flag `--seam-max` does not lift this gate. Callers that force delivery with `--seam-max 1000` or scan fixed cuts with lifted gates must add `--seam-pop-max off` beside `--seam-max 1000` to deliver what they delivered before. Callers matching failure lines by their first words need a rule for `video-loop: loop seam pop`. Loops that pass the gate, loops with an unreadable top band, and pinned clips produce the exact same files as before, save an `--anchor motion-auto` cut taken in place of a first choice the gate would have refused before the cut.
+
+- **Behavior change: seam pop is now a gate.** A walk or run loop whose `pop` is over the bound is refused, while a pop exactly at the bound passes. The gate applies to all walk or run loops gated by seam ratio (`--cycle fixed`, periodic searches, `--anchor motion-auto`, and `--repair off`), but does not gate pinned clips (`--cycle pinned`). The check runs after the seam gate and step gate; cuts refused by earlier gates fail with their existing lines. On refusal, the failure line is `video-loop: loop seam pop <pop> exceeds <bound> (<kind> length <L> frames from <start>): the top of the silhouette jumps into the loop's first frame up or down <percent> % of the body height, <ratio>x its median step — the loop does not close at its top; cut it where it does, or regenerate the clip`, detailing the pop, bound, cut, and directional jump metrics, without printing a warning line or adding to `jolt.warnings`. Loops whose top band cannot be read pass with verdict `unreadable` and retain their warning line. The flag `--seam-max` does not lift this gate, because seam pop measures top band placement rather than seam ratio distance.
+- **New: `--seam-pop-max` flag.** `video-loop --seam-pop-max BOUND|off` sets the seam pop bound. It defaults to 10 (`repair.SEAM_POP_REFERENCE`) and accepts any number over 0, or `off` to turn the gate off.
+- **Behavior change: `--anchor motion-auto` evaluates candidates for seam pop before cutting.** Before a cut is taken, candidate cuts are evaluated using `loop.corrected_cut` and `repair.seam_pop_of`. If the search cut would be refused, the engine evaluates up to four candidates (`local_cycle.SEAM_TRIES`) in search order (equivalent cuts earliest first, then remaining best first) and selects the first passing cut; if all four fail, the first choice stays and fails on the loop. For step counts, foot crossing cuts passing the seam gate are checked for pop, taking the first of four cuts that passes both gates. Every motion-auto run now corrects the search cut once before taking the cut.
+- **Report: `seam_pop_gate` record and step count fields.** Walk and run reports and CLI summaries add `seam_pop_gate` containing `verdict` (`passed`, `refused`, `unreadable`, `off`, or `not-applicable`), `max`, `pop`, and `why`. Failed reports include this record as well. Motion-auto searches record `cycle.seam_pop_gate` with `max`, `tried`, `applied`, and `why`. In addition, `step_count.seam_gate.tried` rows and `step_count.search` gain `pop`, `pop_gate`, and `pop_skipped`.
+- **Tests: synthetic and unit coverage.** Synthetic tests in `tests/video/test_seam_pop_gate.py` verify a standing rod walk where an 11 px tip drop reads a pop of 11.0 and is refused, while a 9 px drop reads 9.0 and passes. Tests confirm that bound 12 or `--seam-pop-max off` keeps the 11 px loop with identical files, `--seam-max 1000` alone does not keep it, unreadable tops pass as `unreadable`, pinned clips report `not-applicable`, and `--anchor motion-auto` switches from a cut with pop 6.0 (5.0 on twos) to a passing cut with pop 0.0 under bound 3. Unit tests cover `repair.seam_pop_gate`, `local_cycle._pop_gate`, `detect`, and `by_steps`. In `tests/video/test_loop_prop_seam.py`, fixed cuts with dropping staff tips are preserved under `--seam-pop-max off`.
+
## v3.0.0 - Remove rig layer composition
**Upgrading from 2.46.0: `sprite-gen compose-layers` and its other launch forms are removed, and rig layer declarations are no longer read.** `compose-atlas` no longer writes a manifest `rig` block or `animation.rows.<state>.track` for a run that declared a rig. Runs that never declared `rig`, `layers` or a state `track` get the same manifest as before. Existing run files and `layers/` folders stay on disk.
diff --git a/docs/loop-repair.md b/docs/loop-repair.md
index d5faae1..f23bd93 100644
--- a/docs/loop-repair.md
+++ b/docs/loop-repair.md
@@ -778,7 +778,7 @@ loop's report carries `jolt`, measured on the loop as it will play (after sectio
| `step_max_over_median` | the largest step over the median (what section 2 repairs) |
| `head.x`, `head.y` | the head's place frame by frame in % of the body's height over the loop: x (sideways) the coverage centroid of the top fifth, y (up and down) the body's top line. Each: `step_max_pct` (largest move in one frame), `step_median_pct`, `max_over_median`, `range_pct`, `worst_into_frame` |
| `reference`, `warnings` | the reference bounds (jolt index **0.43**, head sideways step **0.75** % of the body height) and what exceeds them, in words |
-| `seam_pop` | the top band's jump into the loop's first frame over the loop's median step ("The seam pop" below); a pop over its bound adds a line to `warnings` |
+| `seam_pop` | the top band's jump into the loop's first frame over the loop's median step ("The seam pop" below); a pop over `--seam-pop-max` refuses the loop, the gate's word in `seam_pop_gate` ("The seam pop gate" below). |
| `gate`, `gated`, `over`, `passed` | the bounds the caller passed, whether they were enforced, what exceeded them |
| `measured` | `after the jump repair` or `as filmed` |
@@ -786,7 +786,8 @@ loop's report carries `jolt`, measured on the loop as it will play (after sectio
lists the reason under `warnings`, and `video-loop` prints a
`video-loop: warning: … (reference bound; the loop is kept …)` line on stderr. The aim is fewer
refilms — section 2 repairs what it can without a new clip — and the reference bounds rest on
-too few judged takes to refilm on (below).
+too few judged takes to refilm on (below). The seam pop is the exception: it is a gate by default
+("The seam pop gate" below).
**A gate only when asked.** `--jolt-max` and/or `--head-step-max` turn the bound passed into a
gate on the repaired loop: beyond it the loop fails with
@@ -856,7 +857,8 @@ plays:
within the usual 15 % of the best and the smallest pop (`cycle.seam_pop`: `first_choice`,
`applied`, `measured`, `unread`, `chosen`). A first choice that does not pop is kept, and nothing past it
is measured, so a loop without such a part is cut exactly as before. If every candidate read pops,
- the first choice is kept (`why`) and the warning below says so. Once the first choice pops, the held
+ the first choice is kept (`why`), and the gate then reads it as every motion-auto cut is read before
+ it is cut ("The seam pop gate" below). Once the first choice pops, the held
part is read below its top too, and the cut may come out two steps long ("The held side" below).
- **A cut whose top cannot be read is not one that closes.** A frame with nothing in the top band
(a tip flung far above the rest in one frame) leaves the cut without a jump to read: it is
@@ -864,11 +866,13 @@ plays:
`seam_pop: null` with `seam_pop_skipped` — and counted under `unread`, apart from `measured`.
It is never chosen on; a first choice that cannot be read is kept, nothing past it is measured,
and `jolt.warnings` says the head could not be tracked.
-- **A pop that stays is a warning line** — `video-loop: warning: the top of the silhouette jumps
- into the loop's first frame up or down … (over 10x): a part held above the head swings on its
- own beat and does not close at this cut`, in `jolt.warnings` like the bounds above. A sideways
- jump into frame 0 that the head bound already names is not said twice. A fixed or `--cycle
- periodic` cut is not chosen again; the warning is all it gets. Nothing fails on it.
+- **A pop over the bound fails the loop:** a walk or run loop whose pop is over the bound is refused
+ ("The seam pop gate" below). When the gate refuses, the pop is not also printed as a warning line
+ and is not in `jolt.warnings`: the refusal says it. With the gate off, a pop over 10 is the warning
+ line `video-loop: warning: the top of the silhouette jumps into the loop's first frame up or down …
+ (over 10x): a part held above the head swings on its own beat and does not close at this cut` in
+ `jolt.warnings`, as before. A sideways jump into frame 0 that the head bound already names is not
+ said twice. A fixed or `--cycle periodic` cut is not chosen again, and the gate refuses it.
- **The bound** sits between walks holding a staff that swings on its own beat and walks without
one, both on the cut as it plays and on the source frames the cut is chosen from. The synthetic
walker of `tests/video/test_loop_prop_seam.py` — steps every 24 frames, a staff above its head swaying every 61 — reads 12 to 18 at the cuts the area
@@ -877,6 +881,26 @@ plays:
sword at the hip). The lower end of a staff whose top closes while the shaft still swings about the
hand is read by the held side below, behind this pop.
+### The seam pop gate
+
+The seam pop gate refuses any walk or run loop whose seam pop exceeds `--seam-pop-max BOUND|off` (default 10, the existing constant `repair.SEAM_POP_REFERENCE`). The metric `jolt.seam_pop` measures how far the top band of the silhouette (the head, or a part held above it such as a staff, a flag, or a raised spear) jumps from the loop's last frame into its first, over the loop's median step (`pop`), read on the loop as it plays, after jump repair. A pop exactly at the bound passes. The gate applies to every walk or run loop whose cut is gated by its seam ratio, whatever chose the cut (`--cycle fixed`, a periodic search, `--anchor motion-auto`) and whether or not the repair ran (`--repair off` included). When the gate refuses, the failure line is `video-loop: loop seam pop <pop> exceeds <bound> (<kind> length <L> frames from <start>): the top of the silhouette jumps into the loop's first frame up or down <percent> % of the body height, <ratio>x its median step — the loop does not close at its top; cut it where it does, or regenerate the clip`. It names the pop, the bound, the cut (kind, length, first frame) and, in words, how far and how many times its median step the top jumps, up or down and/or sideways: each axis whose largest step is the wrap and whose wrap is over the bound. The pop is not also printed as a warning line and is omitted from `jolt.warnings`.
+
+The report gains `seam_pop_gate` on every walk or run loop, printed in the CLI summary and retained in failed reports:
+
+| Field | What |
+|---|---|
+| `verdict` | `passed`, `refused`, `unreadable`, `off`, or `not-applicable` |
+| `max` | The bound, or `null` when off |
+| `pop` | The pop read, or `null` when unreadable |
+| `why` | Explains why the top band could not be read for `unreadable`, or `a pinned cut is gated by its pin` for `not-applicable` |
+
+- **Check order:** The seam pop gate is checked after the seam gate and the step gate. A cut those refuse is refused by them, with the same line as before.
+- **Unreadable top band:** A loop whose top band cannot be read (a frame with nothing in the top band, for example `a loop frame has no head to track`) is not refused: `seam_pop_gate.verdict` is `unreadable` with `why`, and the existing warning line that the head could not be tracked is still printed. It is never passed quietly.
+- **Pinned clips:** A pinned clip (`--cycle pinned`) is not gated by it: its gate is its pin, as for the seam ratio. Its verdict is `not-applicable`, with `why` set to `a pinned cut is gated by its pin`.
+- **Disabling and `--seam-max`:** `--seam-pop-max off` turns the gate off: the pop is reported, and a pop over 10 is the warning line `video-loop: warning: the top of the silhouette jumps into the loop's first frame up or down … (over 10x): a part held above the head swings on its own beat and does not close at this cut` as before. The flag `--seam-max` does not lift this gate. A `--seam-max` past 2.5 lifts the step gate and the fixed cut's step count refusal because those read the same distance the seam ratio reads; the seam pop reads the place of the top band, a measure in the family of `--jolt-max` and `--head-step-max`.
+- **Pre-cut checks under `--anchor motion-auto`:** Before a cut is taken, candidate cuts are read as the gate reads the loop, their frames corrected as the cut will be (`loop.corrected_cut`, one correction a cut for the seam and the pop: `loop.CutOnCells`) and checked for wrap jump (`repair.seam_pop_of`), short of jump repair. First, the search cut, after the top band has chosen again where it popped, is read; where the gate would refuse it, the next candidate in search order (equivalent cuts earliest first, then the rest best first) is read, taking the first of up to four cuts (`local_cycle.SEAM_TRIES`) the gate does not refuse. Where the gate would refuse all four, the first choice stays and the gate refuses it on the loop. This is recorded in `cycle.seam_pop_gate` (`max`, `tried`, `applied`, `why`). Second, among cuts of two steps chosen by foot crossings, cuts passing the seam gate are read for pop; the first of four cuts passing both gates is taken, adding `pop`, `pop_gate`, and `pop_skipped` to `step_count.seam_gate.tried` and `step_count.search`. Every motion-auto run corrects the search cut once before cutting it.
+- **Byte for byte identity and synthetic results:** With the gate off, or wherever the gate passes, the gate changes no cut and no file: loop files are byte for byte what the previous engine gives, save an `--anchor motion-auto` cut taken in place of a first choice the gate would have refused before the cut. In synthetic tests on a standing rod walk, a fixed cut whose tip drops 11 px reads a pop of 11.0 and is refused, while a 9 px drop reads 9.0 and passes. Under `--anchor motion-auto`, the pop read before the cut equals the loop's own reading (6.0 drawn a frame each, 5.0 on twos), allowing a bound of 3 to drop that cut for the next candidate with pop 0.0.
+
### The held side — a staff that closes at the top and swings below the hand
A staff turns about the hand as the arm that holds it swings: once a cycle, two steps. One step on
@@ -1034,7 +1058,11 @@ far the wrap is from joining the same point of the walk, in frames, the worst ov
whose seam the gate will pass is taken, read as the gate reads it before anything is cut
(`loop.seam_on_cells`: the cut corrected as it will be, its wrap over its step on the analysis
thumbnail; `step_count.seam_gate.tried`): the correction of one cut can leave a jump at its wrap that
- no reading of the clip shows. Each reading is a whole correction, six fine searches of the motion
+ no reading of the clip shows. For the cuts of two steps that foot crossings choose among, a cut whose
+ seam passes the seam gate is now read for its pop too: of the first four cuts, the first that both
+ gates pass is taken, the search's own cut stands only where both pass it, and
+ `step_count.seam_gate.tried` rows and `step_count.search` gain `pop`, `pop_gate`, and, where
+ unreadable, `pop_skipped` ("The seam pop gate" above). Each reading is a whole correction, six fine searches of the motion
anchor, and the cut taken is corrected once more, so a gate that tries all four corrects five cuts;
the search reads a row of its shifts at once, to the values one patch at a time gives ([loop
review](loop-review.md#explicit-xy-motion-correction)). A part on a beat of its own — a tail, a staff — that closes on no cut of
diff --git a/docs/loop-review.md b/docs/loop-review.md
index a86c3c0..7ba4385 100644
--- a/docs/loop-review.md
+++ b/docs/loop-review.md
@@ -202,7 +202,11 @@ section 3, "The seam pop"; `cycle.seam_pop`). A first choice whose top closes, o
nothing more is measured. Once it pops, the held part is read below its top as well, on the side
the top band sits on: a cut whose shaft closes under the hand is taken first, and where no cut one
step long closes it, a window two steps long — one cycle — is (`cycle.steps`, `strip.json`
-`steps: 2`; [loop repair](loop-repair.md) section 3, "The held side"). An explicit `--max-len` is
+`steps: 2`; [loop repair](loop-repair.md) section 3, "The held side"). Where the seam pop gate would
+refuse the cut so chosen, the next of the search's candidates in search order is read, and the first of
+up to four cuts the gate does not refuse is taken; if all four fail, the first choice stays and fails on
+the loop. See [loop repair](loop-repair.md) section 3, "The seam pop gate", recorded as
+`cycle.seam_pop_gate`. An explicit `--max-len` is
never widened, nor cut back to half the clip: an explicit window is the window, on every path that
sets a length (the count of steps and the one-shot failover below included), and a cut outside it
fails ([loop repair](loop-repair.md) section 3, "The step screen"). Without one, only
diff --git a/docs/video-pipeline.md b/docs/video-pipeline.md
index 2a2478c..c9e0beb 100644
--- a/docs/video-pipeline.md
+++ b/docs/video-pipeline.md
@@ -378,7 +378,7 @@ or more in under half a second, then walks at its new size. What it finds, and w
every `start` and `context_pair_range` in the report's `cycle`, refused candidates too, so a cut
taken again from them (`--cycle fixed --start`) is the frames they name. A cut the caller names (`fixed`, `pinned`) is the caller's frames, lead-in or not.
-Gates, all fail loud: no period (profile flat, below the recorded `periodicity_min`), loop seam ratio above `--seam-max` (2.0), GIF/WebP reopened and checked (frame count, `loop=0`, transparent corners, no RGB under alpha 0 in the WebP). On every walk or run loop that plays round, the step gate reads cells between drawings and refuses the loop when its largest step that is not a pixel's jitter, divided by the mean of the other steps, exceeds `STEP_RATIO_MAX` (2.5); a step is a pixel's jitter when aligning its drawing with the previous drawing takes at most `STEP_JITTER_PX` (1.5) pixels of the frames as filmed, measured by coverage so colour has no effect, and the step with that move taken back is within 2.5 of the mean. A fixed cut of a walk or run reads clip foot crossings to judge the cut, refusing an odd step count that would swap legs at the wrap. Both checks are lifted by `--seam-max` past 2.5; see `docs/loop-repair.md` section 3, "The step gate".
+Gates, all fail loud: no period (profile flat, below the recorded `periodicity_min`), loop seam ratio above `--seam-max` (2.0), GIF/WebP reopened and checked (frame count, `loop=0`, transparent corners, no RGB under alpha 0 in the WebP). On every walk or run loop that plays round, the step gate reads cells between drawings and refuses the loop when its largest step that is not a pixel's jitter, divided by the mean of the other steps, exceeds `STEP_RATIO_MAX` (2.5); a step is a pixel's jitter when aligning its drawing with the previous drawing takes at most `STEP_JITTER_PX` (1.5) pixels of the frames as filmed, measured by coverage so colour has no effect, and the step with that move taken back is within 2.5 of the mean. A fixed cut of a walk or run reads clip foot crossings to judge the cut, refusing an odd step count that would swap legs at the wrap. Both checks are lifted by `--seam-max` past 2.5; see `docs/loop-repair.md` section 3, "The step gate". Every walk or run loop gated by its seam ratio (not a pinned clip) is also refused when the top of its silhouette (the head, or a part held above it) jumps into the loop's first frame more than `--seam-pop-max` times its median step (default 10; `jolt.seam_pop.pop`, read on the loop as it plays); a top that cannot be read is not refused (`seam_pop_gate` says `unreadable`). `--seam-max` does not lift this gate; `--seam-pop-max off` turns it off, leaving a warning line as before; see `docs/loop-repair.md` section 3, "The seam pop gate".
See [loop repair](loop-repair.md).
diff --git a/sprite_gen/video/local_cycle.py b/sprite_gen/video/local_cycle.py
index aa46070..d1d5535 100644
--- a/sprite_gen/video/local_cycle.py
+++ b/sprite_gen/video/local_cycle.py
@@ -213,12 +213,48 @@ def _shape_rank(candidates, chosen, wrap_pop, held_edge=None, length_cap=None, d
return picked, record
-def counted(distances, trajectory, *, min_len, max_len, periodicity_min, signals=None):
+def _pop_said(read):
+ """A cut's top band at the wrap as the seam pop gate reads it before the cut (`pop_gate`), for the record: the pop,
+ and the gate's word — `refused` over its bound, `passed`, or `unreadable` (`pop_skipped`, why), which it does not
+ refuse."""
+ if 'skipped' in read:
+ return {'pop': None, 'pop_skipped': read['skipped'], 'pop_gate': 'unreadable'}
+ return {'pop': read['pop'], 'pop_gate': 'refused' if read['over'] else 'passed'}
+
+
+def _pop_gate(chosen, rest, pop_gate):
+ """The seam pop gate before the cut. `pop_gate(start, length)` reads a cut's top band at the wrap as the gate reads
+ the loop — its frames corrected as the cut will be (loop.CutOnCells): `{'pop', 'over', 'max'}`, or `{'skipped',
+ 'max'}` where the top band cannot be read, which the gate does not refuse. The chosen cut is read first; where the
+ gate would refuse it, the next of `rest` (in the caller's order), and the first of SEAM_TRIES the gate does not
+ refuse is taken — as `by_steps` takes the first two-step cut its seam gate passes. Where it would refuse them all,
+ the first choice stays, and the gate refuses it on the loop. Returns (the cut, the record: `max`, `tried`,
+ `applied`, and `why` where none passed)."""
+ tried = []
+ picked = None
+ bound = None
+ for row in [chosen, *rest][:SEAM_TRIES]:
+ read = pop_gate(row['start'], row['length'])
+ bound = read['max']
+ tried.append({'start': row['start'], 'length': row['length'], **_pop_said(read)})
+ if tried[-1]['pop_gate'] != 'refused':
+ picked = row
+ break
+ record = {'max': bound, 'tried': tried, 'applied': picked is not None and picked is not chosen}
+ if picked is None:
+ record['why'] = (f"the gate refuses each of the {len(tried)} cuts read: the first choice is kept, and the gate "
+ "refuses it on the loop")
+ picked = chosen
+ return picked, record
+
+
+def counted(distances, trajectory, *, min_len, max_len, periodicity_min, signals=None, pop_gate=None):
"""A cut of a length someone counted (`video-loop --steps`) where the clip is too short to see a
window that long repeat (`detect` found none): the counted length stands for the repeat. Every
window [min_len, max_len] long with two clip frames before it is read, and the one whose wrap is
nearest the clip's own way on there is taken (`_closure`, the earliest on a tie); whether it closes
- is the seam gate's word. Raises ValueError where no window has room."""
+ is the seam gate's word. With `pop_gate`, a window the seam pop gate would refuse gives way to the next nearest
+ (`_pop_gate`, `seam_pop_gate`). Raises ValueError where no window has room."""
n = len(distances)
rows = []
for length in range(min_len, max_len+1):
@@ -236,8 +272,9 @@ def counted(distances, trajectory, *, min_len, max_len, periodicity_min, signals
if not rows:
raise ValueError(f"no window {min_len}-{max_len} frames long has two clip frames before it in {n}")
rows.sort(key=lambda row: (row['closure'], row['start'], row['length']))
- chosen = rows[0]
+ chosen, gate = _pop_gate(rows[0], rows[1:], pop_gate) if pop_gate is not None else (rows[0], None)
return {**chosen, 'kind': 'periodic', 'method': 'counted-window-v1',
+ **({'seam_pop_gate': gate} if gate is not None else {}),
'repeat': 'not seen in the clip: the counted length stands for it', 'choice': 'closure',
'period_global': None, 'periodicity_min': periodicity_min, 'review_recommended': True,
'candidate_count': len(rows), 'candidates': rows[:REFUSED_SHOWN],
@@ -270,10 +307,15 @@ def judged(rows, judge):
def detect(distances, trajectory, *, min_len, max_len, gait_floor,
periodicity_min, double_tolerance, double_search, max_fraction=.5, signals=None, wrap_pop=None,
- held_edge=None, length_cap=None, double=True, closure=False, judge=None):
+ held_edge=None, length_cap=None, double=True, closure=False, judge=None, pop_gate=None):
"""`wrap_pop(start, length)`, when given, is the top band's jump at that cut's wrap
(repair.seam_pop): a chosen cut that pops is chosen again (`_shape_rank`), and a search that finds
nothing raises with the windows it refused, popping ones last (`ValueError.diagnostics`).
+
+ `pop_gate(start, length)`, when given, is the seam pop gate's reading of a cut before it is cut (`_pop_gate`): the
+ cut chosen — after `_shape_rank` — that the gate would refuse gives way to the next of the candidates in the
+ search's order (the equivalent ones earliest first, then the rest best first), the first of SEAM_TRIES the gate
+ does not refuse (`seam_pop_gate` in the result).
`held_edge` (loop.HeldEdge) reads the held side below the top of a cut chosen again; the cut it
takes may be two lengths long (`steps` in the result: two steps, one cycle), but never longer than
`length_cap`, nor with `double` false.
@@ -404,6 +446,12 @@ def detect(distances, trajectory, *, min_len, max_len, gait_floor,
shape = None
if wrap_pop is not None:
chosen, shape = _shape_rank(candidates, chosen, wrap_pop, held_edge, length_cap, double)
+ gate = None
+ if pop_gate is not None:
+ rest = sorted((row for row in candidates if (row['start'], row['length']) != (chosen['start'], chosen['length'])),
+ key=lambda row: ((0, row['start'], row['score'], row['length']) if row['score'] <= cutoff
+ else (1, row['score'], row['start'], row['length'])))
+ chosen, gate = _pop_gate(chosen, rest, pop_gate)
if 'ratio' not in chosen:
# A window two lengths long (`_held_rank`) was not a candidate: its wrap over its step, as a candidate's.
s, L = chosen['start'], chosen['length']
@@ -418,6 +466,7 @@ def detect(distances, trajectory, *, min_len, max_len, gait_floor,
'candidates': candidates[:12],
**({'choice': 'closure'} if closure else {}),
**({'seam_pop': shape} if shape is not None else {}),
+ **({'seam_pop_gate': gate} if gate is not None else {}),
'step_screen': steps,
}
@@ -480,8 +529,14 @@ def _rank(rows, *, flow_limit, seam_max, in_phase):
return band + rest, len(band)
+def _gates(tried, seam_max):
+ """A cut read before it is cut passes its seam gate (`seam` at most `seam_max`) and the seam pop gate does not
+ refuse it (`pop_gate`, where it was read)."""
+ return tried['seam'] <= seam_max and tried.get('pop_gate') != 'refused'
+
+
def by_steps(distances, trajectory, reading, *, found, refused, min_len, max_len, seam_flow, wrap_pop, seam_gate, flow_limit,
- seam_max, gait_floor, periodicity_min, signals):
+ seam_max, gait_floor, periodicity_min, signals, pop_gate=None):
"""The cut the clip's own steps choose (`reading`, crossings.Reading), after the pixel search: `found`, its cut,
or `refused`, why it found none. Returns (the cut, or None where the search's word stands and it found none;
`step_count`, the record).
@@ -510,6 +565,10 @@ def by_steps(distances, trajectory, reading, *, found, refused, min_len, max_len
it does not close). A search's cut the gate refuses too gives way as before: the two-step cut's wrap may still
be closed by the overlapped wrap (repair.overlap_wrap), and the gate says whether it is.
+ With `pop_gate` (the seam pop gate's reading before the cut, `_pop_gate`), a cut the seam gate passes is read for
+ its top band too, and passes only where the seam pop gate would not refuse it: of the two-step cuts the first
+ that passes both is taken, and the search's cut stands only where both pass it (`pop`, `pop_gate` beside `seam`).
+
A cut taken on two steps records `steps` (count 2, by crossings): `video-cycle-align` reads a return half way
as its step, and the step screen's pixel suspicion of one step (`step_screen`) is settled, kept as
`pixel_suspect`."""
@@ -553,9 +612,11 @@ def by_steps(distances, trajectory, reading, *, found, refused, min_len, max_len
tried = []
for row in ranked[:SEAM_TRIES]:
tried.append({'start': row['start'], 'length': row['length'], 'seam': round(seam_gate(row['start'], row['length']), 3)})
- if tried[-1]['seam'] <= seam_max:
+ if pop_gate is not None and tried[-1]['seam'] <= seam_max:
+ tried[-1].update(_pop_said(pop_gate(row['start'], row['length'])))
+ if _gates(tried[-1], seam_max):
break
- passed = [t for t in tried if t['seam'] <= seam_max]
+ passed = [t for t in tried if _gates(t, seam_max)]
picked = next(row for row in ranked if (row['start'], row['length']) == ((passed[0]['start'], passed[0]['length']) if passed
else (tried[0]['start'], tried[0]['length'])))
record['seam_gate'] = {'max': seam_max, 'tried': tried}
@@ -564,7 +625,9 @@ def by_steps(distances, trajectory, reading, *, found, refused, min_len, max_len
# A cut the count does not refute, and the seam gate passes, stands until a two-step cut closes in its place.
own = round(seam_gate(found['start'], found['length']), 3)
record['search']['seam'] = own
- if own <= seam_max:
+ if pop_gate is not None and own <= seam_max:
+ record['search'].update(_pop_said(pop_gate(found['start'], found['length'])))
+ if _gates(record['search'], seam_max):
record.update(chosen_by='search', cut=searched, flow_limit=flow_limit, seam_max=seam_max, declined={
'cut': [start, length], 'phase': picked['phase'], 'gated': ranked.index(picked) < band,
'seam': next(t['seam'] for t in tried if (t['start'], t['length']) == (start, length))})
diff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.py
index 569e558..e6ccec9 100644
--- a/sprite_gen/video/loop.py
+++ b/sprite_gen/video/loop.py
@@ -1345,18 +1345,59 @@ class SeamFlow:
"window": [[round(v, 3) for v in scores["windows"][int(scores["window"][k])]] for k in at]}
+def corrected_cut(frames: list[Image.Image]) -> list[Image.Image]:
+ """A motion-auto cut's frames corrected as the cut will be (`auto_motion.discover`, `auto_motion.correct_cycle`,
+ as `run_loop` corrects the cut it takes). Raises ValueError where they cannot be."""
+ regions, _ = auto_motion.discover(frames, reference_index=0)
+ frames, _ = auto_motion.correct_cycle(frames, regions, coarse_dx=body_wrap_offset(frames, search=motion_anchor.COARSE_SEARCH))
+ return frames
+
+
def seam_on_cells(frames: list[Image.Image]) -> float:
"""The seam gate's reading of a motion-auto cut before it is cut: its frames corrected as the cut will be
- (`auto_motion.discover`, `auto_motion.correct_cycle`), then read as `wrap_on_cells` reads them.
- Infinite where the frames cannot be corrected."""
+ (`corrected_cut`), then read as `wrap_on_cells` reads them. Infinite where the frames cannot be corrected."""
try:
- regions, _ = auto_motion.discover(frames, reference_index=0)
- frames, _ = auto_motion.correct_cycle(frames, regions, coarse_dx=body_wrap_offset(frames, search=motion_anchor.COARSE_SEARCH))
+ frames = corrected_cut(frames)
except ValueError:
return math.inf
return wrap_on_cells(frames)
+class CutOnCells:
+ """A motion-auto cut (`start`, `length` of `frames`) read before it is cut as the gates read the loop: its frames
+ corrected as the cut will be (`corrected_cut`), then its seam (`seam`, as `seam_on_cells` reads it) and the top band's
+ jump into its first frame (`pop`, `repair.seam_pop_of`: the seam pop gate's reading, `jolt.seam_pop`), short of the
+ jump repair, which runs on the cut once it is taken. A cut is corrected once, whichever is read first, and none of
+ its frames is kept. `gate` is `pop` for `local_cycle` (`pop_gate`), or None where the seam pop gate is off."""
+
+ def __init__(self, frames: list[Image.Image], *, pop_max: float | None):
+ self.frames, self.pop_max = frames, pop_max
+ self._read: dict[tuple[int, int], tuple[float, dict[str, Any]]] = {}
+
+ def _of(self, start: int, length: int) -> tuple[float, dict[str, Any]]:
+ if (start, length) not in self._read:
+ try:
+ cut = corrected_cut(self.frames[start:start + length])
+ except ValueError as exc:
+ self._read[start, length] = (math.inf, {"skipped": f"the cut's frames could not be corrected ({exc})"})
+ else:
+ self._read[start, length] = (wrap_on_cells(cut), repair_mod.seam_pop_of(cut))
+ return self._read[start, length]
+
+ def seam(self, start: int, length: int) -> float:
+ return self._of(start, length)[0]
+
+ def pop(self, start: int, length: int) -> dict[str, Any]:
+ measured = self._of(start, length)[1]
+ if "skipped" in measured:
+ return {"skipped": measured["skipped"], "max": self.pop_max}
+ return {"pop": measured["pop"], "over": self.pop_max is not None and measured["pop"] > self.pop_max, "max": self.pop_max}
+
+ @property
+ def gate(self) -> Any:
+ return self.pop if self.pop_max is not None else None
+
+
def cells_box(frames: list[Image.Image]) -> tuple[int, int, int, int]:
"""The union box of a loop's frames, every pixel not fully transparent: the crop its rendered cells are read on."""
boxes = [f.getbbox() for f in frames]
@@ -1512,9 +1553,10 @@ def cycle_apart(files: list[Path], *, start: int, length: int, skip: int, analys
def _by_steps(cycle: dict[str, Any] | None, refused: ValueError | None, *, frames: list[Image.Image], analysis: dict[str, Any],
D: np.ndarray, trajectory: np.ndarray, window: CutWindow, searched: dict[str, Any], detect: dict[str, Any],
- seam_max: float) -> dict[str, Any]:
+ seam_max: float, cells: CutOnCells) -> dict[str, Any]:
"""The cut the clip's own steps choose (`local_cycle.by_steps`, the crossings of the frames the search read,
sprite_gen/video/crossings.py), recorded `step_count`, from the search's cut or its refusal (`refused`).
+ `cells` reads a cut of `frames` before it is cut as the seam gate and the seam pop gate read the loop.
Where the clip shows its steps but no cut of two, and the search's cut is one they refute (one step, three), the
search runs again on the window it searched (`searched`) refusing such cuts (`detect`'s `judge`). A search that
@@ -1527,14 +1569,14 @@ def _by_steps(cycle: dict[str, Any] | None, refused: ValueError | None, *, frame
moved = moved_alpha(frames, analysis)
picked, record = local_cycle.by_steps(
D, trajectory, reading, found=cycle, refused=refused, min_len=window.lo, max_len=window.max_len or len(frames),
- seam_flow=SeamFlow(frames, analysis), wrap_pop=wrap_pop_on(moved), seam_gate=lambda s, L: seam_on_cells(frames[s:s + L]),
+ seam_flow=SeamFlow(frames, analysis), wrap_pop=wrap_pop_on(moved), seam_gate=cells.seam, pop_gate=cells.gate,
flow_limit=repair_mod.FLOW_LIMIT, seam_max=seam_max,
gait_floor=detect["gait_floor"], periodicity_min=detect["periodicity_min"], signals=signals)
if picked is not None and record.get("cut", {}).get("verdict") == "refuted":
first = record["cut"]
try:
picked = local_cycle.detect(D, trajectory, signals=signals, wrap_pop=wrap_pop_on(moved), held_edge=HeldEdge(moved),
- length_cap=window.max_len, judge=reading.judge, **searched, **detect)
+ length_cap=window.max_len, judge=reading.judge, pop_gate=cells.gate, **searched, **detect)
except ValueError as exc:
picked, refused = None, exc
record["searched_again"] = {"refuted": first, "why": f"no cut of two steps, and the search's cut is {first['why']}: "
@@ -1564,7 +1606,7 @@ def _by_steps(cycle: dict[str, Any] | None, refused: ValueError | None, *, frame
def _counted(cycle: dict[str, Any], steps: int, *, window: CutWindow, D: np.ndarray, trajectory: np.ndarray,
- frames: list[Image.Image], moved: list[np.ndarray], detect: dict[str, Any]) -> dict[str, Any]:
+ frames: list[Image.Image], moved: list[np.ndarray], detect: dict[str, Any], cells: CutOnCells) -> dict[str, Any]:
"""The cut once its steps are counted (`--steps`): 2 keeps it; 1 cuts again in the window two of
its lengths long, [2L-1, 2L+1], inside the caller's bounds (`window.within`) — not half the clip —
with the same search (a repeat seen in the clip, the top band and the held side read again) save that
@@ -1592,11 +1634,13 @@ def _counted(cycle: dict[str, Any], steps: int, *, window: CutWindow, D: np.ndar
signals = leg_signals(frames)
try:
found = local_cycle.detect(D, trajectory, min_len=lo, max_len=hi, length_cap=hi, signals=signals,
- wrap_pop=wrap_pop_on(moved), held_edge=HeldEdge(moved), double=False, closure=True, **detect)
+ wrap_pop=wrap_pop_on(moved), held_edge=HeldEdge(moved), double=False, closure=True,
+ pop_gate=cells.gate, **detect)
except ValueError as unseen:
# Too short a clip to see the cycle repeat: the count stands for it (`cycle.coverage` says how short).
try:
- found = local_cycle.counted(D, trajectory, min_len=lo, max_len=hi, periodicity_min=detect["periodicity_min"], signals=signals)
+ found = local_cycle.counted(D, trajectory, min_len=lo, max_len=hi, periodicity_min=detect["periodicity_min"],
+ signals=signals, pop_gate=cells.gate)
except ValueError as exc:
failed = ValueError(f"--steps 1: the cut of {first['length']} frames from {first['start']} is one step, and the clip "
f"({len(D)} frames) has no window {lo}-{hi} frames long to cut: {exc}")
@@ -1688,6 +1732,7 @@ def run_loop(
overlap_wrap: str = "on",
wrap_blend: str = "auto",
unfixed: str = "warn",
+ seam_pop_max: float | None = repair_mod.SEAM_POP_REFERENCE,
) -> dict[str, Any]:
state = state.strip().lower() if state else state
if state == effect.STATE:
@@ -1723,6 +1768,8 @@ def run_loop(
raise SystemExit(f"video-loop: unknown --unfixed {unfixed!r}; expected one of {', '.join(UNFIXED_MODES)}")
if facing not in FACINGS:
raise SystemExit(f"video-loop: unknown --facing {facing!r}; expected one of {', '.join(FACINGS)}")
+ if seam_pop_max is not None and not (math.isfinite(seam_pop_max) and seam_pop_max > 0):
+ raise SystemExit(f"video-loop: --seam-pop-max {seam_pop_max}: a bound over 0, or off")
if anchor is None:
# gaits drift a few pixels over a cycle and the wrap shows it; in-place states do not
anchor = "body" if profile_for(state).gait else "none"
@@ -1814,10 +1861,13 @@ def run_loop(
double_tolerance=GAIT_DOUBLE_TOL, double_search=GAIT_DOUBLE_SEARCH)
searched: dict[str, Any] = {"min_len": lo, "max_len": hi}
refused: ValueError | None = None
+ # The cuts the search chooses among, read before one is cut as the seam gate and the seam pop gate read the loop.
+ cells = CutOnCells(source_frames, pop_max=seam_pop_max)
try:
moved = moved_alpha(source_frames, analysis)
cycle = local_cycle.detect(D, trajectory, min_len=lo, max_len=hi, signals=leg_signals(source_frames),
- wrap_pop=wrap_pop_on(moved), held_edge=HeldEdge(moved), length_cap=window.max_len, **detect)
+ wrap_pop=wrap_pop_on(moved), held_edge=HeldEdge(moved), length_cap=window.max_len,
+ pop_gate=cells.gate, **detect)
except ValueError as first:
# A front or back gait that walked toward the camera, or a slow one: one more
# search, recorded (`gait_fallback`), and only after the first found nothing.
@@ -1831,6 +1881,7 @@ def run_loop(
D, trajectory, analysis = auto_motion.analyse(source_frames, fps=fps)
report_base["automatic_motion_analysis"] = analysis
fallback["scale_undone"] = True
+ cells = CutOnCells(source_frames, pop_max=seam_pop_max)
# An explicit --max-len is the caller's ceiling and stays one.
hi_long = window.past(gait_fallback.long_window(lo, len(files), fps))
fallback["window"] = [lo, hi_long]
@@ -1841,7 +1892,7 @@ def run_loop(
cycle = local_cycle.detect(D, trajectory, min_len=lo, max_len=hi_long,
max_fraction=gait_fallback.LONG_CYCLE_FRACTION,
signals=leg_signals(source_frames), wrap_pop=wrap_pop_on(moved),
- held_edge=HeldEdge(moved), length_cap=window.max_len, **detect)
+ held_edge=HeldEdge(moved), length_cap=window.max_len, pop_gate=cells.gate, **detect)
except ValueError as second:
failed = ValueError(f"{second} (also with the gait fallback: window [{lo}, {hi_long}], "
f"scale drift {drift['drift']:+.1%}{', undone' if fallback['scale_undone'] else ''})")
@@ -1854,10 +1905,11 @@ def run_loop(
# A count given is the word on the search's cut; the crossings are not asked.
if refused is not None:
raise refused
- cycle = _counted(cycle, steps, window=window, D=D, trajectory=trajectory, frames=source_frames, moved=moved, detect=detect)
+ cycle = _counted(cycle, steps, window=window, D=D, trajectory=trajectory, frames=source_frames, moved=moved,
+ detect=detect, cells=cells)
else:
cycle = _by_steps(cycle, refused, frames=source_frames, analysis=analysis, D=D, trajectory=trajectory,
- window=window, searched=searched, detect=detect, seam_max=seam_max)
+ window=window, searched=searched, detect=detect, seam_max=seam_max, cells=cells)
elif cycle_mode == "once":
source_frames = [Image.open(f).convert("RGBA") for f in files]
cycle = nonloop.select_cut(D, masses, fps=fps, ending=partial(
@@ -2100,8 +2152,16 @@ def run_loop(
# whose repair could not run (no RIFE) is gated as filmed, and the failure says why.
jolt = repair_mod.measure_jolt(frames, facing=facing)
reference = {"jolt_max": repair_mod.JOLT_REFERENCE, "head_step_max": repair_mod.HEAD_STEP_REFERENCE}
+ # The seam pop is a gate where the seam ratio gates the cut — not a pinned clip, whose gate is its pin — read on
+ # the loop as it plays, whatever cut it and whether the repair ran. Its word is given after the seam and step
+ # gates (below), so a cut they refuse is refused in their line.
+ report_base["seam_pop_gate"] = (
+ repair_mod.seam_pop_gate(jolt["seam_pop"], pop_max=seam_pop_max) if cycle["kind"] not in ("pinned", *nonloop.KINDS)
+ else {"verdict": "not-applicable", "why": f"a {cycle['kind']} cut is gated by its pin"})
warnings = repair_mod.jolt_verdict(jolt, **reference)
- warnings += repair_mod.seam_pop_verdict(jolt, head_step_max=repair_mod.HEAD_STEP_REFERENCE)
+ if report_base["seam_pop_gate"]["verdict"] != "refused":
+ # A pop the gate refuses is said in its refusal, not in a line that keeps the loop.
+ warnings += repair_mod.seam_pop_verdict(jolt, head_step_max=repair_mod.HEAD_STEP_REFERENCE)
# The held side below the top, read on the source frames when the cut was chosen again (local_cycle).
warnings += repair_mod.held_edge_verdict(cycle.get("seam_pop"))
warnings += coverage_verdict(cycle)
@@ -2343,6 +2403,19 @@ def run_loop(
print(f"video-loop: warning: the loop's largest step between drawings is {ratio:.2f}x their mean (into frame "
f"{read['largest_into']}), over {STEP_RATIO_MAX:g}: it jumps inside — kept, as --seam-max {seam_max:g} "
"lifts the step gate", file=sys.stderr)
+ popped = report_base.get("seam_pop_gate")
+ if popped is not None and popped["verdict"] == "refused":
+ # The top of the loop — the head, or a part held above it — jumps at the wrap: the loop does not close there,
+ # whatever its seam ratio, an area measure, says. Not lifted by --seam-max: --seam-pop-max off turns it off.
+ error = (f"video-loop: loop seam pop {popped['pop']:.2f} exceeds {popped['max']:g} ({cycle['kind']} length {L} frames "
+ f"from {i}): the top of the silhouette jumps into the loop's first frame "
+ f"{repair_mod.seam_pop_words(report_base['jolt']['seam_pop'], popped['max'])} — the loop does not close at "
+ "its top; cut it where it does, or regenerate the clip")
+ refuse(target, out_dir, name, {**report_base, "status": "failed", "error": error, "cycle": cycle,
+ "periodic_attempt": periodic_attempt, "resampled_seam": resampled_seam,
+ "resampled_inner_mean_adjacent": resampled_adjacent,
+ "resampled_seam_ratio": seam_ratio}, cut_written=True)
+ raise SystemExit(error)
# GIF has binary transparency. Bake the effect onto its declared black preview
# background instead of turning its faint partial-alpha glow into opaque dark pixels.
gif_background = "#000000" if cycle["kind"] == "lifetime" else None
@@ -2398,6 +2471,19 @@ def run_loop(
return payload
+def _seam_pop_max(value: str) -> float | None:
+ """`--seam-pop-max`: a bound over 0, or `off` (None)."""
+ if value.strip().lower() == "off":
+ return None
+ try:
+ bound = float(value)
+ except ValueError:
+ raise argparse.ArgumentTypeError(f"{value!r}: a bound over 0, or off") from None
+ if not (math.isfinite(bound) and bound > 0):
+ raise argparse.ArgumentTypeError(f"{value!r}: a bound over 0, or off")
+ return bound
+
+
def add_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--frames-dir", required=True, type=Path, help="keyed RGBA frames from `sprite-gen video-frames` (…/keyed)")
parser.add_argument("--out-dir", required=True, type=Path)
@@ -2421,6 +2507,14 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--unfixed", choices=UNFIXED_MODES, default="warn", help="walk/run, under --repair auto or on: a frame the jump repair leaves off the walk's flow — no group of up to two drawings brings it back, or the group that would was refused (its RIFE frame had a fault) — is recorded in jump_repair.unfixed; warn (default): a warning line, the loop kept; refuse: the loop fails")
parser.add_argument("--jolt-max", type=float, default=None, help=f"walk/run: fail the repaired loop when its jolt index (how far each step strays from its neighbours' mean, over the median step) exceeds this. Default: no gate — the index is reported and a value over {repair_mod.JOLT_REFERENCE} is a warning line")
parser.add_argument("--head-step-max", type=float, default=None, help=f"walk/run: fail the repaired loop when the head's largest sideways move in one frame exceeds this %% of the body height. Default: no gate — reported, and over {repair_mod.HEAD_STEP_REFERENCE} is a warning line")
+ parser.add_argument("--seam-pop-max", type=_seam_pop_max, default=repair_mod.SEAM_POP_REFERENCE, metavar="BOUND|off",
+ help=f"walk/run: fail the loop when the top of the silhouette (the head, or a part held above it) jumps into "
+ f"its first frame more than this many times its median step (`jolt.seam_pop`, read on the loop as it "
+ f"plays; default {repair_mod.SEAM_POP_REFERENCE:g}), a cut fixed by hand as one --anchor motion-auto "
+ "chooses — which reads the cuts it chooses among the same way and takes the next where the gate would "
+ "refuse the first. A top that cannot be read is not refused (`seam_pop_gate: unreadable`); a pinned "
+ f"cut is gated by its pin. --seam-max does not lift it. off: no gate — over {repair_mod.SEAM_POP_REFERENCE:g} "
+ "is a warning line (docs/loop-repair.md section 3, \"The seam pop\")")
parser.add_argument("--facing", choices=FACINGS, default="right", help="which way the body faces in the frames (default right): the jolt index's hair, and the size reading video-loop-compare's jump guard reads, are behind it; the jump repair reads the flow either way")
parser.add_argument("--size-hold", choices=SIZE_HOLD_MODES, default="auto", help="--anchor motion-auto: auto (default) scales a clip whose height, read one cycle on (the same pose a cycle later), changes by 1 %% or more over the clip back to its first frame's size before the cycle search, so the loop's last frame is the size of its first (recorded as size_hold, with the evidence); off: search the frames as filmed")
parser.add_argument("--steps", type=int, choices=STEPS, default=None,
@@ -2450,6 +2544,7 @@ def run(**kwargs: object) -> int:
size_hold=str(kwargs.get("size_hold") or "auto"), steps=kwargs.get("steps"), # type: ignore[arg-type]
overlap_wrap=str(kwargs.get("overlap_wrap") or "on"), wrap_blend=str(kwargs.get("wrap_blend") or "auto"),
unfixed=str(kwargs.get("unfixed") or "warn"),
+ seam_pop_max=kwargs.get("seam_pop_max", repair_mod.SEAM_POP_REFERENCE), # type: ignore[arg-type]
)
summary = {k: payload[k] for k in ("state", "frames_total", "window", "cycle_seconds", "n_out", "delay_ms", "resampled_seam_ratio", "specks_dropped", "report")}
summary["cycle"] = {k: payload["cycle"].get(k) for k in ("kind", "start", "length", "period_global", "ratio", "review_recommended", "half_period_guard", "fundamental")}
@@ -2467,6 +2562,10 @@ def run(**kwargs: object) -> int:
"seam_pop": payload["jolt"]["seam_pop"].get("pop")}
if payload["cycle"].get("seam_pop", {}).get("applied"):
summary["cycle"]["seam_pop"] = payload["cycle"]["seam_pop"]
+ if payload["cycle"].get("seam_pop_gate", {}).get("applied"):
+ summary["cycle"]["seam_pop_gate"] = payload["cycle"]["seam_pop_gate"]
+ if payload.get("seam_pop_gate"):
+ summary["seam_pop_gate"] = payload["seam_pop_gate"]
if "steps" in payload["cycle"]:
summary["cycle"]["steps"] = payload["cycle"]["steps"]
summary["cycle"]["coverage"] = payload["cycle"]["coverage"]
diff --git a/sprite_gen/video/repair.py b/sprite_gen/video/repair.py
index 8c15a11..496e484 100644
--- a/sprite_gen/video/repair.py
+++ b/sprite_gen/video/repair.py
@@ -1425,8 +1425,9 @@ HEAD_MEDIAN_FLOOR = 0.05 # % of body height: a median step below this is the tr
# The top band's step into the loop's first frame, over the loop's median step, beyond which the
# wrap pops (docs/loop-repair.md section 3, "The seam pop"). It sits between walks holding a part
# that sways on its own beat and walks without one, on the cut as it plays and on the source frames
-# the cut is chosen from. Above it the cut is chosen again (`--anchor motion-auto`), and a pop that
-# stays is a warning line.
+# the cut is chosen from. Above it the cut is chosen again (`--anchor motion-auto`), and it is the
+# seam pop gate's default bound (`video-loop --seam-pop-max`): a loop that pops over it is refused,
+# with the gate off a warning line.
SEAM_POP_REFERENCE = 10.0
# The held side's seam (docs/loop-repair.md section 3, "The held side"): a held part that swings on
# its own beat misses below its top too — under the hand, where the top band does not reach. Read
@@ -1525,6 +1526,15 @@ def seam_pop(alphas: list[np.ndarray]) -> dict[str, Any]:
return record
+def seam_pop_of(frames: list[Image.Image]) -> dict[str, Any]:
+ """`seam_pop` of a loop's frames read as `measure_jolt` reads the loop (their alpha in their union box), or
+ `skipped` (why) where the top band cannot be read."""
+ try:
+ return seam_pop(coverage(frames, union_box(frames)))
+ except ValueError as exc:
+ return {"skipped": str(exc)}
+
+
def held_side(masks: list[np.ndarray]) -> str:
"""The side of the body the top band (HEAD_BAND) sits on, "left" or "right": where a part held
higher than the head is held. `masks` are a cut's frames, True where the body is."""
@@ -1653,12 +1663,34 @@ def seam_pop_verdict(measured: dict[str, Any], *, head_step_max: float | None =
and pop[axis]["wrap_over_median"] > pop["reference"] and not (axis == "x" and said)]
if not axes:
return []
- words = {"x": "sideways", "y": "up or down"}
- return ["the top of the silhouette jumps into the loop's first frame "
- + ", ".join(f"{words[a]} {v['wrap_pct']:.2f} % of the body height, {v['wrap_over_median']:.1f}x its median step" for a, v in axes)
+ return ["the top of the silhouette jumps into the loop's first frame " + _pop_axes(axes)
+ f" (over {pop['reference']:g}x): a part held above the head swings on its own beat and does not close at this cut"]
+def _pop_axes(axes: list[tuple[str, dict[str, Any]]]) -> str:
+ words = {"x": "sideways", "y": "up or down"}
+ return ", ".join(f"{words[a]} {v['wrap_pct']:.2f} % of the body height, {v['wrap_over_median']:.1f}x its median step" for a, v in axes)
+
+
+def seam_pop_gate(pop: dict[str, Any], *, pop_max: float | None) -> dict[str, Any]:
+ """The seam pop as a gate (section 3, "The seam pop"): `pop` (`seam_pop`, or `skipped`) against `pop_max`
+ (`video-loop --seam-pop-max`, SEAM_POP_REFERENCE by default; None: off). `verdict` is `refused` where the pop is
+ over `pop_max`, `passed` where it is not, `unreadable` where the top band could not be read — not refused, and
+ `why` says it — and `off` with the pop as read."""
+ if pop_max is None:
+ return {"verdict": "off", "max": None, "pop": pop.get("pop")}
+ if "skipped" in pop:
+ return {"verdict": "unreadable", "max": pop_max, "pop": None, "why": pop["skipped"]}
+ return {"verdict": "refused" if pop["pop"] > pop_max else "passed", "max": pop_max, "pop": pop["pop"]}
+
+
+def seam_pop_words(pop: dict[str, Any], pop_max: float) -> str:
+ """Where the top band jumps into the loop's first frame over `pop_max` times its median step, in words: each axis
+ whose largest step is the wrap and over the bound, how far (% of the body height) and how many times its step."""
+ return _pop_axes([(axis, pop[axis]) for axis in ("y", "x")
+ if pop[axis]["wrap_is_largest"] and pop[axis]["wrap_over_median"] > pop_max])
+
+
def jolt_verdict(measured: dict[str, Any], *, jolt_max: float | None = JOLT_REFERENCE,
head_step_max: float | None = HEAD_STEP_REFERENCE) -> list[str]:
"""What exceeds the bounds, in words; empty when the loop stays inside. A bound of None is not checked."""