Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
fix(video): a filmed ghost in a loop delivered as cut is given way in the jump repair; source-restoration-v5 reads the ghost
Soohong Kimbb3edf54131c
diff --git a/sprite_gen/video/align.py b/sprite_gen/video/align.pyindex 77bbea2..c44996f 100644--- a/sprite_gen/video/align.py+++ b/sprite_gen/video/align.py@@ -97,7 +97,7 @@ from sprite_gen.video import legs as legs_modfrom sprite_gen.video import loop as loop_modfrom sprite_gen.video import period as period_modfrom sprite_gen.video import rife as rife_mod-from sprite_gen.video.interpolation_quality import CROSSFADE_LOOK, SMEAR_WARN, OUTLINE_WARN, faults, ghost_screen, looks+from sprite_gen.video.interpolation_quality import CROSSFADE_LOOK, SMEAR_WARN, OUTLINE_WARN, clean_beside, faults, ghost_screen, looksSNAP = 0.03 # a sample time within this of a source frame takes that frameSOURCE_DIR = loop_mod.CYCLE_SOURCE_DIR # removed by video-loop whenever it cuts the loop again@@ -257,14 +257,15 @@ def resample(frames: list[Image.Image], length: int, interpolate: rife_mod.Intersmears: list[dict[str, Any]] = []ghost_at: list[dict[str, Any]] = []- def clean(k: int, first: int, other: int) -> int:- """`first` where the screen passes it, else `other` where it passes that (rife takes `first`- as it is); each ghost passed over or taken is listed in `ghost_at`, a ghost taken with why it was kept."""+ def clean(k: int, first: int, other: int | None) -> int:+ """`first` where the screen passes it, else `other`, the clean frame beside it, where there is one+ (rife takes `first` as it is); each ghost passed over or taken is listed in `ghost_at`, a ghost+ taken with why it was kept."""if first not in ghosts:return first- taken_ = first if between == "rife" or other in ghosts else other+ taken_ = first if between == "rife" or other is None else otherghost_at.append({"at": k, "source": first, "ghost": ghosts[first], "taken": taken_,- **({"kept": KEPT_NO_CLEAN if other in ghosts else KEPT_RIFE} if taken_ == first else {})})+ **({"kept": KEPT_NO_CLEAN if other is None else KEPT_RIFE} if taken_ == first else {})})return taken_for k in range(length):@@ -274,10 +275,9 @@ def resample(frames: list[Image.Image], length: int, interpolate: rife_mod.Internearer = (i + (frac >= 0.5)) % countbeside = (i + (frac < 0.5)) % count # the other frame beside the timeif frac < SNAP or frac > 1 - SNAP: # on a source frame (the nearer); a ghost there gives way to the frame after it, else before- after, before = (nearer + 1) % count, (nearer - 1) % count- taken: dict[str, Any] = {"source": clean(k, nearer, before if after in ghosts else after)}+ taken: dict[str, Any] = {"source": clean(k, nearer, clean_beside(nearer, ghosts, count))}elif between == "nearest":- taken = {"source": clean(k, nearer, beside)}+ taken = {"source": clean(k, nearer, None if beside in ghosts else beside)}nearest_at.append(k)else:if interpolate is None:@@ -288,7 +288,8 @@ def resample(frames: list[Image.Image], length: int, interpolate: rife_mod.Inter"crossfade": rife_mod.crossfade(made, a, b, frac)}wrong = faults(measure)keep = between == "rife" or not wrong- taken = {"between": [i % count, (i + 1) % count], "t": round(frac, 4)} if keep else {"source": clean(k, nearer, beside)}+ taken = ({"between": [i % count, (i + 1) % count], "t": round(frac, 4)} if keep+ else {"source": clean(k, nearer, None if beside in ghosts else beside)})(made_at if keep else nearest_at).append(k)smears.append({"at": k, "method": "rife" if keep else "nearest", **measure, "faults": wrong, "look": looks(measure)})out.append(made if "between" in taken else frames[taken["source"]])@@ -710,7 +711,7 @@ def _rebuild(loop_dir: Path, meta_path: Path, meta: dict[str, Any], frames: listshutil.rmtree(loop_dir / ".webp-frames", ignore_errors=True)# a GIF or WebP holds a frame shown twice in a row (`--between nearest` stretching a loop) as one# frame of twice the delay, so each is checked for one frame per run of identical cells- runs = 1 + sum(1 for a, b in zip(cells, cells[1:]) if a.tobytes() != b.tobytes())+ runs = loop_mod.shown_runs(cells)record["gif"] = loop_mod.verify_animation(gif_path, expect_frames=runs, check_stale=False)record["webp"] = loop_mod.verify_animation(webp_path, expect_frames=runs, check_stale=True)return mergeddiff --git a/sprite_gen/video/follow.py b/sprite_gen/video/follow.pyindex 4345871..ce58ede 100644--- a/sprite_gen/video/follow.py+++ b/sprite_gen/video/follow.py@@ -777,10 +777,12 @@ def follow_loop(loop_dir: Path, regions: list[tuple[float, float, float, float]]joined.save(staged[strip_path])save_clean_gif(out, staged[gif_path], duration_ms=delay_ms, loop=0, alpha_threshold=128)loop_mod.write_webp(out, staged[webp_path], delay_ms=delay_ms, workdir=stage / ".webp-frames")+ # a cell left as it was beside its twin (a filmed ghost given way to the frame beside it) is one frame of both+ shown = loop_mod.shown_runs(out)record = {**answer.record(),- "gif": loop_mod.verify_animation(staged[gif_path], expect_frames=n, check_stale=False),- "webp": loop_mod.verify_animation(staged[webp_path], expect_frames=n, check_stale=True),+ "gif": loop_mod.verify_animation(staged[gif_path], expect_frames=shown, check_stale=False),+ "webp": loop_mod.verify_animation(staged[webp_path], expect_frames=shown, check_stale=True),}atomic_write_text(staged[meta_path], json.dumps({**meta, "follow": record}, indent=2) + "\n")for path, written in staged.items(): # the record last, as it was written lastdiff --git a/sprite_gen/video/interpolation_quality.py b/sprite_gen/video/interpolation_quality.pyindex 84274c5..1d43be8 100644--- a/sprite_gen/video/interpolation_quality.py+++ b/sprite_gen/video/interpolation_quality.py@@ -3,10 +3,12 @@Measurements live in ``rife`` (``smear``, ``ghost``, ``crossfade``); these are the existing alignmentbounds, also applied before replacing a filmed middle frame during jump repair, the ghost screen-every frame a loop path delivers passes, filmed or made, and the cross-fade a made frame is named-for, kept (docs/loop-repair.md section 4).+every frame a loop path delivers passes, filmed or made, the clean frame a filmed ghost gives way+to, and the cross-fade a made frame is named for, kept (docs/loop-repair.md section 4)."""+from collections.abc import Container+from PIL import Imagefrom sprite_gen._deps import np@@ -54,3 +56,12 @@ def ghost_screen(frames: list[Image.Image]) -> dict:return {**record, "ghosts": [], "why": f"the loop is drawn part-covered: its median frame reads {level:.5f}, over the "f"{GHOST_WARN} that names a ghost"}return {**record, "ghosts": [{"frame": i, "ghost": v} for i, v in enumerate(readings) if v > GHOST_WARN]}+++def clean_beside(frame: int, ghosts: Container[int], count: int) -> int | None:+ """The frame of a loop of `count` frames a filmed ghost at `frame` gives way to: the frame after+ it where the screen passes it (`ghosts` are the frames it names), else the one before it; None+ where both are ghosts too, and the ghost is kept. The cycle alignment takes it at a time on a+ ghost, and the jump repair of `video-loop` where its frame between the two is not taken."""+ after, before = (frame + 1) % count, (frame - 1) % count+ return after if after not in ghosts else before if before not in ghosts else Nonediff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.pyindex 168491e..57d4fb2 100644--- a/sprite_gen/video/loop.py+++ b/sprite_gen/video/loop.py@@ -850,42 +850,85 @@ def write_loop_report(target: Path, payload: dict[str, Any]) -> None:atomic_write_text(target, json.dumps(finite(payload), ensure_ascii=False, indent=2, allow_nan=False) + "\n")+def shown_runs(cells: list[Image.Image]) -> int:+ """The frames a GIF or WebP of `cells` holds: a cell shown twice in a row (a filmed ghost given way+ to the frame beside it, `--between nearest` stretching a loop) is one frame of twice the delay in+ both, so one per run of identical cells."""+ return 1 + sum(1 for a, b in zip(cells, cells[1:]) if a.tobytes() != b.tobytes())++def _repair_jumps(frames: list[Image.Image], interpolate: rife_mod.Interpolate | None, *, facing: str,- required: bool) -> tuple[list[Image.Image], dict[str, Any]]:- """`repair_mod.repair_jumps`, with RIFE located only once a frame is to be made: a loop- without a jump needs no binary. The report names the interpolator that made the frames.+ required: bool, screen: dict[str, Any]) -> tuple[list[Image.Image], dict[str, Any]]:+ """`repair_mod.repair_jumps` on the cut as filmed and its ghost `screen`, with RIFE located only+ once a frame is to be made: a loop without a jump or a ghost between two clean frames needs no+ binary. The report names the interpolator that made the frames.A frame to make and no RIFE installed: `required` lets `RifeNotInstalled` through; otherwise- the loop comes back as filmed and the record says why (`applied: false`, `rife`, `install`)."""+ each filmed ghost gives way to the clean frame beside it, a jump stays as filmed, and the record+ says why where a jump was left (`rife`, `install`; `applied` false where nothing was replaced)."""made_by: list[dict[str, str]] = []+ calls = 0def lazy(a: Image.Image, b: Image.Image, t: float) -> Image.Image:- nonlocal interpolate+ nonlocal interpolate, callsif interpolate is None:located = rife_mod.Rife()made_by.append(located.describe())interpolate = located+ calls += 1return interpolate(a, b, t)try:- repaired, record = repair_mod.repair_jumps(frames, lazy, facing=facing)+ repaired, record = repair_mod.repair_jumps(frames, lazy, facing=facing, screen=screen)except rife_mod.RifeNotInstalled as exc:if required:raise- # RIFE is located before the first frame is made, so nothing was replaced yet.- worst = round(float(repair_mod.jump_scores(frames, facing=facing)["score"].max()), 4)- return frames, {"applied": False, "why": "RIFE not installed — cut as filmed", "rife": str(exc),- "install": rife_mod.INSTALL_COMMAND, "ratio": repair_mod.JUMP_RATIO, "facing": facing,- "score_max_before": worst, "score_max_after": worst, "replaced": []}+ # RIFE is located before the first frame is made, so nothing was made yet: the stage runs again+ # with no interpolator, each ghost giving way to the clean frame beside it and a jump left as filmed.+ repaired, record = repair_mod.repair_jumps(frames, None, facing=facing, screen=screen)+ record["applied"] = bool(record["replaced"])+ if "unmade" in record:+ record.update(why="RIFE not installed — cut as filmed" if not record["replaced"] else+ "RIFE not installed — the jump cut as filmed, each filmed ghost given way to the clean frame beside it",+ rife=str(exc), install=rife_mod.INSTALL_COMMAND)+ return repaired, recordframes = repairedrecord["applied"] = bool(record["replaced"])if made_by:record["interpolator"] = {"kind": "rife-ncnn-vulkan", **made_by[0]}- elif record["attempts"]:+ elif calls:record["interpolator"] = {"kind": "injected"}return frames, record+def _ghost_lines(jump_repair: dict[str, Any]) -> list[str]:+ """What became of each filmed ghost the jump repair stage read, in words (`video-loop: warning:` lines)."""+ lines = []+ for r in jump_repair.get("rounds", []):+ if r.get("why") != "ghost":+ continue+ j = r["target"]+ line = (f"frame {j} of the cut carries a part-covered band over {100 * r['original']['ghost']:.2f} % of its body, at least "+ f"{rife_mod.GHOST_THICK} px thick — a filmed ghost; ")+ if r["taken"] == "rife":+ lines.append(line + f"given way to RIFE's frame between frames {r['neighbours'][0]} and {r['neighbours'][1]} "+ f"(cycle/frame-{j:03d}.png) (docs/loop-repair.md section 2)")+ continue+ if r["taken"] is None:+ lines.append(line + f"and so are the frames beside it ({r['neighbours'][0]} and {r['neighbours'][1]}); kept, as there "+ f"is no clean frame to give way to (cycle/frame-{j:03d}.png) — film this direction again (docs/loop-repair.md section 2)")+ continue+ if r["proposal"] is not None:+ why = f"RIFE's frame between its neighbours has a fault ({', '.join(r['faults'])})"+ elif r["no_proposal"] == "no interpolator":+ why = f"RIFE is not installed, so no frame between its neighbours was made (`{rife_mod.INSTALL_COMMAND}`)"+ else:+ why = r["no_proposal"]+ lines.append(line + f"given way to frame {r['taken']['source']} beside it, shown twice in a row (cycle/frame-{j:03d}.png): "+ f"{why} (docs/loop-repair.md section 2)")+ return lines++def moved_alpha(frames: list[Image.Image], analysis: dict[str, Any]) -> list[np.ndarray]:"""The alpha of every frame, each moved by the analysis translation `auto_motion.analyse` measured(its drift taken out, the way the cut will be corrected), cropped once to the clip's subject:@@ -1298,22 +1341,37 @@ def run_loop("recipe": RECIPE, "wrap_dx_px": wrap_dx,"before_repair_pixels_sha256": [evidence_mod.digest(f.tobytes()) for f in frames],}+ if prof.gait:+ # The ghost screen of the cut as filmed (docs/loop-repair.md section 4), read before the jump repair: each+ # filmed ghost it names is a target of that repair, which gives it way to a clean frame where there is one.+ # A loop delivered as cut, never aligned, would show it otherwise.+ report_base["ghost_screen"] = ghost_screen(frames)if repair != "off" and prof.gait:report_base["jump_repair"] = Nonetry:- frames, report_base["jump_repair"] = _repair_jumps(frames, interpolate, facing=facing, required=repair == "on")+ frames, report_base["jump_repair"] = _repair_jumps(frames, interpolate, facing=facing, required=repair == "on",+ screen=report_base["ghost_screen"])except (ValueError, rife_mod.RifeUnavailable) as exc:fix = (f"install RIFE (`{rife_mod.INSTALL_COMMAND}`), or pass --repair auto to cut it as filmed with a warning"if isinstance(exc, rife_mod.RifeNotInstalled) else "fix RIFE, or pass --repair off to cut it as filmed")- error = f"video-loop: {exc}; the loop has a jump frame to repair — {fix} (docs/loop-repair.md)"+ error = (f"video-loop: {exc}; the loop has a frame to make (after a jump, or for a filmed ghost between two clean "+ f"frames) — {fix} (docs/loop-repair.md)")shutil.rmtree(out_dir / FALLBACK_FRAMES_DIR, ignore_errors=True)write_loop_report(target, {**report_base, "status": "failed", "error": error, "cycle": cycle})raise SystemExit(error) from excif report_base["jump_repair"]["replaced"]:report_base["seam_measurement"] = "rendered-cells"+ # What became of each filmed ghost: given way (the cell and what it shows now) or kept, no clean frame beside it.+ ghost_rounds = [r for r in report_base["jump_repair"]["rounds"] if r.get("why") == "ghost"]+ report_base["ghost_given_way"] = [{"frame": r["target"], "ghost": r["original"]["ghost"], "taken": r["taken"]}+ for r in ghost_rounds if r["taken"] is not None]+ report_base["ghost_kept"] = [{"frame": r["target"], "ghost": r["original"]["ghost"]} for r in ghost_rounds if r["taken"] is None]+ for line in _ghost_lines(report_base["jump_repair"]):+ print(f"video-loop: warning: {line}", file=sys.stderr)for r in report_base["jump_repair"].get("rounds", []):if r["outcome"] == "accepted" and r["look"]:- print(f"video-loop: warning: frame {r['target']} was repaired with RIFE's frame between its neighbours, which may "+ print(f"video-loop: warning: frame {r['target']} was {'given way for a filmed ghost' if r['why'] == 'ghost' else 'repaired'} "+ "with RIFE's frame between its neighbours, which may "f"cross-fade two drawings inside its outline (crossfade {r['proposal']['crossfade']:.4f}); kept, a reading to ""look at — see it in the loop, or cut it with --repair off (docs/loop-repair.md section 4)", file=sys.stderr)if "rife" in report_base["jump_repair"]:@@ -1351,14 +1409,13 @@ def run_loop(raise SystemExit(error)for line in warnings:print(f"video-loop: warning: {line} (reference bound; the loop is kept — docs/loop-repair.md)", file=sys.stderr)- # The ghost screen of the cut as delivered (docs/loop-repair.md section 4): a loop delivered as cut,- # never aligned, carries a filmed ghost as it is, so each is named here; `video-cycle-align` screens- # its source again and takes a clean frame beside it.- report_base["ghost_screen"] = ghost_screen(frames)- for g in report_base["ghost_screen"]["ghosts"]:- print(f"video-loop: warning: frame {g['frame']} of the cut (cycle/frame-{g['frame']:03d}.png) carries a part-covered band "- f"over {100 * g['ghost']:.2f} % of its body, at least {rife_mod.GHOST_THICK} px thick — a filmed ghost; delivered as cut "- "it shows, and video-cycle-align takes a clean frame beside it (docs/loop-repair.md)", file=sys.stderr)+ if "ghost_given_way" not in report_base:+ # The jump repair did not run (--repair off): a filmed ghost is delivered as cut, named here;+ # `video-cycle-align` screens its source again and takes a clean frame beside it.+ for g in report_base["ghost_screen"]["ghosts"]:+ print(f"video-loop: warning: frame {g['frame']} of the cut (cycle/frame-{g['frame']:03d}.png) carries a part-covered band "+ f"over {100 * g['ghost']:.2f} % of its body, at least {rife_mod.GHOST_THICK} px thick — a filmed ghost; delivered as cut "+ "it shows (--repair off), and video-cycle-align takes a clean frame beside it (docs/loop-repair.md)", file=sys.stderr)if not report_base["ghost_screen"]["reads"]:print(f"video-loop: warning: the ghost screen does not read this cut — {report_base['ghost_screen']['why']}; no frame ""of it is named a ghost, here or in video-cycle-align, so look at cycle/ (docs/loop-repair.md)", file=sys.stderr)@@ -1400,6 +1457,12 @@ def run_loop(strip_meta["drawings"] = {k: report_base["drawings"][k] for k in ("hold", "drawings_per_second", "contrast", "frames")}strip_meta["cycle_drawings"] = {k: report_base["cycle_drawings"][k] for k in ("start", "length", "steps", "hold", "drawings_per_second", "contrast")} | ({"why": report_base["cycle_drawings"]["why"]} if "why" in report_base["cycle_drawings"] else {})+ # A cut frame that is no longer the frame as filmed for a filmed ghost, and one kept with no clean frame beside+ # it: `cycle/` is the alignment's material (`cycle.source/`), whose screen no longer sees a ghost given way, so the+ # strip says it, and an alignment carries it over (frames of the cut).+ for key in ("ghost_given_way", "ghost_kept"):+ if report_base.get(key):+ strip_meta[key] = report_base[key]if motion is not None:strip_meta["foot_anchor"] = anchorstrip_meta["motion_anchor"] = motion@@ -1463,8 +1526,10 @@ def run_loop(save_clean_gif(pick, gif_path, duration_ms=delay_ms, loop=0, alpha_threshold=128)write_webp(pick, webp_path, delay_ms=delay_ms, workdir=out_dir / ".webp-frames")shutil.rmtree(out_dir / ".webp-frames", ignore_errors=True)- gif_report = verify_animation(gif_path, expect_frames=n_out, check_stale=False)- webp_report = verify_animation(webp_path, expect_frames=n_out, check_stale=True)+ # A filmed ghost given way to the frame beside it is that frame shown twice in a row: one frame of the GIF or WebP+ shown = shown_runs(pick)+ gif_report = verify_animation(gif_path, expect_frames=shown, check_stale=False)+ webp_report = verify_animation(webp_path, expect_frames=shown, check_stale=True)payload = {**report_base,@@ -1567,6 +1632,9 @@ def run(**kwargs: object) -> int:summary["cycle"]["step_screen"] = payload["cycle"]["step_screen"]if payload.get("ghost_screen", {}).get("ghosts") or payload.get("ghost_screen", {}).get("reads") is False:summary["ghost_screen"] = payload["ghost_screen"]+ for key in ("ghost_given_way", "ghost_kept"):+ if payload.get(key):+ summary[key] = payload[key]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/playback.py b/sprite_gen/video/playback.pyindex 04c9836..0255c0a 100644--- a/sprite_gen/video/playback.py+++ b/sprite_gen/video/playback.py@@ -65,21 +65,36 @@ def mapping(loop: Any) -> tuple[list[int], int] | None:return [min(n - 1, round(k * n / count)) for k in range(count)], delay+def runs(loop: Any, indices: list[int]) -> list[tuple[int, int]]:+ """The strip cells `indices` play as (first index, frames shown): a cell shown again right after an+ identical one (a filmed ghost given way to the frame beside it) is one frame of a GIF or WebP, held+ that many delays."""+ out: list[tuple[int, int]] = []+ for index in indices:+ if out and loop.frames[out[-1][0]].tobytes() == loop.frames[index].tobytes():+ out[-1] = (out[-1][0], out[-1][1] + 1)+ else:+ out.append((index, 1))+ return out++def verify(loop: Any, animations: dict[str, Playback]) -> tuple[dict[str, Any], str | None]:recipe = mapping(loop)if recipe is None:return {}, "playback-schedule-unverified"indices, delay = recipe+ shown = runs(loop, indices)records = {}for key, fmt in (("gif", "GIF"), ("webp", "WEBP")):if key not in animations:return records, "playback-missing"animation = animations[key]- expected_delay = delay // 10 * 10 if fmt == "GIF" else delay- if (animation.format != fmt or animation.loop != 0 or len(animation.frames) != len(indices)- or animation.durations != [expected_delay] * len(indices)):+ # The GIF writer adds the delays of identical frames and stores the sum in hundredths of a second.+ durations = [count * delay // 10 * 10 if fmt == "GIF" else count * delay for _, count in shown]+ if (animation.format != fmt or animation.loop != 0 or len(animation.frames) != len(shown)+ or animation.durations != durations):return records, f"{key}:playback-schedule-mismatch"- for frame, index in zip(animation.frames, indices):+ for frame, index in zip(animation.frames, (index for index, _ in shown)):cell = loop.frames[index]expected = _prepare_transparent_frame(cell, 128).convert("RGBA") if fmt == "GIF" else cellif frame.size != cell.size or visible_bytes(frame) != visible_bytes(expected):diff --git a/sprite_gen/video/repair.py b/sprite_gen/video/repair.pyindex 8c1225d..6e81f39 100644--- a/sprite_gen/video/repair.py+++ b/sprite_gen/video/repair.py@@ -6,7 +6,10 @@ lands somewhere it was not one frame earlier: one step of the loop changes far mloop's usual step. That step is a jump; the frame after it is replaced by the frame RIFE makeshalf-way between its two neighbours, and every other frame stays the video's own(docs/loop-repair.md section 2). Re-making every frame instead (an offset of half a frame) also-softens the frames that were fine, and was judged "not corrected" (2026-10-03).+softens the frames that were fine, and was judged "not corrected" (2026-10-03). A frame the+ghost screen names a filmed ghost is replaced in the same stage, before the jumps are read: by+RIFE's frame between its neighbours where both are clean and it has no fault, else by the clean+frame beside it (docs/loop-repair.md section 4).Measured on the loop as it plays — cyclic, the last frame followed by the first — and insidethe union box of the body over the whole loop, the way the strip cells are cut, so a frame's@@ -21,7 +24,7 @@ from PIL import Imagefrom sprite_gen._deps import npfrom sprite_gen.video.rife import Interpolate, crossfade, ghost, smear-from sprite_gen.video.interpolation_quality import faults, ghost_screen, looks+from sprite_gen.video.interpolation_quality import clean_beside, faults, ghost_screen, looks# A step this many times the loop's median step (whole body, or the hair behind it) is a jump.JUMP_RATIO = 1.4@@ -75,22 +78,68 @@ def jump_scores(frames: list[Image.Image], *, facing: str = "right", box: tuple[return {"whole": w, "hair": h, "score": np.maximum(w, h)}+def _give_way(frames: list[Image.Image], j: int, ghosts: dict[int, float], interpolate: Interpolate | None,+ out: list[Image.Image]) -> dict[str, Any]:+ """The round of a filmed ghost at `j` (`why` ghost), its cell replaced in `out` where it gives way.++ Where both frames beside it are clean, RIFE's frame half way between them is proposed and taken+ without a fault (`taken` rife); else, or where there is no interpolator, the clean frame beside it+ the cycle alignment would take (`interpolation_quality.clean_beside`, `taken` {source}); where+ both are filmed ghosts too it is kept (`taken` None)."""+ n = len(frames)+ a, b = (j - 1) % n, (j + 1) % n+ measure: dict[str, Any] | None = None+ wrong: list[str] = []+ no_proposal = ("a frame beside it is a filmed ghost too" if a in ghosts or b in ghosts+ else "no interpolator" if interpolate is None else None)+ if no_proposal is None:+ assert interpolate is not None+ made = interpolate(frames[a], frames[b], 0.5)+ if made.mode != "RGBA" or made.size != frames[j].size:+ raise ValueError("repair interpolator must return an RGBA frame of the original size")+ measure = {**smear(made, frames[a], frames[b]), "ghost": ghost(made), "crossfade": crossfade(made, frames[a], frames[b], 0.5)}+ wrong = faults(measure)+ if not made.getchannel("A").getbbox():+ wrong.append("empty")+ beside = clean_beside(j, ghosts, n)+ taken: Any = "rife" if measure is not None and not wrong else {"source": beside} if beside is not None else None+ if taken == "rife":+ out[j] = made+ elif taken is not None:+ out[j] = frames[beside]+ return {"why": "ghost", "target": j, "neighbours": [a, b],+ "original": {**smear(frames[j], frames[a], frames[b]), "ghost": ghosts[j]},+ "proposal": measure, **({"no_proposal": no_proposal} if no_proposal else {}), "faults": wrong,+ "look": looks(measure) if measure is not None else [], "taken": taken,+ "outcome": "accepted" if taken == "rife" else "given-way" if taken is not None else "kept",+ **({"replaced": j} if taken is not None else {})}++def repair_jumps(frames: list[Image.Image], interpolate: Interpolate | None, *, facing: str = "right",- ratio: float = JUMP_RATIO, max_frames: int = MAX_REPAIRS) -> tuple[list[Image.Image], dict[str, Any]]:- """Replace the frame that breaks each jump with RIFE's frame between its neighbours, worst jump first.-- At most `max_frames` calls, and never next to a frame already made: two made frames side by side- are made from each other and melt the legs. A proposal with a shared interpolation-quality- fault — a ghost too, on its own coverage, where the loop's ghost screen reads it — keeps the- original middle frame; a proposal that cross-fades two drawings inside its silhouette is still- taken, its round naming it (`look`). Blocked and rejected targets do not end the search- for independent targets. `interpolate` may be None while no jump is- found; it is asked for only when a frame is to be made (a ValueError says so otherwise).- Scores are re-read after each replacement, on the union box of the original loop."""+ ratio: float = JUMP_RATIO, max_frames: int = MAX_REPAIRS,+ screen: dict[str, Any] | None = None) -> tuple[list[Image.Image], dict[str, Any]]:+ """Replace each filmed ghost the screen names, then the frame that breaks each jump with RIFE's+ frame between its neighbours, worst jump first.++ `screen` is the ghost screen of `frames` as filmed (`interpolation_quality.ghost_screen`, read+ here when not given). Each ghost it names is a round of its own (`why` ghost, in frame order,+ outside the call budget): RIFE's frame between its two neighbours where both are clean and the+ frame has no fault, else the clean frame beside it (the frame after it, else the one before it),+ else, both being filmed ghosts too, the ghost kept (`_give_way`). The jumps are then read on+ the loop as the ghosts left it (`why` jump): at most `max_frames` calls, and never next to a+ frame already made or given way: two made frames side by side are made from each other and+ melt the legs. A proposal with a shared interpolation-quality fault — a ghost too, on its own+ coverage, where the screen reads the loop — keeps the original middle frame; a proposal that+ cross-fades two drawings inside its silhouette is still taken, its round naming it (`look`).+ Blocked and rejected targets do not end the search for independent targets. `interpolate` may+ be None: a ghost then gives way to the clean frame beside it, and the jump search stops at the+ first frame it would make, naming it (`unmade`). Scores are re-read after each replacement, on+ the union box of the original loop."""out = list(frames)n = len(out)box = union_box(frames)- reads: bool | None = None # whether the ghost screen reads the loop as filmed, once a frame is made+ screen = screen if screen is not None else ghost_screen(frames)+ reads = bool(screen["reads"])first = jump_scores(out, facing=facing, box=box)record: dict[str, Any] = {"ratio": ratio, "max_frames": max_frames, "facing": facing, "hair_box": list(hair_box(facing)),@@ -101,10 +150,16 @@ def repair_jumps(frames: list[Image.Image], interpolate: Interpolate | None, *,record.update(stopped="loop shorter than 4 frames", score_max_after=record["score_max_before"])return out, recordreplaced: list[int] = []+ ghosts = {g["frame"]: g["ghost"] for g in screen["ghosts"]}+ for j in sorted(ghosts):+ round_ = _give_way(frames, j, ghosts, interpolate, out)+ record["rounds"].append(round_)+ if "replaced" in round_:+ replaced.append(j)attempted: set[int] = set()blocked: set[int] = set()stopped = f"{max_frames} interpolation calls used"- scores = first+ scores = jump_scores(out, facing=facing, box=box) if replaced else firstfor _ in range(max_frames):selected = Nonefor k0 in np.argsort(-scores["score"], kind="stable"):@@ -131,19 +186,19 @@ def repair_jumps(frames: list[Image.Image], interpolate: Interpolate | None, *,breakk, j, score = selectedif interpolate is None:- raise ValueError(f"frame {j} follows a jump ({score:.2f}x the median step) and no interpolator is available")+ record["unmade"] = {"step": [k, (k + 1) % n], "target": j, "score": round(score, 4)}+ stopped = "a frame to make after a jump and no interpolator"+ breaka, b = out[(j - 1) % n], out[(j + 1) % n]made = interpolate(a, b, 0.5)if made.mode != "RGBA" or made.size != out[j].size:raise ValueError("repair interpolator must return an RGBA frame of the original size")attempted.add(j)- if reads is None:- reads = ghost_screen(frames)["reads"]measure = {**smear(made, a, b), "ghost": ghost(made) if reads else None, "crossfade": crossfade(made, a, b, 0.5)}wrong = faults(measure)if not made.getchannel("A").getbbox():wrong.append("empty")- record["rounds"].append({"step": [k, (k + 1) % n], "target": j, "score": round(score, 4),+ record["rounds"].append({"why": "jump", "step": [k, (k + 1) % n], "target": j, "score": round(score, 4),"whole": round(float(scores["whole"][k]), 4), "hair": round(float(scores["hair"][k]), 4),"original": {**smear(out[j], a, b), "ghost": ghost(out[j]) if reads else None},"proposal": measure, "faults": wrong, "look": looks(measure),diff --git a/sprite_gen/video/restoration.py b/sprite_gen/video/restoration.pyindex e5133f7..b1cfb56 100644--- a/sprite_gen/video/restoration.py+++ b/sprite_gen/video/restoration.py@@ -16,6 +16,9 @@ bridge stops the operation. All quality measurements consume final pixels.A target is a cell the jump repair replaced because a step into or out of thesource frame there jumped. Restoring that frame's pixels can restore the jump:acceptance also reads the jump repair's own step score around the changed cell.+The jump repair also replaces a filmed ghost, a frame the ghost screen names, and+restoring it would deliver the ghost again: a cell whose source frame the cut's+screen names is never a target, and acceptance reads the ghost on final pixels."""from __future__ import annotations@@ -37,15 +40,15 @@ from sprite_gen.spec.runio import atomic_write_textfrom sprite_gen.util import resamplefrom sprite_gen.video import evidence, playback, repair, rife, sourcefrom sprite_gen.video.compare import KIND as COMPARISON_KIND, Loop-from sprite_gen.video.interpolation_quality import SMEAR_WARN, OUTLINE_WARN, faults+from sprite_gen.video.interpolation_quality import GHOST_WARN, SMEAR_WARN, OUTLINE_WARN, faults, ghost_screen-METRIC = "source-restoration-v4"-POLICY = "key-protected-source-copy-one-step-cap-jump-guard-v1"+METRIC = "source-restoration-v5"+POLICY = "key-protected-source-copy-one-step-cap-jump-ghost-guard-v1"SCOPE = "processing-defect-restoration"OPERATION = "restore_active_cut"KIND = "sprite-gen-video-loop-restoration"-REPAIR_SCHEMA = 3-COMPARISON_SCHEMA = 5+REPAIR_SCHEMA = 4+COMPARISON_SCHEMA = 6MAX_PROPOSALS = 3ARTIFACTS = ("strip", "meta", "report", "gif", "webp")LISTED = 256 # capped or protected pixels a report spells out; the masks always hold all of them@@ -65,8 +68,17 @@ def read_loop(paths: dict[str, Path]) -> tuple[Loop, dict[str, playback.Playbackreturn loop, animations-def measure(frames: list[Image.Image], neighbours: list[Image.Image]) -> list[dict[str, float]]:- return [rife.smear(f, neighbours[k - 1], neighbours[(k + 1) % len(frames)]) for k, f in enumerate(frames)]+def measure(frames: list[Image.Image], neighbours: list[Image.Image], reads: bool) -> list[dict[str, float | None]]:+ """Each frame against its two neighbours (`rife.smear`) and its own ghost reading (`rife.ghost`), where the+ cut's ghost screen reads the loop (`reads`; None otherwise), so `faults` judges both."""+ return [{**rife.smear(f, neighbours[k - 1], neighbours[(k + 1) % len(frames)]), "ghost": rife.ghost(f) if reads else None}+ for k, f in enumerate(frames)]+++def filmed_screen(projection: source.Projection) -> dict[str, Any]:+ """The ghost screen of the cut's source frames as the cut read them (`interpolation_quality.ghost_screen`),+ at their own size: the frames each cell was resampled from (`projection.cropped`)."""+ return ghost_screen(projection.cropped)def _key_hue(rgba: Any, key: str) -> Any:@@ -187,12 +199,17 @@ def _describe(part: Partial, origin: Image.Image, reference: Image.Image, croppedef proposals(frames: list[Image.Image], projection: source.Projection, shown: list[int],- applied: list[int]) -> list[int]:+ applied: list[int], screen: dict[str, Any]) -> list[int]:+ """The cells to restore, worst first: a cell the jump repair replaced (`repair_hints`) whose final pixels+ carry an interpolation fault, against its own neighbours and the source's, that the source frame at its+ time does not — and whose source frame the cut's ghost `screen` does not name: the cut gave that ghost way."""ref = projection.frames- actual, fixed, original = measure(frames, frames), measure(frames, ref), measure(ref, ref)+ reads = bool(screen["reads"])+ actual, fixed, original = measure(frames, frames, reads), measure(frames, ref, reads), measure(ref, ref, reads)boundary = {0, len(ref) - 1, shown[0], shown[-1]}+ filmed = {g["frame"] for g in screen["ghosts"]}eligible = [k for k in projection.record["repair_hints"] if k in shown and k not in boundary and k not in applied- and frames[k].tobytes() != ref[k].tobytes()+ and k not in filmed and frames[k].tobytes() != ref[k].tobytes()and faults(actual[k]) and faults(fixed[k]) and not faults(original[k])]return sorted(eligible, key=lambda k: (-max(fixed[k]["outline_loss"], fixed[k]["dark_excess"]), k))[:MAX_PROPOSALS]@@ -268,12 +285,26 @@ def jump(before: list[Image.Image], after: list[Image.Image], ref: list[Image.Im"status": _status([(c["baseline"], c["candidate"]) for c in cells])}+def ghost_axis(a_final: list[dict[str, Any]], b_final: list[dict[str, Any]], reference: list[dict[str, Any]],+ screen: dict[str, Any]) -> dict[str, Any]:+ """Each cell's own ghost reading (`rife.ghost`) on final pixels, beyond GHOST_WARN: any rise regresses it.+ `filmed` is the screen of the cut's source frames; where it does not read the loop (drawn part-covered)+ no cell is judged, as in the cut."""+ if not screen["reads"]:+ return {"filmed": screen, "threshold": GHOST_WARN, "status": "non_regressing", "reason": "loop-drawn-part-covered"}+ a, b = ([q["ghost"] for q in row] for row in (a_final, b_final))+ return {"baseline": a, "candidate": b, "reference": [q["ghost"] for q in reference], "threshold": GHOST_WARN,+ "filmed": screen, "status": _status([(max(0, x - GHOST_WARN), max(0, y - GHOST_WARN)) for x, y in zip(a, b)])}++def judge(before: list[Image.Image], after: list[Image.Image], ref: list[Image.Image], key: str,- facing: str | None) -> dict[str, Any]:- """The protections over final pixels, from one loop's cells to the next's."""+ facing: str | None, screen: dict[str, Any]) -> dict[str, Any]:+ """The protections over final pixels, from one loop's cells to the next's. `screen` is the cut's ghost+ screen of its source frames (`filmed_screen`)."""changed = [k for k, (a, b) in enumerate(zip(before, after)) if a.tobytes() != b.tobytes()]- a_final, b_final, reference = measure(before, before), measure(after, after), measure(ref, ref)- a_fixed, b_fixed = measure(before, ref), measure(after, ref)+ reads = bool(screen["reads"])+ a_final, b_final, reference = measure(before, before, reads), measure(after, after, reads), measure(ref, ref, reads)+ a_fixed, b_fixed = measure(before, ref, reads), measure(after, ref, reads)axes: dict[str, Any] = {}for metric, threshold in (("outline_loss", OUTLINE_WARN), ("dark_excess", SMEAR_WARN)):a, b = ([max(0, q[metric] - threshold) for q in row] for row in (a_final, b_final))@@ -296,6 +327,8 @@ def judge(before: list[Image.Image], after: list[Image.Image], ref: list[Image.I"status": "regressed" if any(r.any() for r in raised) else "non_regressing"}# A rise brings back what the jump repair took out: a measured worsening, so `regressed`, as on every axis.axes["jump"] = jump(before, after, ref, changed, facing)+ # So does a ghost: the jump repair gave a filmed ghost way, and its source frame would bring it back.+ axes["ghost"] = ghost_axis(a_final, b_final, reference, screen)cleared = [{"cell": k, "faults": sorted(set(faults(a_final[k])) - set(faults(b_final[k])))} for k in changed]regressed = [k + ":regressed" for k, v in axes.items() if v["status"] == "regressed"]if regressed:@@ -316,9 +349,10 @@ class Chain:facing: str | None # the jump repair's; None only when it replaced no cell, so there is no targetshown: list[int]applied: list[dict[str, Any]]+ screen: dict[str, Any] # the ghost screen of the cut's source frames (`filmed_screen`)def targets(self, frames: list[Image.Image]) -> list[int]:- return proposals(frames, self.projection, self.shown, [e["target"] for e in self.applied])+ return proposals(frames, self.projection, self.shown, [e["target"] for e in self.applied], self.screen)def chain(origin: Loop, current: Loop, src: source.Source) -> tuple[Chain | None, str | None]:@@ -354,7 +388,7 @@ def chain(origin: Loop, current: Loop, src: source.Source) -> tuple[Chain | Noneschedule = playback.mapping(origin)if schedule is None:return None, "playback-schedule-unverified"- state = Chain(projection, key, facing, schedule[0], [])+ state = Chain(projection, key, facing, schedule[0], [], filmed_screen(projection))if receipt is None:return state, Noneapplied = receipt.get("applied")@@ -374,7 +408,7 @@ def chain(origin: Loop, current: Loop, src: source.Source) -> tuple[Chain | Nonepart = partial(origin.frames[target], projection.frames[target], projection.cropped[target], key)after = [part.frame if k == target else f for k, f in enumerate(frames)]if (part.alpha_conflict or _portable(entry) != _portable(_entry(target, part, origin, previous, frames, src, projection))- or judge(frames, after, projection.frames, key, facing)["verdict"] != "improved"):+ or judge(frames, after, projection.frames, key, facing, state.screen)["verdict"] != "improved"):raise ValueError("an applied restoration is not reproduced by the origin, the source and the protections")state.applied.append(entry)frames = after@@ -398,6 +432,8 @@ def _base(origin: Loop, baseline: Loop, candidate: Loop, src: source.Source) ->"one step is the least a channel can change: a bound on the cap, not a verdict on how it looks","the jump guard reads coverage, not colour: a wrong colour in a source frame is seen only ""through the jump it came with",+ "the ghost guard reads a band of part coverage at least 5 px thick, on the cut's source frames and "+ "on final cells: a thinner one, or one the cell's size thins under it, is not seen","source and origin receipts bind supplied bytes; they are not signatures of the original producer"]}@@ -461,7 +497,7 @@ def compare(origin: Loop, baseline: Loop, candidate: Loop, src: source.Source, *receipt = _receipt(origin, src, projection, [*state.applied, entry])if _portable(candidate.source_report) != _portable({**baseline.source_report, "restoration": receipt}):return finish("unknown", ["candidate-report-differs-from-verified-receipt"])- measured = judge(baseline.frames, candidate.frames, ref, state.key, state.facing)+ measured = judge(baseline.frames, candidate.frames, ref, state.key, state.facing, state.screen)result["axes"] = {**measured["axes"], "seam": {"status": "non_regressing", "reason": "strip-and-playback-boundary-cells-and-durations-exact"}}result["gait"]["source_order"] = "preserved"