Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
fix(video): a staff that swings on its own beat is not cut where it jumps — seam_pop
Soohong Kim70f4a8793581
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex be163ad..1fb0563 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,13 @@All notable public changes to `sprite-gen` are recorded here. Versions track the `version:` field in `SKILL.md` and `pyproject.toml`.+## Unreleased (v2.35.0) - A staff that swings on its own beat is not cut where it jumps++- **Output change: `video-loop --anchor motion-auto` chooses its cut again when the top of the silhouette jumps into the first frame.** A staff, a flag or a raised spear held above the head can sway on a beat slower than the steps; a cut one step long then ends with it elsewhere, the body closes and the held part jumps at the wrap. The seam ratio is an area measure and a thin rod hardly moves it, so such a cut passed. The search now weighs, for its first choice, the top band's step into the first frame over the loop's median step (`repair.seam_pop`, on the frames it chooses from, moved by the analysis translation; the median a pixel at least), counted only when the wrap is that band's largest step. Over the bound (**10**, `repair.SEAM_POP_REFERENCE`) every candidate is measured, and among those under it the cut is taken from the scores within the usual 15 % of the best, smallest jump first. The report's `cycle.seam_pop` records `first_choice`, `applied`, `measured` and `chosen` (or `why` when every candidate jumps and the first choice is kept). A first choice under the bound is kept and nothing past it is measured: a loop without such a part is cut, written and warned about byte for byte as before. [docs/loop-repair.md](docs/loop-repair.md#the-seam-pop--a-part-held-above-the-head-swinging-on-its-own-beat).+- **New: every walk and run loop reports the seam pop and warns on it** (`jolt.seam_pop`: per axis `wrap_pct`, `step_median_pct`, `wrap_over_median`, `wrap_is_largest`; `pop`, `reference`, `pops`; `seam_pop` in the printed summary's `jolt`). Over the bound, on the loop as it plays, `jolt.warnings` and stderr gain `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`. The top line (up or down) had no bound at all; a sideways jump into frame 0 the head's 0.75 % bound already names is not said twice. Nothing fails on it, and a fixed or `--cycle periodic` cut is not chosen again.+- **New: a motion-auto search that finds no cycle reports the windows it measured and refused.** The failed report's `cycle` was `null`, so a caller that delivers anyway (a forced `--cycle fixed`) had no measured window and took the whole clip — which, for a walk, cannot loop. It now carries `status: "refused"`, `window`, `refused_count` and up to 12 `candidates` (`start`, `length`, `score`, `ratio`, `context_repeat_over_step`, `drift_line_residual_analysis_px`, `seam_pop`, and `refused`: why), best score first and those whose top jumps at the wrap last (`local_cycle.REFUSED_SHOWN`). The error, the exit code and every other gate are unchanged. [docs/loop-review.md](docs/loop-review.md#the-gait-fallback-a-slow-walk-or-a-walk-toward-the-camera).+- **`tests/video/test_loop_prop_seam.py`** draws a walker stepping every 24 frames with a staff above its head swaying every 61: v2.34.0 cuts it where the staff's tip jumps 11 times its largest step inside the loop, and now it is cut where the tip closes; a fixed cut whose staff tip rises and drops back at the wrap warns; a walk whose legs never come back fails with measured windows in its report.+## v2.34.0 - A foot the set alignment names by too small a margin is left for whoever looks- **Output change: a side or diagonal loop whose shade parts its two strikes by less than 0.025 in luma is no longer named** (`video-cycle-align`, `video-set --align-cycles`; `align.SHADE_MARGIN`, was 0.015). The shade cue (the far leg drawn darker) named a foot whenever the strikes differed by 0.015; on drawn walks checked by eye it named feet wrong at margins under the new bar and right above it. A foot named wrong is not asked about — the loop ships half a cycle off — so a margin under the bar now leaves the foot unnamed: the loop starts on its larger strike with `start_foot: null`, is listed under the report's `unnamed_feet` with its two candidate strike frames, and is told back with `--foot <loop>=left|right` (`video-set --align-foot`) by a person or a vision call. Its frames, strip, GIF and WebP are those of its larger strike as before; only who named the foot changes. Front and back loops (the depth cue, 1 % of the body's height) and every loop whose margin clears the bar come out byte for byte as they were. [docs/loop-repair.md](docs/loop-repair.md#4-one-cycle-for-a-direction-set--video-cycle-align-video-set---align-cycles-auto).diff --git a/SKILL.md b/SKILL.mdindex f1b8dbd..0ad338b 100644--- a/SKILL.md+++ b/SKILL.md@@ -138,4 +138,4 @@ Scene creation consumes finished assets and remains optional. Asset metadata own## Contracts and advanced tools-[run-contract](docs/run-contract.md) owns numeric requests, run layout, atomic publication and curated exports. [architecture](docs/architecture.md) explains domain ownership. [docs index](docs/README.md) lists every specialized feature and QA procedure. `sprite-gen --help` derives the command map from the package catalog. Never replace an engine stage — extraction, the loop cut, set alignment, loop repair — with a script of your own while presenting the result as a pipeline output. Where a stage's result is wrong, use the engine's own options first (another cut with `video-loop --max-len` or `--cycle fixed`, `video-cycle-align --length`, `--between auto` (the default: a made frame that melted takes the nearer source frame) or `--between nearest`, or `--cycles <loop>=<k>` once you have counted a suspect loop's strides, or `--foot <loop>=left|right` (`video-set --align-foot <item>=…`) once you have looked at the first strike frame of a loop the report lists under `unnamed_feet`), keep the engine's result as the comparison, report the defect against the engine, and name in the delivery each stage done by hand and why. A new clip is for what no stage can reach: the drawing, the motion itself, a clip that holds no whole cycle ([loop-review](docs/loop-review.md)) — and a clip the engine names for one: when the alignment report's `retake` lists a loop (reason `held-drawings`: the cycle cut from its clip shows each drawing for two or three frames, the set's length leaves it at under 13 drawings a second, and frames between its drawings could not be made, so the loop halts there), run the engine verbs first as above, then film that direction again and align the set anew rather than hand-painting the gap; tell the user what the reason was and that a new take usually fixes it ([loop-repair](docs/loop-repair.md) section 4).+[run-contract](docs/run-contract.md) owns numeric requests, run layout, atomic publication and curated exports. [architecture](docs/architecture.md) explains domain ownership. [docs index](docs/README.md) lists every specialized feature and QA procedure. `sprite-gen --help` derives the command map from the package catalog. Never replace an engine stage — extraction, the loop cut, set alignment, loop repair — with a script of your own while presenting the result as a pipeline output. Where a stage's result is wrong, use the engine's own options first (another cut with `video-loop --max-len` or `--cycle fixed`, `video-cycle-align --length`, `--between auto` (the default: a made frame that melted takes the nearer source frame) or `--between nearest`, or `--cycles <loop>=<k>` once you have counted a suspect loop's strides, or `--foot <loop>=left|right` (`video-set --align-foot <item>=…`) once you have looked at the first strike frame of a loop the report lists under `unnamed_feet`), keep the engine's result as the comparison, report the defect against the engine, and name in the delivery each stage done by hand and why. A new clip is for what no stage can reach: the drawing, the motion itself, a clip that holds no whole cycle ([loop-review](docs/loop-review.md)) — and a clip the engine names for one: when the alignment report's `retake` lists a loop (reason `held-drawings`: the cycle cut from its clip shows each drawing for two or three frames, the set's length leaves it at under 13 drawings a second, and frames between its drawings could not be made, so the loop halts there), run the engine verbs first as above, then film that direction again and align the set anew rather than hand-painting the gap; tell the user what the reason was and that a new take usually fixes it ([loop-repair](docs/loop-repair.md) section 4). When `video-loop` warns that the top of the silhouette jumps into the loop's first frame (a staff or flag held above the head, swinging on its own beat), that part does not close at the cut: look at the loop, and try `--cycle fixed` with a cut two steps long before filming again; a walk refused for no cycle names in its report's `cycle.candidates` the windows it measured, best first, for a cut you must deliver anyway ([loop-repair](docs/loop-repair.md) section 3, "The seam pop").diff --git a/docs/loop-repair.md b/docs/loop-repair.mdindex 8a5bfd4..83f066f 100644--- a/docs/loop-repair.md+++ b/docs/loop-repair.md@@ -203,6 +203,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` || `gate`, `gated`, `over`, `passed` | the bounds the caller passed, whether they were enforced, what exceeded them || `measured` | `after the jump repair` or `as filmed` |@@ -246,12 +247,55 @@ Read:reference (0.43) sits at the kept takes' edge and flags nothing in this set. An alternating joltlike that side walk's is a known miss of this index.- **The top line is reported, not bounded**: a walk seen from behind bobs more (the kept Lite- back view reaches 2.42 %), so one bound would flag kept back views or pass the refused one.+ back view reaches 2.42 %), so one bound would flag kept back views or pass the refused one Only its+ step into the first frame is weighed, against the loop's own steps (below).- **Why no gate by default**: at the reference bounds, 18 of the 46 takes exceed one — 16 of 30Lite, 2 of 16 Pro, none of the nine kept. Lite's head sways about three times as far as Pro's,so as a default gate it would refilm about every other Lite walk: the opposite of the aim, onthe strength of two refusals. The bounds stay a reference until more takes are judged.+### The seam pop — a part held above the head, swinging on its own beat++A staff, a flag or a raised spear can sway on a beat of its own, slower than the steps. A cut one+step long then ends with it somewhere else: the body closes at the wrap and the held part jumps.+The seam ratio does not see it — it is an area measure, and a thin rod moved many times its usual+step changes few pixels — and the head's sideways bound above sees it only when the jump is large+in absolute terms. What sees it is the top band of `head.x`/`head.y`: on a body holding something+higher than its head, that band is the tip of what it holds.++Every walk and run loop's `jolt` carries `seam_pop` (`repair.seam_pop`), measured on the loop as it+plays:++| Field | What |+|---|---|+| `x`, `y` | per axis of the top band: `wrap_pct` (its step from the last frame into the first, % of the body height), `step_median_pct` (the loop's median step), `wrap_over_median` (the wrap over the median, the median a pixel at least: a step under a pixel is the tracker's rounding) and `wrap_is_largest` |+| `pop` | the larger `wrap_over_median` of the axes whose largest step is the wrap; 0 when neither's is |+| `reference`, `pops` | the bound (**10**, `repair.SEAM_POP_REFERENCE`) and whether `pop` exceeds it |++- **Only the wrap, and only when it is the largest step.** The question is whether the cut closes,+ not whether the top moves: a walk seen from behind bobs, and hair redrawn every frame jumps+ inside the loop as much as at the wrap — for either the wrap is ordinary, and `pop` stays 0.+- **`--anchor motion-auto` chooses again.** The search measures the same thing on the frames it+ chooses from (moved by the analysis translation, `loop.wrap_pop_on`), for its first choice only.+ If that pops, every candidate is measured, and among those that do not pop it takes the scores+ within the usual 15 % of the best and the smallest pop (`cycle.seam_pop`: `first_choice`,+ `applied`, `measured`, `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 pops,+ the first choice is kept (`why`) and the warning below says so.+- **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.+- **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+ measure alone chose, and 0 at the cuts chosen again.+- **What it does not see**: a held part that never reaches the top band (a spear held level, a+ sword at the hip), and the lower end of a staff whose top closes while the shaft still swings+ about the hand. A clip like that may need a cut two steps long, which the search does not make;+ `--cycle fixed` cuts one ([loop review](loop-review.md)).+## 4. One cycle for a direction set — `video-cycle-align`, `video-set --align-cycles auto`Each direction of a walk is filmed on its own and comes out its own length (one Lite set:diff --git a/docs/loop-review.md b/docs/loop-review.mdindex 40ed4e6..1dafeb2 100644--- a/docs/loop-review.md+++ b/docs/loop-review.md@@ -92,7 +92,11 @@ motion around both boundaries, and a supported doubled recurrence when a shortstep falls below the gait floor. Candidate ranking also penalizes drift that asingle linear correction could not remove. Among scores within 15% of the best,the earliest repeat is used; exact cut quantization may differ by one frame from-the lag minimum. An explicit `--max-len` is never widened; without one, only the gait+the lag minimum. When the top of the silhouette jumps into that cut's first frame —+a staff or flag held above the head, swinging on its own beat — the candidates are measured+and the cut is chosen again among those whose top closes ([loop repair](loop-repair.md)+section 3, "The seam pop"; `cycle.seam_pop`). A first choice whose top closes is kept and+nothing more is measured. An explicit `--max-len` is never widened; without one, only the gaitfallback below looks past the state's window, and only after this search found nothing.### The gait fallback: a slow walk, or a walk toward the camera@@ -123,7 +127,12 @@ back here if the first search found no cycle.)Every other gate is the same, the seam limit included. A clip the first search cuts is cutexactly as before. The report records the first search's reason, the measured drift, whetherit was undone and the window (`gait_fallback`); if the second search fails too, the error-keeps its `no periodic cycle found` start and says what was tried. The scaled-back frames are+keeps its `no periodic cycle found` start and says what was tried. The failed report's `cycle`+then names the windows the search measured and refused (`status: "refused"`, `window`,+`refused_count`, and up to 12 `candidates`: `start`, `length`, `score`, `ratio`,+`context_repeat_over_step`, `drift_line_residual_analysis_px`, `seam_pop`, and `refused`, why),+best score first and those whose top jumps at the wrap last, so a caller that must deliver+anyway (a forced `--cycle fixed`) cuts one the engine measured rather than the whole clip. The scaled-back frames arewritten to `<out-dir>/.gait-fallback-frames` and removed once the strip is built or the runfails.diff --git a/docs/video-pipeline.md b/docs/video-pipeline.mdindex 1fee041..129df43 100644--- a/docs/video-pipeline.md+++ b/docs/video-pipeline.md@@ -690,6 +690,11 @@ was 17). `video-loop` therefore:ranking. `cycle.selection` records the half-open source-pair range, repeaterror, normalised error, wrap penalty and combined score; `next_frame_distance`retains the single-frame diagnostic. Fixed cuts do not use this ranking.+ The seam is an area measure: a thin part (a staff, a flag) that jumps at the wrap+ changes few pixels and hardly moves it. `--anchor motion-auto` also weighs the top+ of the silhouette at the wrap and chooses again when it jumps, and every walk or run+ reports that jump and warns on it ([loop repair](loop-repair.md) section 3,+ "The seam pop").This neighbourhood check measures temporal consistency, not anatomical legidentity. A consistently repeated malformed motion can still score well; visual@@ -872,7 +877,9 @@ animation gates apply. `--cycle periodic` refuses a weak periodic candidate;`--cycle one-shot` forces return detection. Stationary clips, jitter and actionswithout an observed return fail loud. Selection and seam refusals write the requestedreport before exiting: `status = "failed"`, error, window, candidate start/length,-seam numerator/denominator and repetition/return evidence. Undefined ratios are JSON+seam numerator/denominator and repetition/return evidence. A walk or run refused by the+`--anchor motion-auto` search names the windows it measured and refused, best first+([loop review](loop-review.md), "The gait fallback"). Undefined ratios are JSON`null`; success records `status = "passed"`. `--cycle fixed --start N --length L` skips detection and cuts exactlythose frames — for a clip that holds too few repeats for the periodicity gate but whosecycle is known (the 2026-09-09 reel jump: 2.3 hops in 145 frames). It is an explicitdiff --git a/sprite_gen/video/local_cycle.py b/sprite_gen/video/local_cycle.pyindex ca2bebb..27e7cbc 100644--- a/sprite_gen/video/local_cycle.py+++ b/sprite_gen/video/local_cycle.py@@ -13,6 +13,8 @@ import mathfrom sprite_gen._deps import npfrom sprite_gen.video import period as period_mod+REFUSED_SHOWN = 12 # refused windows a failed search reports, as many as a found cycle's candidates+def _around(start, length):"""The frames whose repeats are compared for a cut at `start`: a quarter of the cut either side."""@@ -30,22 +32,75 @@ def _profile(distances, js, radius, lo, hi):return profile+def _measure(distances, trajectory, start, length, profile):+ """The parts of a window's score, for a window the search refused (`refused`): the same sums as+ a candidate's, so a refused window and a candidate read alike."""+ step = float(np.diag(distances[start:start+length, start:start+length], 1).mean())+ if step <= 1e-10 or length not in profile:+ return None+ ratio = float(distances[start+length-1, start])/step+ x = np.arange(length)+ segment = trajectory[start:start+length]+ residual = float(np.abs(segment-np.polyval(np.polyfit(x, segment, 1), x)).mean())+ error = profile[length]+ return {'start': start, 'length': length, 'score': error/step + .3*abs(math.log(max(.01, ratio))) + residual,+ 'ratio': ratio, 'context_repeat_over_step': error/step, 'drift_line_residual_analysis_px': residual}+++def _shape_rank(candidates, chosen, wrap_pop):+ """Choose again when the chosen cut's top pops at the wrap (`wrap_pop`, repair.seam_pop on the+ analysed frames): among the candidates that do not pop, the same score tolerance, then the+ smallest pop. Nothing is measured past the first choice when it does not pop, so a cut without+ a thin part swinging on its own beat is chosen exactly as before."""+ first = wrap_pop(chosen['start'], chosen['length'])+ record = {'method': 'top-band-wrap-v1', 'reference': first['reference'],+ 'first_choice': {'start': chosen['start'], 'length': chosen['length'], 'pop': first['pop']},+ 'applied': False}+ if not first['pops']:+ return chosen, record+ calm = []+ for row in candidates:+ measured = wrap_pop(row['start'], row['length'])+ row['seam_pop'] = measured['pop']+ if not measured['pops']:+ calm.append(row)+ record['measured'] = len(candidates)+ if not calm:+ record['why'] = 'every candidate pops at the wrap; the first choice is kept'+ return chosen, record+ cutoff = min(row['score'] for row in calm)*1.15+1e-8+ picked = min((row for row in calm if row['score'] <= cutoff),+ key=lambda row: (row['seam_pop'], row['score'], row['start'], row['length']))+ record.update(applied=True, chosen={'start': picked['start'], 'length': picked['length'], 'pop': picked['seam_pop']})+ return picked, record++def detect(distances, trajectory, *, min_len, max_len, gait_floor,- periodicity_min, double_tolerance, double_search, max_fraction=.5, signals=None):+ periodicity_min, double_tolerance, double_search, max_fraction=.5, signals=None, wrap_pop=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`)."""n = len(distances)# A cycle has to be seen repeating: half the clip by default, more for the gait fallback.lo, hi = max(6, min_len), min(max_len, int(n*max_fraction))if hi < lo:raise ValueError(f"automatic motion cycle window [{lo}, {hi}] has no repeated cycle")candidates = []+ refused = []for length in range(max(lo, gait_floor), hi+1):radius = max(2, length//4)for start in range(n-length-radius-1):_, js = _around(start, length)profile = _profile(distances, js, radius, lo, hi)++ def refuse(why, start=start, length=length, profile=profile):+ row = _measure(distances, trajectory, start, length, profile)+ if row is not None:+ refused.append({**row, 'refused': why})minima = [lag for lag in profile if lag-1 in profile and lag+1 in profileand profile[lag] <= min(profile[lag-1], profile[lag+1]) and lag <= hi]if not minima:+ refuse('no local repeat minimum')continuedeepest = min(profile[lag] for lag in minima)period = min(lag for lag in minima if profile[lag] <= deepest*1.15+1e-4)@@ -53,26 +108,31 @@ def detect(distances, trajectory, *, min_len, max_len, gait_floor,if period < gait_floor:doubles = [lag for lag in minima if abs(lag-2*period) <= double_search and lag >= gait_floor]if not doubles:+ refuse('one step: no repeat near twice it')continuedoubled = min(doubles, key=profile.get)if profile[doubled] > profile[period]*(1+double_tolerance)+1e-4:+ refuse('one step: twice it repeats worse')continueguard = {'applied': True, 'from': period, 'to': doubled,'gait_floor': gait_floor, 'reason': 'local-two-step-repeat'}period = doubled# Allow one frame of cut quantization around the measured local lag.if abs(length-period) > 1 or profile.get(length, math.inf) > profile[period]*1.15+1e-4:+ refuse(f'the local repeat is {period} frames')continuebaseline = float(np.mean(list(profile.values())))error = profile[length]depth = 1-error/baseline if baseline > 0 else 0step = float(np.diag(distances[start:start+length, start:start+length], 1).mean())if depth < periodicity_min or step <= 1e-10 or error/step > 2:+ refuse('repeat too shallow' if depth < periodicity_min else 'repeat error over two steps')continue# A still/rest segment matching another still is not a repeated gait.first_motion = float(distances[js[:-1], js[1:]].mean())second_motion = float(distances[js[:-1]+length, js[1:]+length].mean())if min(first_motion, second_motion) < .25*step:+ refuse('a still segment')continueratio = float(distances[start+length-1, start])/stepx = np.arange(length)@@ -87,12 +147,31 @@ def detect(distances, trajectory, *, min_len, max_len, gait_floor,'drift_line_residual_analysis_px': residual, 'half_period_guard': guard,})if not candidates:- raise ValueError("no periodic cycle found — no supported local two-step repeat after drift analysis")+ exc = ValueError("no periodic cycle found — no supported local two-step repeat after drift analysis")+ # The windows the search measured and refused, best first: a caller that must deliver anyway+ # (a forced cut) takes one the engine measured instead of the whole clip.+ refused.sort(key=lambda row: (row['score'], row['start'], row['length']))+ shown = refused[:REFUSED_SHOWN]+ if wrap_pop is not None:+ pops = {}+ for row in shown:+ measured = wrap_pop(row['start'], row['length'])+ row['seam_pop'] = measured['pop']+ pops[row['start'], row['length']] = measured['pops']+ shown.sort(key=lambda row: (pops[row['start'], row['length']], row['score'], row['start'], row['length']))+ exc.diagnostics = {'kind': 'periodic', 'method': 'local-repeat-drift-v1', 'status': 'refused',+ 'window': [lo, hi], 'refused_count': len(refused),+ 'order': 'score' + (', windows whose top pops at the wrap last' if wrap_pop is not None else ''),+ 'candidates': shown}+ raise exccandidates.sort(key=lambda row: (row['score'], row['start'], row['length']))# Equivalent-quality candidates: prefer the earliest demonstrated repeat.cutoff = candidates[0]['score']*1.15+1e-8chosen = min((r for r in candidates if r['score'] <= cutoff),key=lambda row: (row['start'], row['score'], row['length']))+ shape = None+ if wrap_pop is not None:+ chosen, shape = _shape_rank(candidates, chosen, wrap_pop)radius, js = _around(chosen['start'], chosen['length'])profile = _profile(distances, js, radius, lo, hi)fundamental = period_mod.screen(@@ -105,4 +184,5 @@ def detect(distances, trajectory, *, min_len, max_len, gait_floor,'review_recommended': True, 'candidate_count': len(candidates),'best_score': candidates[0]['score'], 'equivalent_score_tolerance': .15,'candidates': candidates[:12],+ **({'seam_pop': shape} if shape is not None else {}),}diff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.pyindex 8ee58b5..366a370 100644--- a/sprite_gen/video/loop.py+++ b/sprite_gen/video/loop.py@@ -856,6 +856,37 @@ def _repair_jumps(frames: list[Image.Image], interpolate: rife_mod.Interpolate |return frames, record+def wrap_pop_on(frames: list[Image.Image], analysis: dict[str, Any]) -> Any:+ """`repair.seam_pop` of a cut (start, length) of `frames`, each moved by the analysis translation+ `auto_motion.analyse` measured (its drift taken out, the way the cut will be corrected): the+ top band's jump at the wrap, for `local_cycle.detect` to rank its candidates by. Alpha only,+ cropped once to the clip's subject; a cut's value is kept once measured."""+ shifts = np.rint(np.asarray(analysis["analysis_only_translation_xy"], dtype=np.float64)).astype(int)+ pad = int(np.abs(shifts).max()) + 1+ boxes = [f.getchannel("A").point(lambda v: 255 if v >= repair_mod.ALPHA_SOLID else 0).getbbox() for f in frames]+ boxes = [b for b in boxes if b]+ box = (min(b[0] for b in boxes), min(b[1] for b in boxes), max(b[2] for b in boxes), max(b[3] for b in boxes))+ w, h = box[2] - box[0] + 2 * pad, box[3] - box[1] + 2 * pad+ moved = []+ for f, (dx, dy) in zip(frames, shifts):+ a = np.zeros((h, w), dtype=np.uint8)+ crop = np.asarray(f.getchannel("A").crop(box))+ a[pad + dy:pad + dy + crop.shape[0], pad + dx:pad + dx + crop.shape[1]] = crop+ moved.append(a)+ measured: dict[tuple[int, int], dict[str, Any]] = {}++ def pop(start: int, length: int) -> dict[str, Any]:+ if (start, length) not in measured:+ try:+ measured[start, length] = repair_mod.seam_pop([a.astype(np.float32) / 255.0 for a in moved[start:start + length]])+ except ValueError as exc:+ # A frame with nothing in the top band: no jump read, so nothing is chosen on it.+ measured[start, length] = {"skipped": str(exc), "reference": repair_mod.SEAM_POP_REFERENCE,+ "pop": 0.0, "pops": False}+ return measured[start, length]+ return pop++def run_loop(frames_dir: Path,out_dir: Path,@@ -959,7 +990,8 @@ def run_loop(detect = dict(gait_floor=round(prof.min_seconds*fps), periodicity_min=PERIODICITY_MIN,double_tolerance=GAIT_DOUBLE_TOL, double_search=GAIT_DOUBLE_SEARCH)try:- cycle = local_cycle.detect(D, trajectory, min_len=lo, max_len=hi, signals=leg_signals(source_frames), **detect)+ cycle = local_cycle.detect(D, trajectory, min_len=lo, max_len=hi, signals=leg_signals(source_frames),+ wrap_pop=wrap_pop_on(source_frames, analysis), **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.@@ -980,10 +1012,14 @@ def run_loop(try:cycle = local_cycle.detect(D, trajectory, min_len=lo, max_len=hi_long,max_fraction=gait_fallback.LONG_CYCLE_FRACTION if max_len is None else .5,- signals=leg_signals(source_frames), **detect)+ signals=leg_signals(source_frames), wrap_pop=wrap_pop_on(source_frames, analysis), **detect)except ValueError as second:- raise ValueError(f"{second} (also with the gait fallback: window [{lo}, {hi_long}], "- f"scale drift {drift['drift']:+.1%}{', undone' if fallback['scale_undone'] else ''})") from first+ 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 ''})")+ # The windows the wider search measured and refused go into the report's `cycle`.+ if hasattr(second, "diagnostics"):+ failed.diagnostics = second.diagnostics # type: ignore[attr-defined]+ raise failed from firstelif cycle_mode == "fixed":if start is None or length is None:raise SystemExit("video-loop: --cycle fixed needs --start and --length")@@ -1092,6 +1128,7 @@ def run_loop(jolt = repair_mod.measure_jolt(frames, facing=facing)reference = {"jolt_max": repair_mod.JOLT_REFERENCE, "head_step_max": repair_mod.HEAD_STEP_REFERENCE}warnings = repair_mod.jolt_verdict(jolt, **reference)+ warnings += repair_mod.seam_pop_verdict(jolt, head_step_max=repair_mod.HEAD_STEP_REFERENCE)gated = repair != "off" and (jolt_max is not None or head_step_max is not None)over = repair_mod.jolt_verdict(jolt, jolt_max=jolt_max, head_step_max=head_step_max) if gated else []report_base["jolt"] = {**jolt, "reference": reference, "warnings": warnings,@@ -1278,7 +1315,10 @@ def run(**kwargs: object) -> int:summary["motion_anchor"] = payload["motion_anchor"]if payload.get("jolt"):summary["jolt"] = {"index": payload["jolt"]["index"], "warnings": payload["jolt"]["warnings"],- "head_x_step_max_pct": payload["jolt"]["head"].get("x", {}).get("step_max_pct")}+ "head_x_step_max_pct": payload["jolt"]["head"].get("x", {}).get("step_max_pct"),+ "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.get("jump_repair", {}).get("replaced"):summary["jump_repair"] = {k: payload["jump_repair"][k] for k in ("replaced", "score_max_before", "score_max_after")}summary["strip"] = {k: payload["strip"][k] for k in ("path", "frames", "w", "h", "body_h", "delay_ms")}diff --git a/sprite_gen/video/repair.py b/sprite_gen/video/repair.pyindex edf6801..db97555 100644--- a/sprite_gen/video/repair.py+++ b/sprite_gen/video/repair.py@@ -135,6 +135,12 @@ JOLT_REFERENCE = 0.43 # alpha jolt index; the kept takes reached 0.414 on stripHEAD_STEP_REFERENCE = 0.75 # head's sideways move in one frame, % of body height; kept <= 0.68, refused 0.82HEAD_BAND = 0.20 # the head is the top fifth of the body's height over the loopHEAD_MEDIAN_FLOOR = 0.05 # % of body height: a median step below this is the tracker's rounding+# 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.+SEAM_POP_REFERENCE = 10.0def jolt_index(step_values: np.ndarray) -> float:@@ -160,6 +166,12 @@ def head_track(alphas: list[np.ndarray]) -> dict[str, Any]:"""The head's place frame by frame, in % of the body's height over the loop: x is the coveragecentroid of the top fifth (HEAD_BAND), y the body's top line. A take whose head pops sidewaysreads here while its coverage change stays ordinary (2026-10-03, Lite back diagonal)."""+ x, y, height = _head_series(alphas)+ return {"body_height_px": height, "x": _track_stats(x), "y": _track_stats(y)}+++def _head_series(alphas: list[np.ndarray]) -> tuple[np.ndarray, np.ndarray, int]:+ """`head_track`'s two places per frame (% of the body height) and the body height in px."""rows = np.where(np.max(np.stack(alphas), axis=0).max(axis=1) > 0.1)[0]if rows.size == 0:raise ValueError("every loop frame is fully transparent")@@ -177,7 +189,40 @@ def head_track(alphas: list[np.ndarray]) -> dict[str, Any]:y = np.array(ys) / height * 100if not (np.isfinite(x).all() and np.isfinite(y).all()):raise ValueError("a loop frame has no head to track")- return {"body_height_px": height, "x": _track_stats(x), "y": _track_stats(y)}+ return x, y, height+++def seam_pop(alphas: list[np.ndarray]) -> dict[str, Any]:+ """How far the top of the silhouette jumps into the loop's first frame (docs/loop-repair.md+ section 3, "The seam pop").++ The top band `head_track` reads is the head, or the tip of whatever the body holds higher than its+ head — a staff, a flag, a raised spear. A thin part like that can sway on its own beat, slower than+ the steps: a cut one step long then ends with it somewhere else, and it jumps at the wrap while+ the body closes. The seam ratio is an area measure and hardly sees a thin part move: a tip that+ jumps many times its usual step changes few pixels.++ Per axis, the wrap's step (last frame -> first) over the loop's median step, a pixel at least: a+ step under a pixel is the tracker's rounding. It pops when the wrap is that axis' largest step+ and exceeds SEAM_POP_REFERENCE times the median; `pop` is the larger of the two, 0 when neither+ axis has its largest step at the wrap. A loop whose top jitters more inside than at the wrap+ (hair redrawn every frame) has its wrap ordinary for it."""+ x, y, height = _head_series(alphas)+ floor = max(HEAD_MEDIAN_FLOOR, 100.0 / height)+ record: dict[str, Any] = {"body_height_px": height, "reference": SEAM_POP_REFERENCE}+ pop = 0.0+ for axis, values in (("x", x), ("y", y)):+ n = len(values)+ d = np.abs(np.array([values[(k + 1) % n] - values[k] for k in range(n)]))+ over = float(d[-1]) / max(float(np.median(d)), floor)+ worst = bool(d[-1] >= d.max())+ record[axis] = {"wrap_pct": round(float(d[-1]), 3), "step_median_pct": round(float(np.median(d)), 3),+ "wrap_over_median": round(over, 3), "wrap_is_largest": worst}+ if worst:+ pop = max(pop, over)+ record["pop"] = round(pop, 3)+ record["pops"] = pop > SEAM_POP_REFERENCE+ return recorddef measure_jolt(frames: list[Image.Image], *, facing: str = "right") -> dict[str, Any]:@@ -187,16 +232,38 @@ def measure_jolt(frames: list[Image.Image], *, facing: str = "right") -> dict[stmed = float(np.median(whole))try:head: dict[str, Any] = head_track(al)+ pop: dict[str, Any] = seam_pop(al)except ValueError as exc:head = {"skipped": str(exc)} # recorded, and the head gate says it could not read it+ pop = {"skipped": str(exc)}return {"index": round(jolt_index(whole), 4),"hair_index": round(jolt_index(hair), 4),"step_max_over_median": round(float(whole.max()) / med, 4) if med > 0 else None,"head": head,+ "seam_pop": pop,}+def seam_pop_verdict(measured: dict[str, Any], *, head_step_max: float | None = HEAD_STEP_REFERENCE) -> list[str]:+ """The top band's jump into the loop's first frame, in words, when it pops (section 3, "The seam+ pop"); empty otherwise. A sideways jump the head bound already names (`jolt_verdict`, into frame+ 0) is not said twice."""+ pop = measured.get("seam_pop") or {}+ if "skipped" in pop or not pop.get("pops"):+ return []+ head = measured["head"].get("x", {})+ said = head_step_max is not None and head.get("step_max_pct", 0) > head_step_max and head.get("worst_into_frame") == 0+ axes = [(axis, pop[axis]) for axis in ("y", "x") if pop[axis]["wrap_is_largest"]+ 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)+ + 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 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."""diff --git a/tests/video/test_loop_prop_seam.py b/tests/video/test_loop_prop_seam.pynew file mode 100644index 0000000..9a719b6--- /dev/null+++ b/tests/video/test_loop_prop_seam.py@@ -0,0 +1,177 @@+# SPDX-License-Identifier: Apache-2.0+"""A thin part held above the head that sways on its own beat (docs/loop-repair.md section 3,+"The seam pop").++The walker steps every 24 frames; the staff it holds sways every 61, so a cut one step long ends+with the staff's tip somewhere else unless it is taken where the tip passes the same place again.+The seam ratio is an area measure and hardly sees a thin rod move. `--anchor motion-auto` chooses+again among its candidates when the top of the silhouette jumps into the first frame, a kept jump+is a warning line, and a search that finds no cycle reports the windows it measured and refused.++Synthetic frames only; the tip's place is known in closed form, so the tests read the cut against it."""++from __future__ import annotations++import json+import math+from pathlib import Path++import numpy as np+import pytest+from PIL import Image, ImageDraw++from sprite_gen.video import local_cycle, loop, repair++STEP, SWAY, AMP = 24, 61, 14+++def _tip(k: int, phase: float) -> float:+ """The staff tip's sideways place against the body, px."""+ return AMP * math.sin(2 * math.pi * k / SWAY + phase)+++def _walker(k: int, *, phase: float = 1.0, legs=None, tip_dy: float = 0.0, staff: bool = True) -> Image.Image:+ im = Image.new("RGBA", (280, 220))+ d = ImageDraw.Draw(im)+ x = 45 + k+ y = 58 + round(k * .2) + round(3 * math.sin(k * 2 * math.pi / STEP))+ d.rectangle((x, y, x + 28, y + 30), fill=(210, 150, 60, 255))+ d.rectangle((x + 20, y + 8, x + 24, y + 12), fill=(10, 30, 50, 255))+ d.rectangle((x - 3, y + 32, x + 30, y + 78), fill=(20, 90, 180, 255))+ d.rectangle((x + 10, y + 35, x + 15, y + 73), fill=(210, 190, 40, 255))+ leg = round(12 * math.sin(k * 2 * math.pi / STEP)) if legs is None else legs(k)+ d.rectangle((x + leg, y + 79, x + 6 + leg, y + 119), fill=(80, 30, 60, 255))+ d.rectangle((x + 24 - leg, y + 79, x + 30 - leg, y + 119), fill=(30, 60, 90, 255))+ d.point((x + leg + 2, y + 85 + k % 12), fill=(240, 240, 240, 255))+ if not staff:+ return im+ hand = (x + 34, y + 50)+ tip = (x + 34 + _tip(k, phase), y - 40 + tip_dy)+ d.line([hand, tip], fill=(120, 80, 40, 255), width=3)+ d.ellipse((tip[0] - 4, tip[1] - 4, tip[0] + 4, tip[1] + 4), fill=(230, 200, 60, 255))+ return im+++def _keyed(tmp_path: Path, frames: list[Image.Image]) -> Path:+ keyed = tmp_path / "keyed"+ keyed.mkdir()+ for k, im in enumerate(frames):+ im.save(keyed / f"{k:03}.png")+ return keyed+++def _wrap_over_step(start: int, length: int, phase: float) -> float:+ """The tip's jump from the cut's last frame to its first, over the largest step inside the cut."""+ inner = max(abs(_tip(k + 1, phase) - _tip(k, phase)) for k in range(start, start + length - 1))+ return abs(_tip(start, phase) - _tip(start + length - 1, phase)) / inner+++def test_motion_auto_does_not_cut_where_the_staff_jumps(tmp_path):+ keyed = _keyed(tmp_path, [_walker(k) for k in range(73)])+ out = tmp_path / "out"+ assert loop.main(["--frames-dir", str(keyed), "--out-dir", str(out), "--state", "walk",+ "--anchor", "motion-auto", "--repair", "off"]) == 0+ report = json.loads((out / "loop.loop.report.json").read_text())+ cycle = report["cycle"]+ assert cycle["length"] in (STEP - 1, STEP, STEP + 1)+ # The cut closes the staff too: its tip at the wrap moves no more than a step inside the loop moves it.+ assert _wrap_over_step(cycle["start"], cycle["length"], 1.0) <= 1.5+ # The first choice, by the area measure alone, ended with the tip elsewhere; it was chosen again.+ shape = cycle["seam_pop"]+ assert shape["applied"] is True and shape["first_choice"]["pop"] > repair.SEAM_POP_REFERENCE+ first = shape["first_choice"]+ assert _wrap_over_step(first["start"], first["length"], 1.0) > 3+ assert shape["chosen"] == {"start": cycle["start"], "length": cycle["length"], "pop": shape["chosen"]["pop"]}+ assert report["jolt"]["seam_pop"]["pops"] is False+ assert not any("jumps into the loop's first frame" in line for line in report["jolt"]["warnings"])+++def test_a_cut_without_a_part_on_its_own_beat_is_chosen_as_before(tmp_path):+ """No staff: the wrap does not pop, nothing past the first choice is measured."""+ keyed = _keyed(tmp_path, [_walker(k, staff=False) for k in range(73)])+ out = tmp_path / "out"+ assert loop.main(["--frames-dir", str(keyed), "--out-dir", str(out), "--state", "walk",+ "--anchor", "motion-auto", "--repair", "off"]) == 0+ shape = json.loads((out / "loop.loop.report.json").read_text())["cycle"]["seam_pop"]+ assert shape["applied"] is False and "measured" not in shape+++def _alphas(tops: list[int], xs: list[int]) -> list[np.ndarray]:+ """A block body with a 2 px rod on top: the rod's top row and column per frame."""+ out = []+ for top, x in zip(tops, xs):+ a = np.zeros((120, 80), np.float32)+ a[40:118, 20:60] = 1+ a[top:40, x:x + 2] = 1+ out.append(a)+ return out+++def test_seam_pop_is_the_wrap_over_the_median_when_the_wrap_is_the_largest_step():+ n = 20+ smooth = _alphas([10] * n, [30 + k // 4 for k in range(n)])+ calm = repair.seam_pop(smooth)+ assert calm["pops"] is False and calm["x"]["wrap_is_largest"]+ # The rod's top rises a little every frame and drops back at the wrap: y pops.+ rising = _alphas([22 - k for k in range(n)], [30] * n)+ popped = repair.seam_pop(rising)+ assert popped["y"]["wrap_is_largest"] and popped["y"]["wrap_over_median"] > repair.SEAM_POP_REFERENCE+ assert popped["pops"] is True and popped["pop"] == popped["y"]["wrap_over_median"]+ # A rod that jumps further inside the loop than at the wrap: the wrap is ordinary for it.+ jitter = repair.seam_pop(_alphas([10] * n, [30 + k // 4 if k != 9 else 60 for k in range(n)]))+ assert jitter["x"]["wrap_is_largest"] is False and jitter["pop"] == 0 and jitter["pops"] is False+++def test_a_kept_jump_up_or_down_at_the_wrap_is_a_warning_line(tmp_path, capsys):+ """A fixed cut, nothing chosen again: the staff's tip rises along the cut and drops back at the wrap."""+ frames = [_walker(k, phase=0.0, tip_dy=-(k % STEP)) for k in range(73)]+ out = tmp_path / "out"+ assert loop.main(["--frames-dir", str(_keyed(tmp_path, frames)), "--out-dir", str(out), "--state", "walk",+ "--cycle", "fixed", "--start", "0", "--length", str(STEP), "--anchor", "none", "--repair", "off",+ "--seam-max", "1000"]) == 0+ jolt = json.loads((out / "loop.loop.report.json").read_text())["jolt"]+ assert jolt["seam_pop"]["pops"] is True and jolt["seam_pop"]["y"]["wrap_is_largest"]+ line = [w for w in jolt["warnings"] if "jumps into the loop's first frame" in w]+ assert len(line) == 1 and "up or down" in line[0]+ assert "video-loop: warning: the top of the silhouette jumps into the loop's first frame" in capsys.readouterr().err+++def test_a_sideways_jump_the_head_bound_names_is_not_said_twice():+ measured = {"head": {"x": {"step_max_pct": 2.0, "worst_into_frame": 0}},+ "seam_pop": {"reference": 10.0, "pops": True, "pop": 14.0,+ "x": {"wrap_pct": 2.0, "wrap_over_median": 14.0, "wrap_is_largest": True},+ "y": {"wrap_pct": 0.1, "wrap_over_median": 1.0, "wrap_is_largest": False}}}+ assert repair.seam_pop_verdict(measured) == []+ under = {**measured, "head": {"x": {"step_max_pct": 0.5, "worst_into_frame": 0}}}+ assert len(repair.seam_pop_verdict(under)) == 1 and "sideways" in repair.seam_pop_verdict(under)[0]+++def test_a_search_that_finds_nothing_reports_the_windows_it_refused():+ values = np.arange(80) + np.sin(np.arange(80)) # moves on and never comes back+ D = np.abs(values[:, None] - values[None, :]).astype(np.float32)+ with pytest.raises(ValueError, match="no periodic cycle") as caught:+ local_cycle.detect(D, np.zeros(80), min_len=12, max_len=36, gait_floor=14,+ periodicity_min=.15, double_tolerance=.25, double_search=3)+ found = caught.value.diagnostics+ assert found["status"] == "refused" and found["refused_count"] >= len(found["candidates"]) > 0+ rows = found["candidates"]+ assert len(rows) <= local_cycle.REFUSED_SHOWN+ assert [r["score"] for r in rows] == sorted(r["score"] for r in rows)+ for r in rows:+ assert {"start", "length", "ratio", "score", "refused"} <= set(r)+ assert r["start"] >= 0 and r["length"] >= 12 and r["start"] + r["length"] <= 80+++def test_a_refused_motion_auto_cut_leaves_measured_windows_in_the_report(tmp_path):+ """The legs spread apart over the clip and never come back: the search refuses, and the report+ names windows to deliver from anyway (before, `cycle` was null and a forced cut took the whole clip)."""+ keyed = _keyed(tmp_path, [_walker(k, legs=lambda j: round(-12 + 24 * j / 72)) for k in range(73)])+ out = tmp_path / "out"+ with pytest.raises(SystemExit, match="no periodic cycle found"):+ loop.main(["--frames-dir", str(keyed), "--out-dir", str(out), "--state", "walk",+ "--anchor", "motion-auto", "--repair", "off"])+ report = json.loads((out / "loop.loop.report.json").read_text())+ assert report["status"] == "failed"+ rows = report["cycle"]["candidates"]+ assert rows and all({"start", "length", "ratio", "seam_pop", "refused"} <= set(r) for r in rows)+ assert all(r["start"] + r["length"] <= 73 for r in rows)