Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
fix(video): a cut whose top cannot be read is not one that closes — seam_pop skipped
Soohong Kim89e16081362e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1fb0563..92ed6ab 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,10 +4,10 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the## 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).+- **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`, `unread` and `chosen` (or `why` when every candidate read jumps and the first choice is kept). A cut whose top band cannot be read — a frame with nothing in it — has no jump to rank: it is recorded `skipped` (why) in place of a `pop` (`first_choice.skipped`; a candidate row's `seam_pop` is `null` with `seam_pop_skipped`), counted under `unread`, and never chosen as one that closes; a first choice that cannot be read 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.+- **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, those whose top could not be read (`seam_pop: null`, `seam_pop_skipped`) after those whose top closes, 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 walker whose staff tip is flung out of the top band in one frame is not cut on a window holding that frame, which cannot be read (the branch's first take recorded those as jumping 0 and chose one whose tip jumps 8 times its largest step); 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 looksdiff --git a/docs/loop-repair.md b/docs/loop-repair.mdindex 83f066f..93366e9 100644--- a/docs/loop-repair.md+++ b/docs/loop-repair.md@@ -279,9 +279,15 @@ plays: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 scoreswithin 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,+ `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.+- **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+ recorded `skipped` (why) in place of `pop` — `first_choice.skipped`, or on a candidate row+ `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 jumpsinto the loop's first frame up or down … (over 10x): a part held above the head swings on itsown beat and does not close at this cut`, in `jolt.warnings` like the bounds above. A sidewaysdiff --git a/docs/loop-review.md b/docs/loop-review.mdindex 1dafeb2..5f29e33 100644--- a/docs/loop-review.md+++ b/docs/loop-review.md@@ -94,8 +94,8 @@ single 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 fromthe 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+and the cut is chosen again among those whose top was read and closes ([loop repair](loop-repair.md)+section 3, "The seam pop"; `cycle.seam_pop`). A first choice whose top closes, or cannot be read, is kept andnothing 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.@@ -131,7 +131,8 @@ keeps its `no periodic cycle found` start and says what was tried. The failed rethen 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+best score first, those whose top could not be read (`seam_pop: null`, `seam_pop_skipped`) after+those whose top closes, and those whose top jumps at the wrap last, so a caller that must deliveranyway (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/sprite_gen/video/local_cycle.py b/sprite_gen/video/local_cycle.pyindex 27e7cbc..64e67bd 100644--- a/sprite_gen/video/local_cycle.py+++ b/sprite_gen/video/local_cycle.py@@ -47,26 +47,43 @@ def _measure(distances, trajectory, start, length, profile):'ratio': ratio, 'context_repeat_over_step': error/step, 'drift_line_residual_analysis_px': residual}+def _read(measured):+ """A cut's pop as `cycle.seam_pop` records it: the jump, or why its top band could not be read."""+ return {'skipped': measured['skipped']} if 'skipped' in measured else {'pop': measured['pop']}+++def _mark(row, measured):+ """A window row's pop: `seam_pop`, or None with `seam_pop_skipped` (why) when its top band could+ not be read — an unread window is neither taken as closing nor as popping."""+ row['seam_pop'] = measured.get('pop')+ if 'skipped' in measured:+ row['seam_pop_skipped'] = measured['skipped']++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."""+ analysed frames): among the candidates whose top was read and does not pop, the same score+ tolerance, then the smallest pop. Nothing is measured past the first choice when it does not pop,+ or when its top could not be read (kept, `skipped`), so a cut without a thin part swinging on its+ own beat is chosen exactly as before. A candidate whose top could not be read is not chosen."""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']},+ 'first_choice': {'start': chosen['start'], 'length': chosen['length'], **_read(first)},'applied': False}- if not first['pops']:+ if 'skipped' in first or not first['pops']:return chosen, recordcalm = []+ unread = 0for row in candidates:measured = wrap_pop(row['start'], row['length'])- row['seam_pop'] = measured['pop']- if not measured['pops']:+ _mark(row, measured)+ if 'skipped' in measured:+ unread += 1+ elif not measured['pops']:calm.append(row)- record['measured'] = len(candidates)+ record.update(measured=len(candidates)-unread, unread=unread)if not calm:- record['why'] = 'every candidate pops at the wrap; the first choice is kept'+ record['why'] = 'every candidate whose top was read pops at the wrap; the first choice is kept'return chosen, recordcutoff = min(row['score'] for row in calm)*1.15+1e-8picked = min((row for row in calm if row['score'] <= cutoff),@@ -153,15 +170,17 @@ def detect(distances, trajectory, *, min_len, max_len, gait_floor,refused.sort(key=lambda row: (row['score'], row['start'], row['length']))shown = refused[:REFUSED_SHOWN]if wrap_pop is not None:- pops = {}+ # Those whose top closes first, then those whose top could not be read, then those that pop.+ rank = {}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']))+ _mark(row, measured)+ rank[row['start'], row['length']] = 1 if 'skipped' in measured else 2 if measured['pops'] else 0+ shown.sort(key=lambda row: (rank[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 ''),+ 'order': 'score' + (', windows whose top could not be read after those whose top closes,'+ ' 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']))diff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.pyindex 366a370..e14d0e4 100644--- a/sprite_gen/video/loop.py+++ b/sprite_gen/video/loop.py@@ -880,9 +880,9 @@ def wrap_pop_on(frames: list[Image.Image], analysis: dict[str, Any]) -> Any: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}+ # A frame with nothing in the top band: no jump read, and no pop to rank it by —+ # `local_cycle` neither takes it as closing nor as popping (`skipped`, why).+ measured[start, length] = {"skipped": str(exc), "reference": repair_mod.SEAM_POP_REFERENCE}return measured[start, length]return popdiff --git a/tests/video/test_loop_prop_seam.py b/tests/video/test_loop_prop_seam.pyindex 9a719b6..f4478e7 100644--- a/tests/video/test_loop_prop_seam.py+++ b/tests/video/test_loop_prop_seam.py@@ -30,11 +30,13 @@ def _tip(k: int, phase: float) -> float: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))+def _walker(k: int, *, phase: float = 1.0, legs=None, tip_dy: float = 0.0, staff: bool = True,+ room: int = 0) -> Image.Image:+ """`room` px more canvas above the walker, for a tip raised higher than the usual canvas holds."""+ im = Image.new("RGBA", (280, 220 + room))d = ImageDraw.Draw(im)x = 45 + k- y = 58 + round(k * .2) + round(3 * math.sin(k * 2 * math.pi / STEP))+ y = 58 + room + 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))@@ -86,6 +88,78 @@ def test_motion_auto_does_not_cut_where_the_staff_jumps(tmp_path):assert not any("jumps into the loop's first frame" in line for line in report["jolt"]["warnings"])+def test_a_window_whose_top_cannot_be_read_is_not_taken_as_closing(tmp_path):+ """One frame (50) has the staff's tip flung 90 px up: every window holding it has a frame with nothing+ in the top band, and its pop cannot be read. Such a window is neither calm nor chosen; before, it was+ recorded as pop 0 and chosen (29/24, the tip's wrap 8x its largest step) over a read one that closes."""+ keyed = _keyed(tmp_path, [_walker(k, room=100, tip_dy=-90 if k == 50 else 0) 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 not cycle["start"] <= 50 < cycle["start"] + cycle["length"]+ assert _wrap_over_step(cycle["start"], cycle["length"], 1.0) <= 1.5+ shape = cycle["seam_pop"]+ assert shape["applied"] is True and shape["first_choice"]["pop"] > repair.SEAM_POP_REFERENCE+ assert shape["unread"] > 0 and shape["measured"] + shape["unread"] == cycle["candidate_count"]+ assert isinstance(shape["chosen"]["pop"], float) and "skipped" not in shape["chosen"]+ assert report["jolt"]["seam_pop"]["pops"] is False+ unread = [r for r in cycle["candidates"] if r.get("seam_pop_skipped")]+ assert all(r["seam_pop"] is None for r in unread)+++def _fake_pop(table):+ """A `wrap_pop` reading a table: (start, length) -> pop, or a reason string for a top it cannot read."""+ def pop(start, length):+ value = table[start, length]+ if isinstance(value, str):+ return {"skipped": value, "reference": repair.SEAM_POP_REFERENCE}+ return {"pop": value, "pops": value > repair.SEAM_POP_REFERENCE, "reference": repair.SEAM_POP_REFERENCE}+ return pop+++def test_shape_rank_keeps_an_unread_first_choice_and_never_chooses_an_unread_candidate():+ rows = [{"start": 0, "length": 24, "score": 1.0}, {"start": 3, "length": 24, "score": 1.01},+ {"start": 6, "length": 24, "score": 1.05}]+ chosen, record = local_cycle._shape_rank([dict(r) for r in rows], dict(rows[0]),+ _fake_pop({(0, 24): "a loop frame has no head to track"}))+ assert chosen["start"] == 0 and record["applied"] is False+ assert record["first_choice"] == {"start": 0, "length": 24, "skipped": "a loop frame has no head to track"}+ candidates = [dict(r) for r in rows]+ chosen, record = local_cycle._shape_rank(candidates, candidates[0], _fake_pop(+ {(0, 24): 14.0, (3, 24): "a loop frame has no head to track", (6, 24): 0.0}))+ assert chosen["start"] == 6 and record["chosen"] == {"start": 6, "length": 24, "pop": 0.0}+ assert record["measured"] == 2 and record["unread"] == 1+ assert candidates[1]["seam_pop"] is None and candidates[1]["seam_pop_skipped"]+ # Nothing read closes: the first choice is kept, not the unread one.+ candidates = [dict(r) for r in rows]+ chosen, record = local_cycle._shape_rank(candidates, candidates[0], _fake_pop(+ {(0, 24): 14.0, (3, 24): "a loop frame has no head to track", (6, 24): 12.0}))+ assert chosen["start"] == 0 and record["applied"] is False and "why" in record+++def test_a_refused_window_whose_top_cannot_be_read_is_not_listed_as_closing():+ values = np.arange(80) + np.sin(np.arange(80))+ D = np.abs(values[:, None] - values[None, :]).astype(np.float32)+ kinds = {}++ def pop(start, length):+ kind = kinds.setdefault((start, length), ("pops", "unread", "calm")[len(kinds) % 3])+ if kind == "unread":+ return {"skipped": "a loop frame has no head to track", "reference": repair.SEAM_POP_REFERENCE}+ value = 14.0 if kind == "pops" else 0.0+ return {"pop": value, "pops": kind == "pops", "reference": repair.SEAM_POP_REFERENCE}+ 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, wrap_pop=pop)+ rows = caught.value.diagnostics["candidates"]+ order = [kinds[r["start"], r["length"]] for r in rows]+ assert order == sorted(order, key=("calm", "unread", "pops").index) and "unread" in order+ for r in rows:+ assert (r["seam_pop"] is None) == (kinds[r["start"], r["length"]] == "unread") == ("seam_pop_skipped" in r)++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)])