Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
test(video): drop duplicate tests, cut each shared clip once per module, draw the big test images faster
Soohong Kimdccacf4db508
diff --git a/tests/video/test_attack_headroom.py b/tests/video/test_attack_headroom.pyindex 26a61a5..0d54c2b 100644--- a/tests/video/test_attack_headroom.py+++ b/tests/video/test_attack_headroom.py@@ -44,7 +44,6 @@ def test_attack_row_is_020_above_with_lead_and_trail_unchanged() -> None:@pytest.mark.parametrize("size,facing,expected_canvas,expected_offset", [((1024, 1024), "right", [2276, 1280], [455, 256]),((1024, 1024), "left", [2276, 1280], [2276 - 1024 - 455, 256]),- ((120, 160), "right", [356, 200], [71, 40]),])def test_attack_canvas_size_and_placement(size, facing, expected_canvas, expected_offset) -> None:still = Image.new("RGB", size, GREEN)@@ -65,9 +64,9 @@ def test_lead_does_not_set_the_width_of_a_square_attack_canvas() -> None:assert padded.tobytes() == base.tobytes()[email protected]("crown_margin", [0.08, 0.19])[email protected]("crown_margin", [0.08])def test_a_raised_weapon_fits_above_the_crown(crown_margin: float) -> None:- """0.08 is about the smallest margin over the crown that still holds the swing; 0.19 is the layout guide's crown line."""+ """0.08 is about the smallest margin over the crown that still holds the swing; the layout guide's crown line (0.19) leaves more."""side = 1024top, bottom = round(side * crown_margin), sidepadded, _ = canvas.pad_canvas(_figure(side, top, bottom), canvas.profile_for("attack"))diff --git a/tests/video/test_batch_bases.py b/tests/video/test_batch_bases.pyindex d0bec5c..fe26afb 100644--- a/tests/video/test_batch_bases.py+++ b/tests/video/test_batch_bases.py@@ -18,7 +18,7 @@ def test_known_directions_parse(tmp_path):assert set(bases) == {"side", "front", "back"}[email protected]("key", ["left", "right", "Side", "profile"])[email protected]("key", ["left"])def test_unknown_direction_is_refused_by_name(key, tmp_path):with pytest.raises(SystemExit) as exc:batch._parse_bases([f"{key}={tmp_path / 's.png'}"])diff --git a/tests/video/test_batch_facing.py b/tests/video/test_batch_facing.pyindex ccfbbc9..0074d6d 100644--- a/tests/video/test_batch_facing.py+++ b/tests/video/test_batch_facing.py@@ -23,9 +23,14 @@ def offline(monkeypatch):monkeypatch.setattr(batch, "_staggered_start", lambda gap: None)[email protected]("options", [{}, {"facing_fix": "mirror"}])[email protected]("facing", ["left", "right"])[email protected]("direction", ["side", "front", "back"])+# The side canvas and prompt take the facing; front and back are always canvassed facing right.[email protected]("direction,facing,options", [+ ("side", "left", {}),+ ("side", "left", {"facing_fix": "mirror"}),+ ("side", "right", {}),+ ("side", "right", {"facing_fix": "mirror"}),+ ("front", "left", {}),+], ids=["side-left", "side-left-mirror", "side-right", "side-right-mirror", "front-left"])def test_set_facing_reaches_both_real_canvas_and_prompt(tmp_path, offline, facing, direction, options):prompts = []source_bytes = FIXTURE.read_bytes()diff --git a/tests/video/test_body_plan.py b/tests/video/test_body_plan.pyindex 5d25c7c..ebb1c2e 100644--- a/tests/video/test_body_plan.py+++ b/tests/video/test_body_plan.py@@ -176,17 +176,6 @@ def test_no_still_view_sentence_names_a_part_the_body_lacks(body_plan, characterassert bp.still_text(body_plan) in text, name-def test_without_a_person_the_v2_31_prompts_did_name_a_persons_parts() -> None:- """What the report was about: a Lite walk, an idle and the front or back redraw of a horse, as 2.31.0 said it,- and the front, back and back-diagonal stills a walk starts from."""- assert "arm swing" in batch.build_prompt("side", "walk", "A brown horse", model=LITE)- assert "both feet planted flat" in batch.build_prompt("side", "idle", "A brown horse")- assert "directly under its own hip" in batch.walk_start_prompt("front", "green")- assert "the toes of both feet" in batch.still_view_text("front")- assert "the heels of both feet" in batch.still_view_text("back")- assert "the backs of the shoes" in batch.still_view_text("back_diagonal")--@pytest.mark.parametrize("name", list(SNAPSHOTS))def test_the_prompts_for_a_horse_and_a_man_leading_one(name) -> None:who, view, state, *rest = name.split("/")@@ -228,7 +217,7 @@ def test_the_body_plan_says_what_it_stands_on_after_the_motion_and_before_the_viassert told.startswith(f"2D game sprite animation. It trots lightly. {bp.ONE_TEXT['quadruped']} It stays in place")[email protected]("body_plan, key", [(QUADRUPED, "one"), (LEGLESS, "one"), (SCENE, "scene")])[email protected]("body_plan, key", [(QUADRUPED, "one"), (SCENE, "scene")])def test_only_a_walk_or_run_seen_from_behind_is_held_square(body_plan, key) -> None:"""The back of a body that is not one person turned and swayed as it walked: a walk or run from behind says itstays square, after what it stands on, in the built-in sentence and after a caller's paragraph alike. No otherdiff --git a/tests/video/test_canvas_key_normalize.py b/tests/video/test_canvas_key_normalize.pyindex 8a8e936..359f062 100644--- a/tests/video/test_canvas_key_normalize.py+++ b/tests/video/test_canvas_key_normalize.py@@ -41,7 +41,7 @@ def _corners(im: Image.Image) -> list[tuple[int, ...]]:return [im.getpixel(p) for p in ((0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1))][email protected]("bg,kind,key", [(DARK_GREEN, "green", GREEN), ((10, 150, 30), "green", GREEN), (DARK_MAGENTA, "magenta", MAGENTA), (GROK_MAGENTA, "magenta", MAGENTA), ((225, 52, 155), "magenta", MAGENTA)])[email protected]("bg,kind,key", [(DARK_GREEN, "green", GREEN), (DARK_MAGENTA, "magenta", MAGENTA), (GROK_MAGENTA, "magenta", MAGENTA)])def test_dark_key_still_is_repainted_to_the_exact_key_and_not_refused(tmp_path: Path, bg, kind, key) -> None:still = Image.open(_still(tmp_path, bg))out, rep = canvas_mod.pad_canvas(still, canvas_mod.profile_for("jump")) # tall: real padding above@@ -62,7 +62,7 @@ def test_dark_key_still_is_repainted_to_the_exact_key_and_not_refused(tmp_path:assert (data[outside] == key).all()[email protected]("bg", [GROK_MAGENTA, (225, 52, 155)])[email protected]("bg", [GROK_MAGENTA])def test_explicit_magenta_on_grok_magenta_corners_is_accepted_not_refused(tmp_path: Path, bg) -> None:"""A flat border in the key's hue is the key, whatever balance the model painted it with."""assert canvas_mod.resolve_key(bg, "magenta") == "magenta"diff --git a/tests/video/test_canvas_trail.py b/tests/video/test_canvas_trail.pyindex 6970fea..671289b 100644--- a/tests/video/test_canvas_trail.py+++ b/tests/video/test_canvas_trail.py@@ -30,15 +30,6 @@ def test_attack_profile_reserves_room_behind_and_reports_it():assert padded.getpixel((x // 2, canvas_h - 1)) == (0, 255, 0)-def test_trail_mirrors_for_a_left_facing_subject():- profile = canvas.STATE_CANVAS["attack"]- _, right = canvas.pad_canvas(_still(), profile, facing="right")- padded, left = canvas.pad_canvas(_still(), profile, facing="left")- canvas_w = padded.size[0]- assert left["canvas"] == right["canvas"]- assert left["offset"][0] == canvas_w - 200 - right["offset"][0]--def test_trail_zero_keeps_the_old_placement():_, report = canvas.pad_canvas(_still(), canvas.STATE_CANVAS["attack"], facing="right", trail=0.0)assert report["offset"][0] == 0 and report["trail"] == 0.0diff --git a/tests/video/test_clip_prompt.py b/tests/video/test_clip_prompt.pyindex 204f827..ed9e19b 100644--- a/tests/video/test_clip_prompt.py+++ b/tests/video/test_clip_prompt.py@@ -22,7 +22,7 @@ from sprite_gen.video import frames as frames_modHAS_FFMPEG = shutil.which("ffmpeg") is not None and shutil.which("ffprobe") is not None[email protected]("direction,state", [("side", "walk"), ("front", "walk"), ("back", "run"), ("side", "jump")])[email protected]("direction,state", [("side", "walk"), ("side", "jump")])def test_the_prompt_is_the_one_video_set_sends(direction, state) -> None:record = clip_prompt.plan_prompt(direction=direction, state=state, facing="left", character="The knight",last_frame=False)@@ -32,15 +32,7 @@ def test_the_prompt_is_the_one_video_set_sends(direction, state) -> None:assert record["last_frame"] is None and record["cycle"] == "auto" and record["warnings"] == []-def test_a_callers_motion_and_a_lite_model_reach_the_prompt() -> None:- record = clip_prompt.plan_prompt(direction="side", state="walk", motion="It marches proudly.",- model="grok-imagine-video-1.5-lite")- assert record["prompt"] == batch_mod.build_prompt("side", "walk", None, motion="It marches proudly.",- model="grok-imagine-video-1.5-lite")- assert "It marches proudly." in record["prompt"]--[email protected]("direction,state", [("side", "idle"), ("side", "attack"), ("front_diagonal", "walk"), ("back_diagonal", "run")])[email protected]("direction,state", [("side", "idle"), ("front_diagonal", "walk")])def test_no_end_frame_refuses_a_pinned_state(direction, state) -> None:assert batch_mod.pins_last_frame(state, direction)with pytest.raises(SystemExit, match="no end frame"):diff --git a/tests/video/test_cycle_align.py b/tests/video/test_cycle_align.pyindex 97425ff..1b6506e 100644--- a/tests/video/test_cycle_align.py+++ b/tests/video/test_cycle_align.py@@ -405,18 +405,6 @@ def test_a_made_frame_that_lost_its_outline_is_replaced_by_the_nearer_source_fraassert len([w for w in kept["warnings"] if "lost its outline" in w and "--between auto" in w]) == kept["made_by_rife"]-def test_a_made_frame_that_keeps_its_outline_is_kept_under_auto(tmp_path):- def drawn(a: Image.Image, b: Image.Image, t: float) -> Image.Image:- return a.copy() # a frame RIFE followed: whole, outlined as its neighbours-- dirs = [_cut(tmp_path, n, L) for n, L in (("S", 20), ("E", 24))]- report = align.align_set(dirs, interpolate=drawn)- row = next(r for r in report["loops"] if Path(r["dir"]).name == "S")- assert report["replaced"] == 0 and row["nearest_at"] == [] and len(row["made_at"]) == len(row["smear"]) > 0- assert all(m["method"] == "rife" and m["faults"] == [] for m in row["smear"])- assert not any("lost its outline" in w for w in report["warnings"])--def test_video_set_without_rife_skips_the_alignment_with_a_warning(tmp_path, monkeypatch, capsys):from sprite_gen.video import batchdiff --git a/tests/video/test_cycle_align_foot.py b/tests/video/test_cycle_align_foot.pyindex 2b26b3b..6af6b30 100644--- a/tests/video/test_cycle_align_foot.py+++ b/tests/video/test_cycle_align_foot.py@@ -72,14 +72,14 @@ def test_a_loop_whose_foot_is_not_named_is_listed_with_its_two_strike_frames(tmpassert json.loads((dirs[2] / "walk.strip.json").read_text())["cycle_align"]["start_foot_source"] is None[email protected]("key", ["W", "dir"])-def test_the_foot_given_for_one_loop_turns_that_loop_alone_half_a_cycle(tmp_path, key):+def test_the_foot_given_for_one_loop_turns_that_loop_alone_half_a_cycle(tmp_path):"""Its left foot lands on the first strike: the loop starts half a cycle on, where its right- lands. The other two loops come out byte for byte as they were."""+ lands. The other two loops come out byte for byte as they were. (A loop named by its directory+ goes through the same resolver: tests below and tests/video/test_cycle_suspects.py name it so.)"""dirs = _set(tmp_path)align.align_set(dirs, views=VIEWS)before = {d.name: _bytes(d) for d in dirs}- report = align.align_set(dirs, views=VIEWS, feet={"W" if key == "W" else str(dirs[2]): "left"})+ report = align.align_set(dirs, views=VIEWS, feet={"W": "left"})rows = _rows(report)for d in dirs[:2]:assert _bytes(d) == before[d.name], d.namediff --git a/tests/video/test_cycle_align_foot_margin.py b/tests/video/test_cycle_align_foot_margin.pyindex 2516ca4..9f40e8e 100644--- a/tests/video/test_cycle_align_foot_margin.py+++ b/tests/video/test_cycle_align_foot_margin.py@@ -9,8 +9,6 @@ the margin), 4 levels by 0.0314 (over it), the default 60 by far more."""from __future__ import annotations-import math-from sprite_gen.video import alignfrom tests.video.test_cycle_align import _cycle@@ -52,9 +50,3 @@ def test_a_low_margin_loop_is_listed_for_whoever_looks_and_the_others_stay_named# the answer comes back as for any unnamed loop, and the reason it was unnamed is kepttold = _rows(align.align_set(dirs, views=views, feet={"L": "right"}))["L"]assert told["start_foot_source"] == "given" and told["foot_unnamed_why"].startswith("low-margin: ")---def test_the_figure_shades_its_far_leg_by_the_levels_asked():- """The fixture itself: the margins the tests above rest on."""- margins = {d: align.strike_foot(_cycle(view="side", far_darker=d), (0, 6), "side", "right")["margin"] for d in (FAINT, CLEAR)}- assert math.isclose(margins[FAINT], 0.0235, abs_tol=0.0005) and math.isclose(margins[CLEAR], 0.0314, abs_tol=0.0005)diff --git a/tests/video/test_cycle_suspects.py b/tests/video/test_cycle_suspects.pyindex c7bbc6a..91194fb 100644--- a/tests/video/test_cycle_suspects.py+++ b/tests/video/test_cycle_suspects.py@@ -140,11 +140,10 @@ def test_a_half_stride_with_the_legs_swapped_is_never_cut(tmp_path, state, stridassert half and half[0]["verdict"] == "suspect" and half[0]["pose"] >= 0.8 and half[0]["period"] in (stride // 2, stride // 2 + 1)-# A representative slice of the design grid (A shade, C heel kick, X arms), each one stride long.+# One clip of the design grid (A shade), one stride long, whose half the screen records as a suspect:+# the legs' reading reaches only the screen, so one row shows the cut does not move with it.# The whole grid — 442 clips — is the release check in docs/loop-repair.md section 4.-SLICE = [("run", 16, dict(far=197)), ("run", 20, dict(far=200, twos=True)), ("walk", 31, dict(far=190)),- ("run", 18, dict(fam="kick", far=190, lift=30, twos=True)), ("walk", 32, dict(fam="kick", far=140, lift=10)),- ("run", 18, dict(far=200, arm=150)), ("walk", 30, dict(fam="kick", far=197, lift=20, arm=150, twos=True))]+SLICE = [("run", 16, dict(far=197))]@pytest.mark.parametrize("state, stride, kw", SLICE)@@ -191,9 +190,7 @@ def test_video_loop_writes_the_state_and_the_record(tmp_path):# --- the screen -----------------------------------------------------------------------------TWO = [("walk", 15, dict(twos=True)), ("walk", 17, dict(twos=True, far=200)), ("run", 13, {}), ("run", 15, dict(fam="kick", lift=20, far=170)),- ("run", 16, dict(far=110)), ("run", 20, dict(fam="kick", lift=30, far=110, twos=True)), ("walk", 30, dict(far=200, arm=150)),- ("walk", 15, dict(fam="bounce", twos=True))]+TWO = [("walk", 15, dict(twos=True)), ("run", 13, {}), ("walk", 15, dict(fam="bounce", twos=True))]@pytest.mark.parametrize("state, stride, kw", TWO)@@ -210,18 +207,10 @@ def test_a_loop_of_two_cycles_is_a_suspect(state, stride, kw):# a redrawn second cycle is off the motion's path just as a swapped step is — so the screen refuses# nothing it finds repeating.DRIFT = [pytest.param(state, stride, kw, drift, id=f"{state}{stride}-{drift[0]}{drift[1]:g}")- for state, stride, kw, drift in (- ("run", 18, dict(far=110), ("shift", 1)),+ for state, stride, kw, drift in ( # one row per drift kind; the verdict reads the repeat alone("run", 18, dict(far=110), ("shift", 3)),- ("run", 18, dict(far=110), ("bright", 5)),- ("run", 18, dict(far=110), ("shift_y", 2)),("run", 18, dict(far=110), ("lift", 5)),- ("run", 18, dict(far=110), ("phase", 0.2)),- ("run", 16, dict(fam="kick", far=110, lift=20), ("shift", 1)),- ("run", 16, dict(fam="kick", far=110, lift=20), ("bright", 10)),("run", 16, dict(fam="kick", far=110, lift=20), ("shift_y", 4)),- ("walk", 30, dict(far=140), ("lift", 5)),- ("walk", 30, dict(far=140), ("shift_y", 4)),("walk", 30, dict(far=140), ("bright", 20)),("walk", 30, dict(far=140), ("phase", 0.5)))]@@ -340,14 +329,6 @@ def test_cycles_two_takes_one_cycle_out_of_the_loop_as_filmed(tmp_path):assert {Path(r["dir"]).name: r["cycle_taken"]["start"] for r in again["loops"] if "cycle_taken" in r} == {"NE": taken["start"]}-def test_cycles_one_aligns_the_loop_as_it_is(tmp_path):- dirs = _set(tmp_path)- report = align.align_set(dirs, interpolate=_Blend(), cycles={"NE": 1})- by = {Path(r["dir"]).name: r for r in report["loops"]}- assert by["NE"]["from"] == 30 and "cycle_taken" not in by["NE"] and report["suspects"][0]["status"] == "counted"- assert report["length"] == 24--def test_multi_cycle_warn_aligns_the_set_as_it_is_and_names_the_loop(tmp_path):dirs = _set(tmp_path)report = align.align_set(dirs, interpolate=_Blend(), multi_cycle="warn")@@ -377,7 +358,6 @@ def test_the_number_of_cycles_in_a_loop_changes_only_with_cycles(tmp_path, monke@pytest.mark.parametrize("strides, odd, state, kw", [((18, 18, 20), 0, "run", dict(far=170)), # rejected round 1's set: one loop's far leg shaded like the near one- ((16, 16, 18), 0, "run", dict(fam="kick", lift=20)), # rejected round 2's set: one loop a heel kick])def test_the_counter_example_sets_stop_and_align_as_before_once_counted(tmp_path, strides, odd, state, kw):"""A run's half repeats in every one of these loops: the set stops, naming each loop, itsdiff --git a/tests/video/test_duration_window_oneshot.py b/tests/video/test_duration_window_oneshot.pyindex 641ef3b..3ae51fb 100644--- a/tests/video/test_duration_window_oneshot.py+++ b/tests/video/test_duration_window_oneshot.py@@ -60,6 +60,7 @@ def test_gait_windows_are_in_seconds_capped_at_half_the_clip() -> None:# non-gait states are untouched: idle wants nearly the whole clip, jump keeps its fractionsassert idle.window(73, 24.0) == (round(73 * 0.60), round(73 * 0.95))assert jump.window(145, 24.0) == (round(145 * 0.11), round(145 * 0.45))+ assert loop_mod.profile_for("unknown-state") is loop_mod.STATE_PROFILES["default"]def test_gait_window_does_not_let_a_single_hop_pass_as_a_walk(tmp_path: Path) -> None:@@ -113,16 +114,6 @@ def test_spec_loader_reads_loop_from_the_strip_sidecar(tmp_path: Path) -> None:assert load_asset(tmp_path / "jump.strip.json").metadata["loop"] is True[email protected](not HAS_IMG2WEBP, reason="img2webp not installed")-def test_one_shot_run_writes_a_non_looping_sidecar(tmp_path: Path) -> None:- _one_shot_frames(tmp_path)- rep = loop_mod.run_loop(tmp_path / "keyed", tmp_path / "jump", fps=24.0, state="jump", min_len=None, max_len=None, n_out=8, seam_max=2.0, name="j", report_path=None)- assert rep["cycle"]["kind"] == "one-shot"- side = json.loads((tmp_path / "jump" / "j.strip.json").read_text())- assert side["kind"] == "one-shot" and side["loop"] is False- assert load_asset(tmp_path / "jump" / "j.strip.json").metadata["loop"] is False--@pytest.mark.skipif(not HAS_IMG2WEBP, reason="img2webp not installed")def test_gif_frame_count_never_exceeds_the_strip_cells(tmp_path: Path) -> None:"""A cycle longer than the cell cap is subsampled into the strip; the GIF/WebP are cutdiff --git a/tests/video/test_edge_speck_lead_in.py b/tests/video/test_edge_speck_lead_in.pyindex 38162a8..1281e5c 100644--- a/tests/video/test_edge_speck_lead_in.py+++ b/tests/video/test_edge_speck_lead_in.py@@ -281,14 +281,7 @@ def test_a_cut_after_a_lead_in_reads_the_standing_height_on_its_own_first_frame(("cut-first-frame", 12, meta["body_src_h"], meta["scale"])-def test_a_cut_of_a_clip_with_no_lead_in_reads_its_first_frame_as_before(tmp_path):- out, meta, keyed = _fixed(tmp_path, [walks.walker(k) for k in range(73)], 12)- assert meta["body_ref"] == "first-frame" and "body_ref_frame" not in meta- assert meta["body_src_h"] == _height(keyed / "000.png")- assert out["lead_in"]["frames"] == 0 and out["cut_size"]["change"] == 0--[email protected]("start, first, change", [(0.93, 112, 0.063), (1.07, 129, -0.068)])[email protected]("start, first, change", [(0.93, 112, 0.063)]) # the other sign: size_change, belowdef test_a_cut_filmed_at_another_size_than_the_first_frame_reads_the_standing_height_on_its_own_first_frame(tmp_path, start, first, change):# Reframed by 7 % over its first 9 frames, the walker opens no lead-in (under LEAD_IN_MIN), and its walk is# filmed 7 % larger (or smaller) than its first frame: read there, the standing height delivered the walk@@ -377,7 +370,7 @@ def test_a_walk_or_run_forced_wide_gets_no_room_above():assert math.isclose(canvas.GAIT_WIDE.ratio, 16 / 9)[email protected]("state", ["walk", "run"])[email protected]("state", ["walk"]) # run takes the same profile (`canvas.profile_for`, above)def test_video_canvas_wide_for_a_gait_from_the_command_line(tmp_path, state):still = tmp_path / "still.png"image = Image.new("RGB", (512, 512), (0, 255, 0))diff --git a/tests/video/test_effect.py b/tests/video/test_effect.pyindex 49ff4b7..2b53c63 100644--- a/tests/video/test_effect.py+++ b/tests/video/test_effect.py@@ -126,8 +126,7 @@ def test_lifetime_cut_keeps_dim_edge_spark_and_terminal_sample(tmp_path):assert preview.convert("RGBA").getchannel("A").getbbox() is None[email protected]("extension", ["gif", "webp"])-def test_lifetime_preview_composites_over_white_without_an_unreported_matte(tmp_path, extension):+def test_lifetime_preview_composites_over_white_without_an_unreported_matte(tmp_path):report = cut(lifetime_frames(tmp_path), tmp_path / "out")meta = report["strip"]strip = Image.open(meta["path"]).convert("RGBA")@@ -138,28 +137,30 @@ def test_lifetime_preview_composites_over_white_without_an_unreported_matte(tmp_cells.append(cell)white = Image.new("RGBA", cells[0].size, "white")black = Image.new("RGBA", cells[0].size, "black")- background = report[extension].get("background")- with Image.open(tmp_path / "out" / f"effect.{extension}") as preview:- assert preview.n_frames == len(cells)- opacity = []- for k, cell in enumerate(cells):- preview.seek(k)- decoded = preview.convert("RGBA")- expected = Image.alpha_composite(black if background == "#000000" else white, cell)- actual = Image.alpha_composite(white, decoded)- # Ordinary alpha compositing catches black matte pixels on white;- # additive compositing on white would make this comparison vacuous.- delta = np.array(expected, dtype=int) - np.array(actual, dtype=int)- assert np.abs(delta).max() <= 2, f"{extension} frame {k} has an unreported matte"- opacity.append(decoded.getchannel("A").getextrema())- if extension == "gif":- assert all(extrema == (255, 255) for extrema in opacity)- assert background == "#000000"- assert report[extension]["opaque"] is True- assert decoded.getextrema() == ((0, 0), (0, 0), (0, 0), (255, 255))- else:- assert background is None- assert decoded.getchannel("A").getbbox() is None+ # One cut, both previews: the GIF and the WebP are written from the same cells.+ for extension in ("gif", "webp"):+ background = report[extension].get("background")+ with Image.open(tmp_path / "out" / f"effect.{extension}") as preview:+ assert preview.n_frames == len(cells), extension+ opacity = []+ for k, cell in enumerate(cells):+ preview.seek(k)+ decoded = preview.convert("RGBA")+ expected = Image.alpha_composite(black if background == "#000000" else white, cell)+ actual = Image.alpha_composite(white, decoded)+ # Ordinary alpha compositing catches black matte pixels on white;+ # additive compositing on white would make this comparison vacuous.+ delta = np.array(expected, dtype=int) - np.array(actual, dtype=int)+ assert np.abs(delta).max() <= 2, f"{extension} frame {k} has an unreported matte"+ opacity.append(decoded.getchannel("A").getextrema())+ if extension == "gif":+ assert all(extrema == (255, 255) for extrema in opacity)+ assert background == "#000000"+ assert report[extension]["opaque"] is True+ assert decoded.getextrema() == ((0, 0), (0, 0), (0, 0), (255, 255))+ else:+ assert background is None+ assert decoded.getchannel("A").getbbox() is Nonedef test_animation_background_is_explicit_and_requires_full_opacity(tmp_path):diff --git a/tests/video/test_explicit_window.py b/tests/video/test_explicit_window.pyindex d20aaf6..cc8b2f4 100644--- a/tests/video/test_explicit_window.py+++ b/tests/video/test_explicit_window.py@@ -59,15 +59,11 @@ ROWS = [lambda r: r["cycle"]["seam_pop"]["held_edge"]["two_step"]["lengths"] == [47, 47]and r["cycle"]["seam_pop"]["held_edge"]["two_step_capped"] == {"max_len": 47, "lengths_over": [48, 49]}, True),("two-step", _held, ("--state", "walk", *MOTION, "--min-len", "20"), lambda r: r["cycle"]["seam_pop"]["applied"], True),- ("counted", _slow, ("--state", "walk", *MOTION, "--max-len", "25", "--steps", "1"),- lambda r: r["cycle"]["steps"]["refused"] == "outside --max-len 25", False),("counted", _short, ("--state", "walk", *MOTION, "--max-len", "42", "--steps", "1"),lambda r: r["cycle"]["steps"]["window"] == [41, 42] and r["cycle"]["steps"]["counted_window"] == [41, 43], True),("counted", _slow, ("--state", "walk", *MOTION, "--min-len", "18", "--steps", "1"), lambda r: r["cycle"]["steps"]["by"] == "given", True),("fallback", _slow_front, ("--state", "walk", *MOTION, "--max-len", "36"), lambda r: r["gait_fallback"]["window"] == [12, 36], False),("fallback", _slow_front, ("--state", "walk", *MOTION, "--min-len", "30"), lambda r: r["gait_fallback"]["window"][0] == 30, True),- ("one-shot", _hop, ("--state", "jump", "--min-len", "8", "--max-len", "14"), # the hop is 16 frames: no one-shot that short- lambda r: r["periodic_attempt"] is not None and r["cycle"]["kind"] == "one-shot", False),("one-shot", _hop, ("--state", "jump", "--max-len", "30"), lambda r: r["periodic_attempt"] is not None and r["cycle"]["kind"] == "one-shot", True),("one-shot", _hop, ("--state", "jump", "--min-len", "30"), lambda r: r["periodic_attempt"] is not None and r["cycle"]["kind"] == "one-shot", True),("fixed", _hop, ("--state", "jump", "--cycle", "fixed", "--start", "50", "--length", "40", "--max-len", "30"),@@ -108,12 +104,15 @@ def test_a_count_the_window_leaves_no_room_for_fails_and_says_both(tmp_path):report = json.loads((tmp_path / "out" / "loop.loop.report.json").read_text())assert report["status"] == "failed" and report["error"] in saidassert report["cycle"]["steps"]["counted_window"] == [41, 43] and report["cycle"]["steps"]["window"] is None+ assert report["cycle"]["steps"]["refused"] == "outside --max-len 25"def test_a_one_shot_the_window_leaves_no_room_for_says_the_window(tmp_path):- keyed = _hop(tmp_path / "clip")+ keyed = _hop(tmp_path / "clip") # the hop is 16 frames: no one-shot that shortwith pytest.raises(SystemExit, match=r"no complete one-shot return .* — in 8-14 frames, inside --min-len 8 --max-len 14"):loop.main(["--frames-dir", str(keyed), "--out-dir", str(tmp_path / "out"), "--state", "jump", "--min-len", "8", "--max-len", "14"])+ report = json.loads((tmp_path / "out" / "loop.loop.report.json").read_text())+ assert report["status"] == "failed" and report["periodic_attempt"] is not None and report["cycle"]["kind"] == "one-shot"def test_the_cut_window_is_worked_out_once():diff --git a/tests/video/test_follow.py b/tests/video/test_follow.pyindex 6e57cd5..c05eac9 100644--- a/tests/video/test_follow.py+++ b/tests/video/test_follow.py@@ -2,6 +2,7 @@import jsonimport mathimport re+import shutilimport numpy as npimport pytest@@ -24,17 +25,27 @@ def walker(k, period=24):return im-def loop_dir(tmp_path):- keyed = tmp_path/'keyed'[email protected](scope='module')+def walk_cut(tmp_path_factory):+ """The walk the loop cases start from, keyed and cut once for the module: `keyed/`, `loop/` and `loop.json`."""+ root = tmp_path_factory.mktemp('walk-cut')+ keyed = root/'keyed'keyed.mkdir()for k in range(73):walker(k).save(keyed/f'{k:03}.png')- out = tmp_path/'loop'+ out = root/'loop'code = loop.main(['--frames-dir', str(keyed), '--out-dir', str(out), '--state', 'walk', '--anchor', 'motion-auto',- '--repair', 'off', '--report', str(tmp_path/'loop.json'), '--name', 'walk'])+ '--repair', 'off', '--report', str(root/'loop.json'), '--name', 'walk'])assert code == 0- return out+ return root+++def loop_dir(walk_cut, tmp_path):+ """A copy of the cut for this case alone, laid out in its tmp_path as cut (`keyed/` beside it), so nothing a case+ writes reaches another."""+ shutil.copytree(walk_cut, tmp_path, dirs_exist_ok=True)+ return tmp_path/'loop'def cells(path, meta):@@ -229,12 +240,6 @@ def test_a_new_cut_removes_the_old_follow_source(loop_dir, tmp_path):assert 'follow' not in json.loads((loop_dir/'walk.strip.json').read_text())-def test_a_move_that_would_fold_the_region_is_refused(loop_dir):- cx, cy, _, _ = chest_region(loop_dir)- with pytest.raises(SystemExit, match='folds a region'):- follow.follow_loop(loop_dir, [(cx, cy, 2, 2)], gain=50)--def test_the_default_refusal_reads_as_it_did(loop_dir):cx, cy, _, _ = chest_region(loop_dir)as_cut = (loop_dir/'walk.strip.png').read_bytes()@@ -493,8 +498,7 @@ def test_numpy_numbers_write_what_the_command_line_writes(loop_dir):assert outputs(loop_dir) == written and json.dumps(result) == json.dumps(given)[email protected]('failure', ['record', 'animation'])[email protected]('followed', [False, True])[email protected]('failure, followed', [('record', False), ('animation', True)])def test_a_run_that_fails_leaves_the_loop_as_it_was(loop_dir, monkeypatch, failure, followed):# The strip and its animations were written over the loop's before the record was: a record that did not# serialise, or an animation that failed its check, left them moved beside a record that does not say so.diff --git a/tests/video/test_follow_read_on.py b/tests/video/test_follow_read_on.pyindex 26188b2..7b8aa56 100644--- a/tests/video/test_follow_read_on.py+++ b/tests/video/test_follow_read_on.py@@ -93,15 +93,24 @@ class Blend:return Image.blend(a, b, t)[email protected](scope='module')+def origin_once(tmp_path_factory):+ """The cut and its follow-through, made once for the module: `cut/` and `followed/`, and the cut strip's sha256."""+ root = tmp_path_factory.mktemp('origin')+ o = cut(root/'cut', [runner(k) for k in range(N)])+ read_on = sha(o/'run.strip.png')+ follow.follow_loop(copy(o, root/'followed'), [chest(o)], on_fold='lower')+ return root, read_on++@pytest.fixture-def origin(tmp_path):+def origin(origin_once, tmp_path):"""The cut every case starts from, followed as cut (the reference), and its strip's sha256 — what an app keeps- as `read_on` beside the regions it read on the first cell."""- o = cut(tmp_path/'cut', [runner(k) for k in range(N)])- read_on = sha(o/'run.strip.png')- followed = copy(o, tmp_path/'followed')- follow.follow_loop(followed, [chest(o)], on_fold='lower')- return o, read_on, followed+ as `read_on` beside the regions it read on the first cell. A copy in this case's tmp_path, so nothing a case+ writes reaches another."""+ root, read_on = origin_once+ shutil.copytree(root, tmp_path, dirs_exist_ok=True)+ return tmp_path/'cut', read_on, tmp_path/'followed'def aligned(o, path, **kw):@@ -116,7 +125,9 @@ def aligned(o, path, **kw):def test_the_first_alignment_records_the_cut_it_was_made_from_and_later_ones_keep_it(origin, tmp_path):o, read_on, _ = originas_cut = meta_of(o)- loop_dir = aligned(o, tmp_path/'turned')+ loop_dir = copy(o, tmp_path/'turned')+ report = align.align_set([loop_dir], between='nearest', multi_cycle='warn')+ assert 'origin' not in report['loops'][0] # the report names each cell's source; the cut's record stays in the metarecord = meta_of(loop_dir)['cycle_align']source = record['origin']assert source['strip_sha256'] == read_on@@ -201,18 +212,6 @@ def test_t1_the_same_turned_loop_followed_as_read_today_moves_another_place(origassert sum(not np.array_equal(moved[k], reference[(k+turned) % N]) for k in range(N)) >= N//2-def test_t1_the_inspection_carries_every_cell_by_the_cuts_reading(origin, tmp_path):- o, read_on, _ = origin- loop_dir = aligned(o, tmp_path/'turned')- turned = meta_of(loop_dir)['cycle_align']['turned_by']- reading = meta_of(loop_dir)['cycle_align']['origin']['reading']['carry_px']- record = follow_inspect.inspect_loop(loop_dir, [chest(o)], tmp_path/'out', on_fold='lower', read_on=read_on)- assert [c['carry_px'] for c in record['cells']] == [reading[(k+turned) % N] for k in range(N)]- assert record['inputs']['settings']['read_on'] == read_on- as_cut = follow_inspect.inspect_loop(o, [chest(o)], tmp_path/'cut-out', on_fold='lower')- assert [c['carry_px'] for c in as_cut['cells']] == reading--# ---------------------------------------------------------------- T2: a stretch by the nearer cell repeats cellsdef test_t2_a_loop_stretched_by_the_nearer_cell_is_carried_cell_for_cell_duplicates_and_all(origin, tmp_path):@@ -266,7 +265,7 @@ def test_t4_another_clip_or_an_unknown_read_on_is_refused_no_match(origin, tmp_pfollow.follow_loop(copy(o, tmp_path/'plain'), [chest(o)], on_fold='lower', read_on=sha(turned/'run.strip.png'))[email protected]('given', ['AB'*32, 'ab'*31+'a', 'zz'*32, ''])[email protected]('given', ['ab'*31+'a'])def test_a_read_on_that_is_no_sha256_is_refused_before_anything_is_read(origin, tmp_path, given):o, _, _ = originwith pytest.raises(SystemExit, match='--read-on'):@@ -288,27 +287,8 @@ def test_t5_a_loop_whose_cells_were_cropped_again_is_refused_uncertain(tmp_path)assert files(loop_dir) == before-def test_t5_a_cell_drawn_again_after_the_alignment_is_refused_uncertain(origin, tmp_path):- o, read_on, _ = origin- loop_dir = aligned(o, tmp_path/'touched')- strip = Image.open(loop_dir/'run.strip.png').convert('RGBA')- ImageDraw.Draw(strip).point((meta_of(loop_dir)['w']*4+3, 3), fill=MARK) # cell 4 is no longer the cut's cell- strip.save(loop_dir/'run.strip.png')- with pytest.raises(SystemExit, match='uncertain.*cell 4'):- follow.follow_loop(loop_dir, [chest(o)], on_fold='lower', read_on=read_on)--# ---------------------------------------------------------------- T6: nothing asked, nothing changes-LEGACY_KEYS = {'regions', 'gain', 'freq_hz', 'zeta', 'harmonics', 'source', 'body_px', 'body_worn_px', 'body_bob_px', 'dx_px', 'dy_px',- 'reach_px', 'gain_requested', 'on_fold', 'fold', 'gif', 'webp'}---def test_t6_without_read_on_the_record_holds_nothing_new(origin):- _, _, followed = origin- assert set(meta_of(followed)['follow']) == LEGACY_KEYS--def test_t6_read_on_the_strip_as_cut_moves_exactly_what_it_moves_without(origin, tmp_path):o, read_on, followed = originloop_dir = copy(o, tmp_path/'same')@@ -323,15 +303,6 @@ def test_t6_read_on_the_strip_as_cut_moves_exactly_what_it_moves_without(origin,assert meta_of(loop_dir)['follow']['read_on']['relation'] == 'same'-def test_t6_an_alignment_adds_two_keys_and_no_pixel(origin, tmp_path):- o, _, _ = origin- loop_dir = aligned(o, tmp_path/'turned')- record = meta_of(loop_dir)['cycle_align']- assert {'origin', 'cells_from'} <= set(record)- report = align.align_set([copy(o, tmp_path/'again')], between='nearest', multi_cycle='warn')- assert 'origin' not in report['loops'][0] # the report names each cell's source; the cut's record stays in the meta--# ---------------------------------------------------------------- T7: the floor decides on the cut's numbersdef test_t7_a_floor_on_a_turned_loop_decides_as_on_the_cut(origin, tmp_path):diff --git a/tests/video/test_follow_stretch_floor.py b/tests/video/test_follow_stretch_floor.pyindex 7a5393b..d2fc097 100644--- a/tests/video/test_follow_stretch_floor.py+++ b/tests/video/test_follow_stretch_floor.py@@ -13,7 +13,7 @@ from sprite_gen.video import follow, follow_inspectW, H, N, DELAY = 160, 300, 13, 41.67SKIN, TORSO, LEG, PATCH, LINE = (200, 150, 120, 255), (90, 120, 180, 255), (190, 170, 120, 255), (120, 160, 220, 255), (10, 10, 20, 255)CX, CY = 80, 112-FLOORS = (0.03, 0.1, 0.2, 0.35)+FLOORS = (0.03, 0.2)def figure(dx, dy, *, lines):@@ -112,14 +112,6 @@ def test_f1_under_refuse_a_move_under_the_floor_is_refused(probes, tmp_path):# ---------------------------------------------------------------- F2: never above the fold rule's gain-def test_f2_where_the_fold_rule_is_stricter_its_gain_stands(probes, tmp_path):- _, region = X2- _, legacy = followed(probes['X2'], tmp_path/'legacy', [region])- _, rec = followed(probes['X2'], tmp_path/'floor', [region], stretch_floor=0.2)- entry = rec['stretch']['regions'][0]- assert entry['floor_gain'] > entry['rule_gain'] == legacy['gain'] == rec['gain']--def test_f2_where_the_floor_is_stricter_its_gain_stands(probes, tmp_path):_, region = X1_, legacy = followed(probes['X1'], tmp_path/'legacy', [region])diff --git a/tests/video/test_gait_fallback.py b/tests/video/test_gait_fallback.pyindex a8cfcba..777c83c 100644--- a/tests/video/test_gait_fallback.py+++ b/tests/video/test_gait_fallback.py@@ -145,6 +145,10 @@ def test_a_clip_the_first_search_cuts_is_cut_without_the_fallback(tmp_path):assert report['cycle']['length'] == 24assert 'gait_fallback' not in reportassert not (output/loop.FALLBACK_FRAMES_DIR).exists()+ # A clip that keeps its size is not held.+ assert report['size_hold']['applied'] is False+ assert abs(report['size_hold']['drift']) < gait_fallback.SIZE_HOLD_MIN+ assert 'padding_ltrb' not in report['size_hold']def test_a_cycle_longer_than_half_the_clip_is_found_by_the_fallback(tmp_path):@@ -159,12 +163,6 @@ def test_a_cycle_longer_than_half_the_clip_is_found_by_the_fallback(tmp_path):assert not (output/loop.FALLBACK_FRAMES_DIR).exists()-def test_an_explicit_max_len_stays_the_ceiling(tmp_path):- code, report, _ = run(tmp_path, [walker(k, period=40) for k in range(73)], '--max-len', '36')- assert str(code).startswith('video-loop: no periodic cycle found')- assert report['gait_fallback']['window'] == [12, 36]--def test_a_walk_toward_the_camera_is_held_at_its_size_before_the_first_search(tmp_path):frames = [walker(k, grow=0.2) for k in range(73)]code, report, output = run(tmp_path, frames)@@ -195,14 +193,6 @@ def test_a_small_change_of_size_is_held_too(tmp_path):assert fallback['scale_undone'] is False and fallback['scale_drift']['drift'] < gait_fallback.SCALE_DRIFT_MIN-def test_a_clip_that_keeps_its_size_is_not_held(tmp_path):- code, report, output = run(tmp_path, [walker(k) for k in range(73)])- assert code == 0- assert report['size_hold']['applied'] is False- assert abs(report['size_hold']['drift']) < gait_fallback.SIZE_HOLD_MIN- assert 'padding_ltrb' not in report['size_hold']--def test_the_size_is_read_one_cycle_on():grows = gait_fallback.cycle_drift([walker(k, grow=0.025) for k in range(73)], min_lag=12, max_lag=36)# The pose matches itself one cycle on; each height is compared with the frames one, two anddiff --git a/tests/video/test_gait_fallback_resample.py b/tests/video/test_gait_fallback_resample.pyindex 20458e8..f48d2d8 100644--- a/tests/video/test_gait_fallback_resample.py+++ b/tests/video/test_gait_fallback_resample.py@@ -30,7 +30,7 @@ def scaled_back(scale: float) -> tuple[Image.Image, Image.Image, tuple[float, ..return src, second, inverse[email protected]("scale", (0.84, 0.95, 1.05, 1.19))[email protected]("scale", (0.84,))def test_a_scaled_back_frame_carries_no_colour_it_did_not_have(scale: float) -> None:src, out, inverse = scaled_back(scale)assert colour_outside_mapped(src, out, inverse) == 0diff --git a/tests/video/test_gait_guard_anchor_wide.py b/tests/video/test_gait_guard_anchor_wide.pyindex 78464cf..9b5e5ae 100644--- a/tests/video/test_gait_guard_anchor_wide.py+++ b/tests/video/test_gait_guard_anchor_wide.py@@ -300,12 +300,3 @@ def test_feet_anchor_does_not_sway_a_body_that_stands_still(tmp_path: Path) -> Nassert max(body) - min(body) <= 1.5assert meta["drift_px"] <= 2 # nothing moved, nothing was removedassert meta["foot_sway_px"] >= 10 # the planted foot does change — reported, not erased---def test_feet_anchor_removes_drift_but_keeps_the_step(tmp_path: Path) -> None:- files = _lifting_walker(tmp_path, period=12, n=24, drift_per_frame=1.5)- frames = [Image.open(f).convert("RGBA") for f in files]- anchored, meta = loop_mod.build_strip(frames, cycle_seconds=1.0, anchor="feet")- body = _cell_body_centres(anchored, meta)- assert max(body) - min(body) <= 1.5- assert 30 <= meta["drift_px"] <= 40 # 23 frames * 1.5 px of authored driftdiff --git a/tests/video/test_gait_harmonic_ambiguity.py b/tests/video/test_gait_harmonic_ambiguity.pyindex 010ed7f..4290b90 100644--- a/tests/video/test_gait_harmonic_ambiguity.py+++ b/tests/video/test_gait_harmonic_ambiguity.py@@ -29,7 +29,7 @@ def test_noisy_harmonic_above_duration_floor_retains_both_occurrences():assert gait['review_recommended'] is True[email protected]('noise', [0, 0.0001])[email protected]('noise', [0.0001])def test_exact_or_near_exact_fast_repeat_is_not_doubled(noise):cycle = loop.detect_cycle(_repeat_distances(noise=noise), min_len=7, max_len=29, gait_floor=8)assert cycle['period_global'] == 13diff --git a/tests/video/test_ghost_given_way.py b/tests/video/test_ghost_given_way.pyindex e17b560..14e6065 100644--- a/tests/video/test_ghost_given_way.py+++ b/tests/video/test_ghost_given_way.py@@ -207,16 +207,6 @@ def test_without_rife_a_filmed_ghost_gives_way_to_the_clean_frame_after_it(tmp_passert "jump frame was not repaired" not in err-def test_a_cell_shown_twice_in_a_row_passes_the_gif_and_webp_check(tmp_path):- """B3: two identical frames in a row — what giving a ghost way to the frame beside it leaves — are one frame- of the GIF and of the WebP. The check counted a frame per cell and refused the loop ("19 frames, expected 20")."""- keyed = _keyed(tmp_path, "E", ())- (keyed / "0010.png").write_bytes((keyed / "0011.png").read_bytes())- report = _cut(keyed, tmp_path / "E", repair="off")- assert report["n_out"] == L and report["gif"]["n_frames"] == report["webp"]["n_frames"] == L - 1- assert loop_mod.shown_runs(_cells(tmp_path / "E")) == L - 1--def test_a_ghost_with_no_clean_frame_beside_it_is_kept_and_named(tmp_path, capsys):"""Frames 9, 10, 11 are filmed ghosts: 9 gives way to 8, 11 to 12, and 10, with no clean frame beside it, iskept — `ghost_kept`, and a line to film the direction again."""@@ -285,42 +275,6 @@ def _phase(k: int) -> int:return (k + EVEN) % L[email protected]("rife_frame", ["not installed", "a ghost too"])-def test_a_ghost_at_the_cuts_first_frame_given_way_leaves_the_seam_the_cut_closes_with(tmp_path, monkeypatch, rife_frame):- """The default seam gate on a walk whose wrap is an ordinary step, its filmed ghost at the cut's first frame, given- way to frame 1 — no RIFE installed, or RIFE's frame between frames 19 and 1 a ghost too. Frame 1 then shows twice in- a row and the step from the last frame into the loop is two: read on the cells as they play, the wrap measured 2.17- times the mean step and a walk that closes was refused, "the cycle does not close". The gate reads the cell given- way as filmed — on the source frames, the seam `--repair off` reads."""- filmed = _cut(_keyed(tmp_path, "filmed", (0,), phase=EVEN), tmp_path / "filmed", repair="off")- middle = None- if rife_frame == "not installed":- _no_rife(monkeypatch, tmp_path)- else:- middle = _Middle(ghostly=((_phase(L - 1), _phase(1)),))- report = _cut(_keyed(tmp_path, "E", (0,), phase=EVEN), tmp_path / "E", interpolate=middle) # before: refused- out = tmp_path / "E"- assert [(g["frame"], g["taken"]) for g in report["ghost_given_way"]] == [(0, {"source": 1})]- assert _cycle(out, 0).tobytes() == _cycle(out, 1).tobytes()- _delivered_clean(out)- assert report["seam_as_filmed"] == [0] and report["seam_measurement"] == "source-frames"- assert report["resampled_seam_ratio"] == filmed["resampled_seam_ratio"] < loop_mod.SEAM_RATIO_MAX- assert report["gif"]["n_frames"] == report["webp"]["n_frames"] == L - 1---def test_a_ghost_at_the_cuts_last_frame_given_way_to_its_first_leaves_the_seam_the_cut_closes_with(tmp_path, monkeypatch):- """The ghost at the cut's last frame given way to frame 0, the cut's first shown again at the wrap: read on the cells,- the wrap was no step at all (0.0), whatever the cut. Read as filmed, it is the seam the cut closes with."""- filmed = _cut(_keyed(tmp_path, "filmed", (L - 1,), phase=EVEN), tmp_path / "filmed", repair="off")- _no_rife(monkeypatch, tmp_path)- report = _cut(_keyed(tmp_path, "E", (L - 1,), phase=EVEN), tmp_path / "E")- out = tmp_path / "E"- assert report["resampled_seam_ratio"] == filmed["resampled_seam_ratio"] > 1 # before: 0.0- assert [(g["frame"], g["taken"]) for g in report["ghost_given_way"]] == [(L - 1, {"source": 0})]- assert _cycle(out, L - 1).tobytes() == _cycle(out, 0).tobytes()- assert report["seam_as_filmed"] == [L - 1] and report["seam_measurement"] == "source-frames"--def test_ghosts_at_both_ends_of_the_cut_given_way_inward_leave_the_seam_the_cut_closes_with(tmp_path, monkeypatch):"""Filmed ghosts at the cut's first and last frames at once: across the wrap each has the other beside it, so noframe is made between its neighbours — frame 0 gives way to the frame after it, the last frame to the one before@@ -341,7 +295,7 @@ def test_ghosts_at_both_ends_of_the_cut_given_way_inward_leave_the_seam_the_cut_SHORT = 14 # a cut six frames short of the walk's cycle: its wrap is six steps and does not close[email protected]("anchor", ["none", "body"])[email protected]("anchor", ["body"]) # `none` reads the seam on the source frames as `body` doesdef test_a_cut_that_does_not_close_is_refused_though_its_last_frame_gives_way_to_its_first(tmp_path, monkeypatch, anchor):"""A cut 14 frames long of a walk 20 frames a cycle does not close (`--repair off` refuses it); its last frame afilmed ghost given way to its first, the wrap read on the cells was a step of nothing and the cut was delivered,@@ -376,7 +330,7 @@ def test_a_cut_with_a_frame_made_reads_its_cell_given_way_as_filmed_on_the_cells_delivered_clean(tmp_path / "E")[email protected]("ghosts", [(0,), (L - 1,), (0, L - 1)], ids=["first", "last", "both"])[email protected]("ghosts", [(0, L - 1)], ids=["both"]) # the wrap reads any set of cells given way as filmeddef test_anchor_body_reads_a_cell_given_way_as_filmed_in_the_wrap_after_its_ramp(tmp_path, monkeypatch, ghosts):"""`--anchor body`, the walk's default, ramps the cut so its last frame returns to its first and records the wrapas it then plays in the strip metadata (`seam_ratio_after_anchor`: the last frame against the first, over the meandiff --git a/tests/video/test_ghost_screen.py b/tests/video/test_ghost_screen.pyindex 88049ad..5f96d1a 100644--- a/tests/video/test_ghost_screen.py+++ b/tests/video/test_ghost_screen.py@@ -116,19 +116,6 @@ def test_a_time_on_a_filmed_ghost_takes_the_clean_frame_beside_it_and_rife_keepsassert next(m for m in facts["smear"] if m["at"] == 1)["faults"] == ["ghost"] # kept under rife, named-def test_a_ghost_with_no_clean_frame_beside_it_is_kept_and_a_loop_already_that_long_is_screened():- frames = _stride(8)- for k in (2, 3, 4):- frames[k] = _band(frames[k])- out, facts = align.resample(frames, 8, None) # already that long: every cell a source frame, screened- assert [frames.index(f) for f in out] == [0, 1, 1, 3, 5, 5, 6, 7]- assert [(g["at"], g["source"], g["taken"]) for g in facts["ghost_at"]] == [(2, 2, 1), (3, 3, 3), (4, 4, 5)]- assert facts["made_by_rife"] == 0- plain = _stride(8)- same, facts = align.resample(plain, 8, None)- assert all(a is b for a, b in zip(same, plain)) and facts["ghost_at"] == []--def test_a_loop_drawn_part_covered_is_resampled_as_before():cape = [_band(f) for f in _stride(4)]out, facts = align.resample(cape, 8, _follow)@@ -153,15 +140,6 @@ def _cut(keyed: Path, out: Path, length: int) -> dict:name="walk", report_path=None, cycle_mode="fixed", start=0, length=length, anchor="none", repair="off")-def test_video_loop_records_the_ghost_screen_of_its_cut(tmp_path, capsys):- """A loop delivered as cut — one direction, never aligned — is screened too: its report names the ghost."""- report = _cut(_keyed(tmp_path, "S", 20, (7,)), tmp_path / "S", 20)- screen = report["ghost_screen"]- assert screen["reads"] and [g["frame"] for g in screen["ghosts"]] == [7]- assert rife.ghost(Image.open(tmp_path / "S" / "cycle" / "frame-007.png")) > GHOST_WARN- assert "frame 7 of the cut" in capsys.readouterr().err--def test_alignment_delivers_no_filmed_ghost_and_names_each_cell_it_passed_over(tmp_path):"""Set length 22: S (20) lands on its ghost at a whole time, E (24) makes a frame next to itsghost, which carries it, and the nearer frame is that ghost. Both take the frame after it."""diff --git a/tests/video/test_held_drawings.py b/tests/video/test_held_drawings.pyindex ebda0cc..d9880a6 100644--- a/tests/video/test_held_drawings.py+++ b/tests/video/test_held_drawings.py@@ -115,7 +115,7 @@ def _cut(tmp_path: Path, name: str, cycle: int, hold: int) -> Path:return out[email protected]("hold, per_second", [(1, 24.0), (2, 12.0), (3, 8.0)])[email protected]("hold, per_second", [(3, 8.0)]) # plumbing: the unit grid above reads every holddef test_video_loop_records_the_clips_drawings_a_second(tmp_path, hold, per_second):d = _cut(tmp_path, "S", 24, hold)report = json.loads((d / "walk.loop.report.json").read_text())diff --git a/tests/video/test_idle_still.py b/tests/video/test_idle_still.pyindex 6a33ebd..f9d024d 100644--- a/tests/video/test_idle_still.py+++ b/tests/video/test_idle_still.py@@ -15,29 +15,6 @@ from sprite_gen.video import batch as batch_modfrom sprite_gen.video import loop as loop_mod-def test_the_idle_prompt_holds_the_feet_and_asks_for_the_return_not_a_rhythm() -> None:- prompt = batch_mod.build_prompt("side", "idle", None)- assert "both feet planted flat on the ground" in prompt- assert "no walking, no marching in place" in prompt- assert "weight sway" not in prompt- assert "evenly paced" not in prompt- assert prompt.endswith("The last frame returns to the exact pose of the first frame, so the animation loops seamlessly.")- # the rest of the frame rules are the ordinary ones, not the attack's- assert "anything it holds" not in prompt- assert prompt.replace(batch_mod.MOTION_TEXT["idle"], "{m}") == batch_mod.PINNED_LOOP_TEXT.format(- motion="{m}", view=batch_mod.VIEW_TEXT["side"].format(facing="right"))---def test_idle_is_pinned_and_its_whole_clip_is_the_loop() -> None:- assert "idle" in batch_mod.PIN_LAST_FRAME_STATES- assert batch_mod.PINNED_LOOP_STATES == frozenset({"idle", "attack"})- # an attack's whole clip is its loop too (one strike, stance to stance), with its own template- assert "Crisp, clean frames" in batch_mod.build_prompt("side", "attack", None)- assert "Crisp, clean frames" not in batch_mod.build_prompt("side", "idle", None)- # the other states keep the evenly paced loop- assert "evenly paced" in batch_mod.build_prompt("side", "walk", None)--def _still_frames(tmp_path: Path, *, n: int = 48, breath: int = 1, end_offset: int = 0) -> Path:"""A standing body that breathes by `breath` px; the last frame is the first moved by `end_offset`."""d = tmp_path / "keyed"@@ -61,21 +38,14 @@ def _loop(tmp_path: Path, keyed: Path, name: str = "idle") -> dict:def test_a_pinned_still_clip_is_one_whole_loop(tmp_path: Path) -> None:+ """Breathing moves almost nothing per frame, so the ratio of the wrap to one step can be large+ while the wrap itself is invisible; the pin decides, with a re-render noise floor."""rep = _loop(tmp_path, _still_frames(tmp_path))cycle = rep["cycle"]assert (cycle["kind"], cycle["start"], cycle["length"]) == ("pinned", 0, 47) # every frame but the re-rendered first- assert cycle["pin_error"] <= cycle["pin_tolerance"]- assert rep["strip"]["kind"] == "pinned"---def test_a_near_still_clip_is_not_refused_for_its_seam_ratio(tmp_path: Path) -> None:- """Breathing moves almost nothing per frame, so the ratio of the wrap to one step can be large- while the wrap itself is invisible; the pin decides, with a re-render noise floor."""- frames = _still_frames(tmp_path, breath=1)- D = loop_mod.distance_matrix(sorted(frames.glob("*.png")))- cycle = loop_mod.pinned_cycle(D, seam_max=loop_mod.SEAM_RATIO_MAX)assert cycle["pin_tolerance"] == max(loop_mod.SEAM_RATIO_MAX * cycle["inner_mean_adjacent"], loop_mod.PIN_NOISE_MAX)assert cycle["pin_error"] <= cycle["pin_tolerance"]+ assert rep["strip"]["kind"] == "pinned"def test_a_clip_that_does_not_come_back_to_its_first_frame_is_refused(tmp_path: Path) -> None:diff --git a/tests/video/test_loop_prop_seam_held.py b/tests/video/test_loop_prop_seam_held.pyindex 563fe4e..608d816 100644--- a/tests/video/test_loop_prop_seam_held.py+++ b/tests/video/test_loop_prop_seam_held.py@@ -92,6 +92,24 @@ def held(tmp_path_factory) -> tuple[Path, dict]:return root, _cut(root, _keyed(root))[email protected](scope="module")+def staffless_cut(tmp_path_factory) -> Path:+ """The walker without a staff, cut once for the module (`<root>/out`): two tests align it."""+ root = tmp_path_factory.mktemp("staffless")+ _cut(root, _keyed(root, staff=False))+ return root+++def staffless(staffless_cut, tmp_path) -> tuple[Path, dict]:+ """A copy of that cut for one test, laid out as `_cut` lays it: what an alignment rewrites stays in the+ test's own directory. The report and strip metadata name the shared keyed frames, which nothing writes;+ the alignment finds the report by name in the loop's directory, not by a path recorded in it."""+ root = tmp_path / "staffless"+ shutil.copytree(staffless_cut / "out", root / "out")+ return root, json.loads((root / "out" / "loop.loop.report.json").read_text())++def test_motion_auto_takes_two_steps_where_the_held_staff_closes_only_there(held):root, report = heldcycle = report["cycle"]@@ -159,13 +177,6 @@ def test_an_explicit_max_len_is_not_widened_by_a_window_two_steps_long(tmp_path)assert "over --max-len 25" in line-def test_a_walk_whose_top_does_not_pop_reads_nothing_below_it(tmp_path):- report = _cut(tmp_path, _keyed(tmp_path, staff=False))- shape = report["cycle"]["seam_pop"]- assert shape["applied"] is False and "held_edge" not in shape and "steps" not in report["cycle"]- assert not any(r.get("held_edge") is not None for r in report["cycle"]["candidates"])--# --- the held side, read on edges -------------------------------------------------------------def _edges(series: list[float], rows: int = 30) -> np.ndarray:@@ -338,13 +349,12 @@ def test_shape_rank_reads_no_held_side_when_the_first_choice_does_not_pop():# --- the set -----------------------------------------------------------------------------------def test_cycle_align_aligns_a_two_step_loop_as_the_one_cycle_it_is(held, tmp_path):+def test_cycle_align_aligns_a_two_step_loop_as_the_one_cycle_it_is(held, staffless):"""The loop cut two steps long is one cycle: it returns half way at its second step, which is nosuspect (status `steps`), and it is resampled to the set's length like the rest — the set's lengththe median of the loops as cut, nothing kept twice as long."""root, report = held- other = tmp_path / "plain"- plain = _cut(other, _keyed(other, staff=False))+ other, plain = stafflesslengths = [report["cycle"]["length"], plain["cycle"]["length"]]out = align.align_set([root / "out", other / "out"], between="nearest")two, one = out["loops"]@@ -379,9 +389,8 @@ CORRESPONDENCE_KEYS_2410 = {"cells_from", "origin"}GHOST_KEYS_2430 = {"ghost_screen", "ghost_at"}-def test_cycle_align_writes_a_loop_without_a_held_part_as_before(tmp_path):- src = tmp_path / "src"- report = _cut(src, _keyed(src, staff=False))+def test_cycle_align_writes_a_loop_without_a_held_part_as_before(tmp_path, staffless):+ src, report = stafflesscut = json.loads((src / "out" / "loop.strip.json").read_text())# The cut names its cells' source: the keyed frames it read, its window in them, and each cell's frame# there — every frame of the window one cell, under one crop.diff --git a/tests/video/test_loop_repair.py b/tests/video/test_loop_repair.pyindex 28b7c3f..85175d2 100644--- a/tests/video/test_loop_repair.py+++ b/tests/video/test_loop_repair.py@@ -187,6 +187,13 @@ def test_video_loop_records_the_repair_and_plays_the_made_frame(tmp_path):assert np.array_equal(np.asarray(Image.open(tmp_path / "out" / "cycle" / "frame-009.png")), np.asarray(reopened[9]))assert json.loads((tmp_path / "w.json").read_text())["jump_repair"]["replaced"] == [10]assert made == [0.5]+ # the jolt of the loop as it plays after the repair (docs/loop-repair.md section 3)+ jolt = rep["jolt"]+ assert jolt["measured"] == "after the jump repair" and jolt["warnings"] == [] and jolt["passed"]+ assert jolt["gated"] is False and jolt["gate"] is None+ assert jolt["reference"] == {"jolt_max": repair.JOLT_REFERENCE, "head_step_max": repair.HEAD_STEP_REFERENCE}+ assert set(jolt["head"]["x"]) >= {"step_max_pct", "step_median_pct", "max_over_median", "range_pct"}+ assert set(jolt["head"]["y"]) >= {"step_max_pct", "step_median_pct", "max_over_median", "range_pct"}def _no_rife(monkeypatch, tmp_path: Path) -> None:@@ -234,12 +241,6 @@ def test_repair_on_without_rife_is_refused_with_the_install_line(tmp_path, monkeassert report["status"] == "failed" and "rife-ncnn-vulkan not found" in report["error"]-def test_repair_on_with_rife_repairs_as_auto_does(tmp_path):- filmed, truth = _loop({10: 12})- rep = _run(tmp_path, _keyed(tmp_path, filmed), repair="on", interpolate=lambda a, b, t: truth[10])- assert rep["jump_repair"]["replaced"] == [10] and rep["jump_repair"]["applied"] is True--def test_a_rife_that_is_found_and_fails_still_fails_the_loop(tmp_path):from sprite_gen.video import rife@@ -305,17 +306,6 @@ def test_a_loop_with_no_head_to_track_says_so_instead_of_passing():assert any("could not be tracked" in o for o in repair.jolt_verdict(measured))-def test_video_loop_reports_the_jolt_of_the_loop_as_it_plays_after_the_repair(tmp_path):- filmed, truth = _loop({10: 12})- rep = _run(tmp_path, _keyed(tmp_path, filmed), interpolate=lambda a, b, t: truth[10])- jolt = rep["jolt"]- assert jolt["measured"] == "after the jump repair" and jolt["warnings"] == [] and jolt["passed"]- assert jolt["gated"] is False and jolt["gate"] is None- assert jolt["reference"] == {"jolt_max": repair.JOLT_REFERENCE, "head_step_max": repair.HEAD_STEP_REFERENCE}- assert set(jolt["head"]["x"]) >= {"step_max_pct", "step_median_pct", "max_over_median", "range_pct"}- assert set(jolt["head"]["y"]) >= {"step_max_pct", "step_median_pct", "max_over_median", "range_pct"}--def test_by_default_a_jolting_loop_is_kept_with_a_warning_line(tmp_path, capsys):filmed, _ = _loop()popped = _head_pop(filmed, 7, 4)diff --git a/tests/video/test_one_step_cut.py b/tests/video/test_one_step_cut.pyindex 7d4367c..821fe2c 100644--- a/tests/video/test_one_step_cut.py+++ b/tests/video/test_one_step_cut.py@@ -121,12 +121,11 @@ def _same_but_the_screen(a: Path, b: Path) -> None:assert left == right[email protected]("cycle, suspect", [(CYCLE, True), (23.5, True), (25, False)])[email protected]("cycle, suspect", [(CYCLE, True)])def test_the_step_screen_changes_nothing_but_its_own_record(tmp_path, monkeypatch, cycle, suspect):- """A one-step cut, a cycle on a frame count that is not whole (23.5 frames: twice it repeats- better, being whole there — a suspect that is no step) and a whole cycle of 25: with the screen- or without it, every image, the strip metadata and the report are the same but for its record, and- the gait observation's copy of it."""+ """A one-step cut: with the screen or without it, every image, the strip metadata and the report+ are the same but for its record, and the gait observation's copy of it. The screen is computed+ after the cut is chosen and only stored (`local_cycle.py`), so one cut answers for any cycle."""keyed = _keyed(tmp_path, cycle)report = _cut(tmp_path / "screened", keyed)assert report["cycle"]["step_screen"]["suspect"] is suspect@@ -135,6 +134,13 @@ def test_the_step_screen_changes_nothing_but_its_own_record(tmp_path, monkeypatc_same_but_the_screen(tmp_path / "screened", tmp_path / "unscreened")[email protected]("cycle, suspect", [(23.5, True), (25, False)])+def test_the_step_screen_reads_a_cycle_on_a_frame_count_that_is_not_whole(tmp_path, cycle, suspect):+ """A cycle of 23.5 frames repeats better twice over, being whole there: a suspect that is no step.+ A whole cycle of 25 is no suspect."""+ assert _cut(tmp_path / "out", _keyed(tmp_path, cycle))["cycle"]["step_screen"]["suspect"] is suspect++def test_steps_1_cuts_the_walk_again_two_steps_long_where_its_arms_close(slow, tmp_path):root, keyed, first = slowreport = _cut(tmp_path / "out", keyed, "--steps", "1")diff --git a/tests/video/test_rife.py b/tests/video/test_rife.pyindex 9ca38e0..a34fb5e 100644--- a/tests/video/test_rife.py+++ b/tests/video/test_rife.py@@ -230,19 +230,3 @@ def test_real_rife_melts_legs_crossing_too_far_and_alignment_takes_the_nearer_frout, facts = align.resample(list(near), 4, interpolate)assert facts["made_at"] == [1, 3] and facts["nearest_at"] == [] and all(not m["faults"] for m in facts["smear"])-[email protected]_rife-def test_real_rife_repair_rejects_outline_loss_and_keeps_the_original_middle(monkeypatch):- from sprite_gen.video import repair-- frames = [_walker(20, -20), _walker(8, -8), _walker(-5, 5), _walker(10, -10)]- before = [f.tobytes() for f in frames]- # Isolate adoption from candidate detection: this target spans the wide crossing- # above, where the actual external RIFE loses an outline the original middle has.- scores = np.array([3., 2., 1., 1.])- monkeypatch.setattr(repair, "jump_scores", lambda *a, **kw: {k: scores for k in ("whole", "hair", "score")})- interpolate = rife.Rife()- out, facts = repair.repair_jumps(frames, interpolate)- assert interpolate.made == facts["attempts"] == 1- assert facts["replaced"] == [] and facts["rounds"][0]["faults"][0] == "outline"- assert [f.tobytes() for f in out] == before == [f.tobytes() for f in frames]diff --git a/tests/video/test_set_sheet.py b/tests/video/test_set_sheet.pyindex 0a4d22a..5063db4 100644--- a/tests/video/test_set_sheet.py+++ b/tests/video/test_set_sheet.py@@ -188,33 +188,6 @@ def test_a_declared_pivot_is_the_one_laid_on_the_cell_centre(tmp_path):assert cb[0] - sb[0] == meta["cell_w"] // 2 - 20 # strip x 20 on the cell centre-def test_same_geometry_as_a_sheet_laid_by_hand(tmp_path):- """A hand-laid sheet: every strip centred in one wide cell and stood on its bottom, the common ground- line the lowest body pixel of any cell. The engine's cells are that layout cropped to the bodies, one- offset for every cell; its ground line is the hand one, moved by that offset."""- sizes = {"S": (61, 100), "SW": (64, 100), "W": (66, 100), "NW": (63, 100), "N": (60, 100), "NE": (67, 100),- "E": (72, 100), "SE": (65, 100)}- dirs = [_direction(tmp_path, c, size=sizes[c], height=70 + i * 3, half=10 + i) for i, c in enumerate(set_sheet.ORDER)]- meta, sheet = _make(tmp_path, dirs, [VIEWS[c] for c in set_sheet.ORDER])- cw_hand, ch_hand = 120, 110- hand = {}- for r, c in enumerate(set_sheet.ORDER):- for k, src in enumerate(_strip_cells(tmp_path / c)):- cell = Image.new("RGBA", (cw_hand, ch_hand), (0, 0, 0, 0))- cell.paste(src, ((cw_hand - src.width) // 2, ch_hand - src.height))- hand[(r, k)] = cell- foot = max(_box(c)[3] for c in hand.values())- offsets = set()- for key, cell in _cells(sheet, meta).items():- hb, cb = _box(hand[key]), _box(cell)- dx, dy = hb[0] - cb[0], hb[1] - cb[1]- offsets.add((dx, dy))- assert cell.tobytes() == hand[key].crop((dx, dy, dx + meta["cell_w"], dy + meta["cell_h"])).tobytes()- assert len(offsets) == 1- (dx, dy), = offsets- assert meta["baseline_y"] == foot - dy--def test_lengths_that_differ_are_laid_all_the_same_and_said_to_differ(tmp_path, capsys):s = _direction(tmp_path, "S", n=12)e = _direction(tmp_path, "E", n=10)diff --git a/tests/video/test_source_restoration.py b/tests/video/test_source_restoration.pyindex 6f87756..5e9be2d 100644--- a/tests/video/test_source_restoration.py+++ b/tests/video/test_source_restoration.py@@ -213,7 +213,7 @@ def test_normal_source_is_noop(case,tmp_path):assert all(outputs(result)[k].read_bytes()==paths[k].read_bytes() for k in paths)[email protected]('field',['clip','canvas','frames_report','frame','manifest','pts'])[email protected]('field',['clip','frames_report','frame','manifest','pts'])def test_changed_or_forged_source_receipt_is_error(case,field):_,inputs,_=caseif field=='manifest':@@ -238,7 +238,7 @@ def test_missing_source_is_error_and_follow_is_shared_unknown(case,tmp_path):with pytest.raises(FileNotFoundError): source.Source.read(**inputs)[email protected]('mutation',['freeze','wrong_time','colour','alpha','duration','crop','report','receipt'])[email protected]('mutation',['freeze','colour','alpha','duration','crop','report','receipt'])def test_tampered_final_artifacts_are_not_accepted(case,tmp_path,mutation):r=repair(case,tmp_path)paths=outputs(r)@@ -253,7 +253,6 @@ def test_tampered_final_artifacts_are_not_accepted(case,tmp_path,mutation):else:fs=cells(paths)if mutation=='freeze': fs=[fs[0]]*len(fs)- elif mutation=='wrong_time': fs[r['target']]=fs[r['target']-1]elif mutation=='colour': ImageDraw.Draw(fs[r['target']]).rectangle((22,25,36,35),fill=(0,255,0))else: fs[r['target']].putpixel((32,32),(255,0,0,0))write_strip(paths,fs)@@ -501,7 +500,6 @@ def test_one_step_the_resample_made_is_capped(key,left,right,mixed,capped):@pytest.mark.parametrize('key,left,right,dark',[('green',(120,115,90,255),(90,115,120,255),None), # two steps- ('green',(240,230,40,255),(40,230,240,255),None), # yellow meets cyan: the mix is a bright green('magenta',(230,60,60,255),(60,60,230,255),None), # red meets blue('green',(240,230,40,255),(40,230,240,255),(5,6))]) # a dark pixel under the mix does not make a deep cap a small onedef test_a_deeper_made_excess_keeps_the_delivered_pixel(key,left,right,dark):@@ -667,26 +665,20 @@ OUTSIDE='differs from the origin outside its restoration receipt'@pytest.mark.parametrize('tamper,refusal',[- ('mask_run',REBUILT),('mask_digest',REBUILT),('output_digest',REBUILT),- ('restored_pixel',PIXELS),('protected_pixel',PIXELS),('normal_pixel',PIXELS),+ ('mask_run',REBUILT),('protected_pixel',PIXELS),('list_emptied','lists no applied cell'),('receipt_removed','carries no restoration receipt'),- ('duplicate',PREFIX),('out_of_range',PREFIX),('first_baseline','another baseline than its prefix'),+ ('duplicate',PREFIX),('first_baseline','another baseline than its prefix'),('extra_field','differs from the one the origin and the source reproduce'),('meta_bytes',OUTSIDE),('report_field',OUTSIDE)])def test_changed_current_baseline_or_receipt_is_error(case,tmp_path,adopted,tamper,refusal):origin,first,current=adoptedentry=lambda report: report['restoration']['applied'][0]if tamper=='mask_run': rewrite_receipt(current,lambda r: entry(r)['copied']['rle'].__setitem__(0,entry(r)['copied']['rle'][0]+1))- elif tamper=='mask_digest': rewrite_receipt(current,lambda r: entry(r)['protected'].update(sha256='0'*64))- elif tamper=='output_digest': rewrite_receipt(current,lambda r: entry(r).update(output_rgba_sha256='0'*64))- elif tamper=='restored_pixel': repaint_cell(current,2,(30,40),(200,150,100,255))# One protected place quietly given the source's pixel: fewer protected pixels than the origin allows.elif tamper=='protected_pixel': repaint_cell(current,2,(25,25),(180,205,120,255))- elif tamper=='normal_pixel': repaint_cell(current,5,(30,40),(200,150,100,255))elif tamper=='list_emptied': rewrite_receipt(current,lambda r: r['restoration'].update(applied=[]))elif tamper=='receipt_removed': rewrite_receipt(current,lambda r: r.pop('restoration'))elif tamper=='duplicate': rewrite_receipt(current,lambda r: r['restoration']['applied'].append(entry(r)))- elif tamper=='out_of_range': rewrite_receipt(current,lambda r: entry(r).update(target=99))elif tamper=='first_baseline': rewrite_receipt(current,lambda r: entry(r)['baseline_artifacts']['strip'].update(sha256='0'*64))elif tamper=='extra_field': rewrite_receipt(current,lambda r: r['restoration'].update(verified=True))elif tamper=='meta_bytes': current['meta'].write_text(current['meta'].read_text()+'\n')@@ -729,11 +721,6 @@ def test_other_policy_receipt_is_not_read_as_this_one(case,tmp_path,adopted):# The released contract before the ghost guard: it could restore a filmed ghost the cut gave way.lambda r: r['restoration'].update(metric_version='source-restoration-v4',policy_version='key-protected-source-copy-one-step-cap-jump-guard-v1'),- # The released contract before the jump guard: its cells were accepted without it.- lambda r: r['restoration'].update(metric_version='source-restoration-v3',- policy_version='key-protected-source-copy-one-step-cap-v1'),- # The same cell under the contract before this one, which never capped: its receipt is not this one's.- lambda r: r['restoration'].update(metric_version='source-restoration-v2',policy_version='key-protected-source-copy-v1'),lambda r: r.update(restoration={'operation':'restore_active_cut','metric_version':'source-restoration-v1','target':2,'restored_cells':[2]})):rewrite_receipt(current,change)@@ -752,10 +739,8 @@ def test_old_proposal_cannot_be_compared_on_the_new_baseline(case,tmp_path,adoptwith pytest.raises(ValueError,match='does not bind'):compare_result(case,second,baseline=case[0],origin=origin)# Evidence of another schema or metric is not this contract's.- for field,value in (('schema_version',2),('schema_version',3),('metric_version','source-restoration-v2'),- ('policy_version','key-protected-source-copy-v1'),('metric_version','source-restoration-v3'),- ('metric_version','source-restoration-v4'),('policy_version','key-protected-source-copy-one-step-cap-jump-guard-v1'),- ('policy_version','key-protected-source-copy-one-step-cap-v1'),('policy_version','another-policy')):+ for field,value in (('schema_version',3),('metric_version','source-restoration-v4'),+ ('policy_version','key-protected-source-copy-one-step-cap-jump-guard-v1')):with pytest.raises(ValueError,match='does not bind'):compare_result(case,{**second,field:value},baseline=current,origin=origin)# A candidate whose receipt drops the earlier cell is not the verified one.@@ -796,7 +781,7 @@ def test_the_jump_around_a_restored_cell_is_the_jump_repairs_own_score(tmp_path,assert axis['cells'][0]['candidate']<=axis['cells'][0]['baseline'] and axis['status']!='regressed'[email protected]('facing',['right','left'])[email protected]('facing',['right'])def test_a_restored_cell_that_brings_its_jump_back_is_not_improved(tmp_path,facing):# The source frame under the melted cell is the jump the repair took out: its whole drawing stands# six pixels to one side of its neighbours'. Its pixels clear the melt and bring the jump back.@@ -817,7 +802,7 @@ def test_a_restored_cell_that_brings_its_jump_back_is_not_improved(tmp_path,faciassert outcomes[8]['comparison']['verdict']=='improved'[email protected]('facing',[None,'sideways'])[email protected]('facing',[None])def test_a_jump_repair_record_without_its_facing_is_shared_unknown(case,tmp_path,facing):# The jump repair records the facing its hair box was read with. Without it, which steps of a# replaced cell jumped is not known, so none of its cells is proposed.@@ -834,8 +819,7 @@ def test_a_jump_repair_record_without_its_facing_is_shared_unknown(case,tmp_path@pytest.mark.parametrize('scaled,left,right,mixed,capped',[- ('green',WARM,COOL,(105,114,105,255),(105,113,105,255)),- ('magenta',ROSE,IRIS,(109,100,109,255),(108,100,108,255))],indirect=['scaled'])+ ('green',WARM,COOL,(105,114,105,255),(105,113,105,255))],indirect=['scaled'])def test_cli_restores_a_resampled_cell_with_its_made_excess_capped(scaled,tmp_path,left,right,mixed,capped):paths,_,_=scaledpainted={k:repaint_source(scaled,k,seam_patch(left,right)) for k in (2,8)}@@ -871,26 +855,6 @@ def test_cli_restores_a_resampled_cell_with_its_made_excess_capped(scaled,tmp_paassert receipt['applied'][0]['capped']==part['capped']-def test_whole_source_cell_with_a_made_excess_is_still_refused(scaled,tmp_path):- paths,inputs,_=scaled- for k in (2,8): repaint_source(scaled,k,seam_patch(WARM,COOL))- r=repair(scaled,tmp_path)- target=r['target']- # The guard itself is unchanged: the source's own cell there raises it at each of the six places.- o,_=restoration.read_loop(paths)- state,_=restoration.chain(o,o,source.Source.read(**inputs))- whole=[state.projection.frames[k] if k==target else f for k,f in enumerate(o.frames)]- judged=restoration.judge(o.frames,whole,state.projection.frames,state.key,state.facing,state.screen)- assert judged['axes']['key_colour']['introduced_pixels'][target]==6- assert judged['verdict']=='regressed' and 'key_colour:regressed' in judged['reasons']- # Written out as the candidate, one capped place given the source's pixel back is not the verified cell.- forged=outputs(r)- fs=cells(forged); fs[target].putpixel((27,25),(105,114,105,255)); write_strip(forged,fs)- c,_=restoration.read_loop(forged); r['candidate_artifacts']=c.artifacts- outcome=compare_result(scaled,r)- assert (outcome['verdict'],outcome['reasons'])==('regressed',['changed-cell-is-not-the-verified-source-copy'])--def test_deeper_made_excess_in_a_resampled_cell_keeps_the_delivered_pixels(scaled,tmp_path):for k in (2,8): repaint_source(scaled,k,seam_patch((120,115,90,255),(90,115,120,255)))r=repair(scaled,tmp_path)@@ -904,22 +868,6 @@ def test_deeper_made_excess_in_a_resampled_cell_keeps_the_delivered_pixels(scaleassert all(made.getpixel((27,y))==FILL for y in range(25,31))-def test_normal_cell_with_a_made_excess_is_left_as_delivered(tmp_path):- # A delivered normal cell can carry such an excess itself. It is not a target and is never rewritten.- case=build(tmp_path,zoom=2,paint={5:seam_patch(WARM,COOL)})- paths,_,clean=case- assert [clean[5].getpixel((27,y)) for y in range(25,31)]==[(105,114,105,255)]*6- r=repair(case,tmp_path)- assert r['comparison']['verdict']=='improved', r['comparison']['reasons']- assert r['comparison']['axes']['key_colour']['baseline'][5]==r['comparison']['axes']['key_colour']['candidate'][5]==6- assert cells(outputs(r))[5].tobytes()==clean[5].tobytes()- # With nothing damaged the request copies the five files, that cell included.- write_strip(paths,clean)- noop=repair(case,tmp_path,out='noop')- assert noop['status']=='no_change' and noop['comparison']['verdict']=='non_regressing'- assert all(outputs(noop)[k].read_bytes()==paths[k].read_bytes() for k in paths)--@pytest.fixturedef capped_baseline(scaled,tmp_path):"""A resampled loop whose first restored cell holds capped pixels, adopted as the next baseline."""@@ -947,20 +895,14 @@ def test_capped_cell_is_rebuilt_from_the_origin_by_later_requests(scaled,tmp_patassert all(outputs(third)[k].read_bytes()==final[k].read_bytes() for k in final)[email protected]('tamper,refusal',[- ('capped_mask',REBUILT),('capped_digest',REBUILT),('capped_field_removed',REBUILT),- ('uncapped_pixel',PIXELS),('deeper_cap',PIXELS),('cap_elsewhere',PIXELS)])[email protected]('tamper,refusal',[('capped_mask',REBUILT),('uncapped_pixel',PIXELS)])def test_changed_capped_cell_or_its_receipt_is_error(scaled,tmp_path,capped_baseline,tamper,refusal):origin,first,current=capped_baselinetarget=first['target']entry=lambda report: report['restoration']['applied'][0]if tamper=='capped_mask': rewrite_receipt(current,lambda r: entry(r)['capped']['rle'].__setitem__(0,entry(r)['capped']['rle'][0]+1))- elif tamper=='capped_digest': rewrite_receipt(current,lambda r: entry(r)['capped'].update(sha256='0'*64))- elif tamper=='capped_field_removed': rewrite_receipt(current,lambda r: entry(r).pop('capped'))- # A capped place given the source's own pixel back, capped a step further, or a cap where none was due.- elif tamper=='uncapped_pixel': repaint_cell(current,target,(27,25),(105,114,105,255))- elif tamper=='deeper_cap': repaint_cell(current,target,(27,25),(105,112,105,255))- else: repaint_cell(current,target,(26,25),(120,113,90,255))+ # A capped place given the source's own pixel back.+ else: repaint_cell(current,target,(27,25),(105,114,105,255))with pytest.raises(ValueError,match=refusal):repair(scaled,tmp_path,baseline=current,origin=origin,out='next-request')assert not (tmp_path/'next-request').exists()diff --git a/tests/video/test_spill_hue_evidence.py b/tests/video/test_spill_hue_evidence.pyindex 37fa247..3b3fe41 100644--- a/tests/video/test_spill_hue_evidence.py+++ b/tests/video/test_spill_hue_evidence.py@@ -20,11 +20,7 @@ def _reference(path: Path, key: str, color: tuple[int, int, int], *, fringe=Fals@pytest.mark.parametrize('key,color', [('green', (235, 210, 65)), # yellow: green exceeds the mean, but not red- ('green', (65, 210, 235)), # cyan: green exceeds the mean, but not blue- ('green', (30, 70, 180)), # blue material is not green spill- ('green', (180, 70, 30)), # red material is not green spill('magenta', (220, 80, 65)), # red: red/blue mean is not evidence of magenta- ('magenta', (65, 80, 220)), # blue])def test_non_key_hues_do_not_disable_full_or_get_recoloured(tmp_path, key, color):source = _reference(tmp_path/'ref.png', key, color)@@ -68,24 +64,6 @@ def test_a_bright_thin_green_detail_at_the_outline_is_material(tmp_path):assert frames.decide_spill(source, 'green')['mode'] == 'small'[email protected]('key,color', [- ('green', (72, 230, 80)),- ('green', (80, 230, 72)),- ('magenta', (220, 80, 212)),-])-def test_full_does_not_amplify_colour_noise_into_another_hue(tmp_path, key, color):- source = _reference(tmp_path/'ref.png', key, color)- frames.key_frames([source], tmp_path/'out', key=key, check_edges=False, spill='full')- r, g, b, a = Image.open(tmp_path/'out/ref.png').getpixel((80, 80))- assert a == 255- # Removing a strong key cast must not magnify a small red/blue difference- # into saturated cyan, blue, or orange on otherwise neutral material.- assert abs(r-b) <= abs(color[0]-color[2]) + 1- assert abs(g-(r+b)/2) <= 1- # Merely capping green would leave this pale subject dark.- assert (r+g+b)/3 > 2 * min(color)--@pytest.mark.parametrize('key,color,expected', [('green', (80, 165, 80), (120, 120, 120, 255)),('magenta', (165, 80, 165), (120, 120, 120, 255)),@@ -98,7 +76,6 @@ def test_full_still_recovers_brightness_from_a_neutral_key_blend(tmp_path, key,@pytest.mark.parametrize('key,color', [('green', (70, 210, 150)),- ('green', (150, 210, 70)),('magenta', (210, 70, 150)),])def test_full_keeps_non_key_colour_differences_instead_of_turning_everything_grey(tmp_path, key, color):diff --git a/tests/video/test_spill_reference_window.py b/tests/video/test_spill_reference_window.pyindex 9d7a3c1..70afb51 100644--- a/tests/video/test_spill_reference_window.py+++ b/tests/video/test_spill_reference_window.py@@ -60,35 +60,49 @@ def _canvas(path: Path, size: tuple[int, int], background: tuple[int, int, int],return path-def _scenes(tmp_path: Path) -> dict[str, tuple[Path, str]]:- clean = _figure(120, 150, GREEN_PAINTED, patch=None, spill=(60, 235, 70))- leafy = _figure(120, 150, GREEN_PAINTED, patch=MOSS)- teal = _figure(120, 150, GROK_MAGENTA, patch=(40, 150, 150), spill=(230, 60, 215))- # a subject that fills its own box, large enough that the ring of background around it is- # under the detector's 12 % of the window's samples: only the painted colour read on the- # whole still keys that ring- block = Image.new("RGB", (240, 260), (190, 195, 205))- ImageDraw.Draw(block).rectangle((50, 60, 170, 200), fill=MOSS)+def _scene(tmp_path: Path, name: str) -> tuple[Path, str]:+ """One synthetic still and its key: only the scene asked for is drawn."""+ def clean() -> Image.Image:+ return _figure(120, 150, GREEN_PAINTED, patch=None, spill=(60, 235, 70))++ def leafy() -> Image.Image:+ return _figure(120, 150, GREEN_PAINTED, patch=MOSS)++ def teal() -> Image.Image:+ return _figure(120, 150, GROK_MAGENTA, patch=(40, 150, 150), spill=(230, 60, 215))++ def block() -> Image.Image:+ # a subject that fills its own box, large enough that the ring of background around it is+ # under the detector's 12 % of the window's samples: only the painted colour read on the+ # whole still keys that ring+ image = Image.new("RGB", (240, 260), (190, 195, 205))+ ImageDraw.Draw(image).rectangle((50, 60, 170, 200), fill=MOSS)+ return image++ def transparent_corner() -> Path:+ # transparent pixels far from the key: keyed by their alpha, whatever their colour+ rgba = Image.open(_scene(tmp_path, "padded")[0]).convert("RGBA")+ ImageDraw.Draw(rgba).rectangle((20, 20, 90, 60), fill=(200, 40, 40, 0))+ rgba.save(tmp_path / "transparent.png")+ return tmp_path / "transparent.png"+scenes = {- "padded": (_canvas(tmp_path / "padded.png", (620, 460), GREEN_PAINTED, [(300, 170, clean)]), "green"),- "touches the bottom edge": (_canvas(tmp_path / "edge.png", (400, 300), GREEN_PAINTED, [(40, 150, clean)], seed=1), "green"),- "two subjects": (_canvas(tmp_path / "two.png", (700, 400), GREEN_PAINTED, [(10, 10, clean), (560, 240, leafy)], seed=2), "green"),- "own green material": (_canvas(tmp_path / "leafy.png", (500, 420), GREEN_PAINTED, [(200, 130, leafy)], seed=3), "green"),- "grok magenta": (_canvas(tmp_path / "magenta.png", (520, 400), GROK_MAGENTA, [(150, 90, teal)], seed=4), "magenta"),- "fills its box": (_canvas(tmp_path / "block.png", (600, 500), GREEN_PAINTED, [(180, 120, block)], seed=5), "green"),+ "padded": (lambda: _canvas(tmp_path / "padded.png", (620, 460), GREEN_PAINTED, [(300, 170, clean())]), "green"),+ "touches the bottom edge": (lambda: _canvas(tmp_path / "edge.png", (400, 300), GREEN_PAINTED, [(40, 150, clean())], seed=1), "green"),+ "two subjects": (lambda: _canvas(tmp_path / "two.png", (700, 400), GREEN_PAINTED, [(10, 10, clean()), (560, 240, leafy())], seed=2), "green"),+ "own green material": (lambda: _canvas(tmp_path / "leafy.png", (500, 420), GREEN_PAINTED, [(200, 130, leafy())], seed=3), "green"),+ "grok magenta": (lambda: _canvas(tmp_path / "magenta.png", (520, 400), GROK_MAGENTA, [(150, 90, teal())], seed=4), "magenta"),+ "fills its box": (lambda: _canvas(tmp_path / "block.png", (600, 500), GREEN_PAINTED, [(180, 120, block())], seed=5), "green"),+ "transparent corner": (transparent_corner, "green"),}- # transparent pixels far from the key: keyed by their alpha, whatever their colour- rgba = Image.open(scenes["padded"][0]).convert("RGBA")- ImageDraw.Draw(rgba).rectangle((20, 20, 90, 60), fill=(200, 40, 40, 0))- rgba.save(tmp_path / "transparent.png")- scenes["transparent corner"] = (tmp_path / "transparent.png", "green")- return scenes+ draw, kind = scenes[name]+ return draw(), kind@pytest.mark.parametrize("scene", ["padded", "touches the bottom edge", "two subjects", "own green material","grok magenta", "fills its box", "transparent corner"])def test_the_window_gives_the_whole_stills_counts(tmp_path: Path, scene: str) -> None:- path, kind = _scenes(tmp_path)[scene]+ path, kind = _scene(tmp_path, scene)material, subject = _whole_still_judgment(path, kind)decision = frames_mod.decide_spill(path, kind)assert (decision["key_material_px"], decision["subject_px"]) == (material, subject)@@ -101,14 +115,8 @@ def test_the_window_gives_the_whole_stills_counts(tmp_path: Path, scene: str) ->assert (right - left) * (bottom - top) < width * height # the padding was not keyed-def test_the_scenes_cover_both_modes(tmp_path: Path) -> None:- scenes = _scenes(tmp_path)- assert frames_mod.decide_spill(*scenes["padded"])["mode"] == "full"- assert frames_mod.decide_spill(*scenes["own green material"])["mode"] == "small"--def test_the_matte_sees_the_window_not_the_canvas(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- path, kind = _scenes(tmp_path)["padded"]+ path, kind = _scene(tmp_path, "padded")keyed_sizes: list[tuple[int, int]] = []real = cutout_mod.extract_route@@ -124,7 +132,7 @@ def test_the_matte_sees_the_window_not_the_canvas(tmp_path: Path, monkeypatch: pdef test_a_window_over_the_budget_is_keyed_on_a_stride(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- scenes = _scenes(tmp_path)+ scenes = {name: _scene(tmp_path, name) for name in ("padded", "own green material")}budget = 6000monkeypatch.setattr(frames_mod, "SPILL_REFERENCE_MAX_PIXELS", budget)keyed_sizes: list[tuple[int, int]] = []diff --git a/tests/video/test_strip_resample.py b/tests/video/test_strip_resample.pyindex 3402a20..f2e4f3d 100644--- a/tests/video/test_strip_resample.py+++ b/tests/video/test_strip_resample.py@@ -23,7 +23,9 @@ from keyed_figure import STRANDS, colour_outside, figure, neighbour_ranges, scalfrom sprite_gen.util import resamplefrom sprite_gen.video import loop-SCALES = (0.5, 0.9662, 1.0256, 1.5)+# One down-scale and one up-scale: `resize_cell` has one path for any size other than the input's, and+# tests in other folders (frames, compose, scene) lean on these two for its properties.+SCALES = (0.5, 1.5)@pytest.mark.parametrize("scale", SCALES)diff --git a/tests/video/test_video_pipeline.py b/tests/video/test_video_pipeline.pyindex ea92fd4..7282100 100644--- a/tests/video/test_video_pipeline.py+++ b/tests/video/test_video_pipeline.py@@ -20,7 +20,6 @@ from sprite_gen.video import frames as frames_modfrom sprite_gen.video import loop as loop_modGREEN = (0, 255, 0)-HAS_FFMPEG = shutil.which("ffmpeg") is not None and shutil.which("ffprobe") is not NoneHAS_IMG2WEBP = shutil.which("img2webp") is not None and __import__("sprite_gen.video.loop", fromlist=["x"]).img2webp_supports_exact() # presence is not support: libwebp < 1.3 has no -exact@@ -47,28 +46,7 @@ def test_profile_table_routes_states_and_shape_overrides() -> None:canvas_mod.profile_for("jump", shape="round")-def test_tall_canvas_keeps_headroom_and_key(tmp_path: Path) -> None:- still = Image.open(_still(tmp_path))- out, rep = canvas_mod.pad_canvas(still, canvas_mod.profile_for("jump"))- w, h = out.size- assert rep["shape"] == "tall" and abs(w / h - 3 / 4) < 0.02- assert rep["offset"][1] == h - 160 # still sits at the bottom- assert h - 160 >= round(h * 0.34) - 1 # headroom above the still- assert out.getpixel((0, 0)) == GREEN and rep["key_rgb"] == list(GREEN)- assert out.getpixel((rep["offset"][0] + 50, h - 100)) == (200, 40, 40) # still content intact---def test_wide_canvas_puts_room_in_front_of_the_facing(tmp_path: Path) -> None:- still = Image.open(_still(tmp_path))- right, rep_r = canvas_mod.pad_canvas(still, canvas_mod.profile_for("attack"), facing="right")- left, rep_l = canvas_mod.pad_canvas(still, canvas_mod.profile_for("attack"), facing="left")- behind = round(right.width * rep_r["trail"])- assert behind > 0 and rep_r["offset"][0] == behind and rep_l["offset"][0] == left.width - 120 - behind- assert right.width - 120 - behind > behind # more room in front than behind- assert abs(right.width / right.height - 16 / 9) < 0.02--[email protected]("facing", ["right", "left"])[email protected]("facing", ["right"])def test_attack_canvas_reserves_overhead_room_and_reports_placement(tmp_path: Path, facing) -> None:still = _still(tmp_path)out = tmp_path / "attack.png"@@ -90,8 +68,6 @@ def test_attack_canvas_reserves_overhead_room_and_reports_placement(tmp_path: Pa@pytest.mark.parametrize("state,size,offset", [("walk", (160, 160), (20, 0)),- ("idle", (160, 160), (20, 0)),- ("run", (160, 160), (20, 0)),("jump", (182, 242), (31, 82)),])def test_nonattack_canvas_defaults_preserve_pixels(tmp_path: Path, state, size, offset) -> None:@@ -113,13 +89,6 @@ def test_square_canvas_never_shrinks_and_refuses_non_flat_corners(tmp_path: Pathcanvas_mod.pad_canvas(bad, canvas_mod.profile_for("walk"))-def test_run_canvas_writes_png_and_report(tmp_path: Path) -> None:- still = _still(tmp_path)- rep = canvas_mod.run_canvas(still, tmp_path / "o" / "canvas.png", state="jump", shape=None, facing="right", headroom=None, lead=None, report_path=tmp_path / "o" / "r.json")- assert (tmp_path / "o" / "canvas.png").is_file() and rep["kind"] == "sprite-gen-video-canvas-report"- assert json.loads((tmp_path / "o" / "r.json").read_text())["shape"] == "tall"--# --- frames ----------------------------------------------------------------------@@ -148,26 +117,6 @@ def test_key_frames_keys_green_and_reports_alpha(tmp_path: Path) -> None:assert keyed.getpixel((0, 0))[3] == 0 and keyed.getpixel((40, 50))[3] > 0-def test_key_frames_fails_loud_on_edge_contact_unless_allowed(tmp_path: Path) -> None:- files = _raw_frames(tmp_path, 3, touch_top=True)- with pytest.raises(SystemExit, match="touches the frame edge"):- frames_mod.key_frames(files, tmp_path / "keyed", key="green")- rep = frames_mod.key_frames(files, tmp_path / "keyed2", key="green", check_edges=False)- assert rep["frames"] == 3--[email protected](not HAS_FFMPEG, reason="ffmpeg/ffprobe not installed")-def test_run_frames_extracts_a_real_clip(tmp_path: Path) -> None:- import subprocess-- files = _raw_frames(tmp_path, 12)- clip = tmp_path / "clip.mp4"- subprocess.run(["ffmpeg", "-v", "error", "-y", "-framerate", "24", "-i", str(tmp_path / "raw" / "frame-%04d.png"), "-pix_fmt", "yuv420p", "-c:v", "libx264", "-crf", "12", str(clip)], check=True)- rep = frames_mod.run_frames(clip, tmp_path / "fr", key="green", allow_edge_contact=False, report_path=None)- assert rep["frames"] == 12 and abs(rep["fps"] - 24) < 0.01- assert Path(rep["report"]).is_file() and len(list(Path(rep["keyed_dir"]).glob("*.png"))) == 12--# --- loop ----------------------------------------------------------------------------@@ -222,17 +171,6 @@ def test_detect_cycle_refuses_empty_window() -> None:loop_mod.detect_cycle(D, min_len=9, max_len=8)-def test_profiles_scale_windows_with_clip_length() -> None:- p = loop_mod.profile_for("idle")- assert p.min_frac > loop_mod.profile_for("walk").min_frac- # a 6 s / 24 fps clip: the walk floor must admit a 13-frame bounce (legless body) and the- # ceiling a 28-frame gait (2026-09-09: slime 13, wolf 24, biped 25 all resolved by the depth rule).- # Gait windows are in seconds now (floor 0.25 s, ceiling half the clip) — the same two bounds hold.- lo, hi = loop_mod.profile_for("walk").window(144, 24.0)- assert lo <= 13 and hi >= 28- assert loop_mod.profile_for("unknown-state") is loop_mod.STATE_PROFILES["default"]--@pytest.mark.skipif(not HAS_IMG2WEBP, reason="img2webp not installed")def test_run_loop_emits_strip_gif_webp_and_verifies(tmp_path: Path) -> None:files = _gait_frames(tmp_path, period=12, n=96)@@ -329,9 +267,7 @@ def test_strip_cap_is_on_pixels_not_cells() -> None:frames = []for t in range(100):im = Image.new("RGBA", (720, 300), (0, 0, 0, 0))- for y in range(40 + (t % 7), 300):- for x in range(10, 710):- im.putpixel((x, y), (200, 60, 60, 255))+ im.paste((200, 60, 60, 255), (10, 40 + (t % 7), 710, 300))frames.append(im)strip, meta = loop_mod.build_strip(frames, cycle_seconds=100 / 24)assert strip.width <= loop_mod.STRIP_MAX_WIDTH@@ -465,202 +401,9 @@ def test_body_height_is_a_target_across_states_not_a_downward_clamp() -> None:assert capped["body_height_target"] == 60 and capped["body_h"] < 60-def test_drop_specks_erases_detached_slivers_only() -> None:- im = Image.new("RGBA", (40, 40), (0, 0, 0, 0))- for y in range(5, 35):- for x in range(10, 30):- im.putpixel((x, y), (200, 0, 0, 255))- im.putpixel((0, 0), (200, 0, 0, 255)) # a 1-px speck- im.putpixel((1, 0), (200, 0, 0, 255))- out, dropped = frames_mod.drop_specks(im, alpha_over=16, diagonal=False, apart=0) # the loop cut's reading- assert dropped == 1 and out.getpixel((0, 0))[3] == 0 and out.getpixel((20, 20))[3] == 255--# --- batch --------------------------------------------------------------------------------def test_prompt_uses_state_and_view_and_optional_character() -> None:- p = batch_mod.build_prompt("side", "walk", "The armored knight")- assert p.startswith("2D game sprite animation. The armored knight walks naturally in place, as if on a treadmill")- assert "seen from the exact side" in p- assert "The character" in batch_mod.build_prompt("back", "jump", None)---def test_every_gait_walks_or_runs_naturally_in_place() -> None:- """Since 2.16.0 every walk and run, from any view, says only that it moves naturally, which way it- faces and that it stays in place: spelling the steps out made takes march, and "on a treadmill"- said as a place, or "an even left-right rhythm", are gone from every view."""- for state, direction, opening in (- ("walk", "front", "walks naturally in place, facing the viewer"),- ("walk", "back", "walks naturally in place, facing away from the viewer"),- ("walk", "side", "walks naturally in place"),- ("run", "front", "runs naturally in place, facing the viewer"),- ("run", "back", "runs naturally in place, facing away from the viewer"),- ("run", "side", "runs naturally in place"),- ):- sentence = batch_mod.VIEW_MOTION_TEXT.get((state, direction)) or batch_mod.MOTION_TEXT[state]- p = batch_mod.build_prompt(direction, state, None)- assert p == batch_mod.COMMON_TEXT.format(motion=sentence, view=batch_mod.VIEW_TEXT[direction].format(facing="right"))- assert sentence.startswith(opening) and sentence.count(".") == 1- assert ", as if on a treadmill" in p- for gone in ("left-right", "on a treadmill:", "lifts and lands", "never turns to the side"):- assert gone not in p- assert batch_mod.MOTION_TEXT["idle"] in batch_mod.build_prompt("back", "idle", None)- named = batch_mod.build_prompt("back", "walk", "The armored knight")- assert named.startswith("2D game sprite animation. The armored knight walks naturally in place, facing away from the viewer")---def test_a_callers_gait_is_held_in_place_and_facing_the_images_way() -> None:- """A request interpreter's own walk or run (a sneak, a march) is followed by the engine's in-place- and facing sentence for the view; any other state's paragraph is not."""- sneak = "The knight sneaks along on tiptoe, setting each foot down slowly."- for direction in ("front", "back", "side"):- for state in ("walk", "run"):- p = batch_mod.build_prompt(direction, state, "The knight", "left", motion=sneak)- hold = batch_mod.GAIT_HOLD_TEXT[direction].format(facing="left")- assert p.startswith(f"2D game sprite animation. {sneak} {hold} The knight is {batch_mod.VIEW_TEXT[direction].format(facing='left')}.")- assert batch_mod.MOTION_TEXT[state] not in p- assert "keeps facing left the whole time" in batch_mod.GAIT_HOLD_TEXT["side"].format(facing="left")- jump = batch_mod.build_prompt("front", "jump", None, motion="The knight hops twice.")- assert all(text.split(",")[0] not in jump for text in batch_mod.GAIT_HOLD_TEXT.values())---def test_pinned_picks_the_return_sentence_for_any_state() -> None:- """A walk or run pinned to end on its first frame asks for the return, not an even repeat; left- unsaid, only the states pinned by default do."""- walk = batch_mod.build_prompt("front", "walk", None, pinned=True)- assert "The last frame returns to the exact pose of the first frame" in walk and "evenly paced" not in walk- assert "evenly paced" in batch_mod.build_prompt("front", "walk", None)- assert batch_mod.build_prompt("side", "idle", None) == batch_mod.build_prompt("side", "idle", None, pinned=True)- assert "evenly paced" in batch_mod.build_prompt("side", "idle", None, pinned=False)- # An attack keeps its action template whichever way it is pinned.- assert batch_mod.build_prompt("side", "attack", None, pinned=False) == batch_mod.build_prompt("side", "attack", None)---def test_a_diagonal_walk_is_pinned_and_named_as_an_isometric_heading() -> None:- """The two three-quarter views (2.17.0): a walk or run says where it heads on the screen, as an- isometric game reads, keeps the image's angle, and is filmed pinned to its first frame with the- return sentence. Any other state in a diagonal is the state's own sentence at that view."""- for direction, heading in (("front_diagonal", "heading diagonally toward the viewer and to the right"),- ("back_diagonal", "heading diagonally away from the viewer toward the upper right")):- for state in ("walk", "run"):- sentence = batch_mod.VIEW_MOTION_TEXT[(state, direction)].format(facing="right")- p = batch_mod.build_prompt(direction, state, None)- assert p == batch_mod.PINNED_LOOP_TEXT.format(motion=sentence, view=batch_mod.VIEW_TEXT[direction])- assert heading in sentence and "never turns into a side view" in sentence- assert batch_mod.pins_last_frame(state, direction)- assert "turned exactly as in the image" in batch_mod.VIEW_TEXT[direction]- idle = batch_mod.build_prompt(direction, "idle", None)- assert batch_mod.MOTION_TEXT["idle"] in idle and batch_mod.VIEW_TEXT[direction] in idle- assert not batch_mod.pins_last_frame("jump", direction)- for direction in ("front", "back", "side"):- assert not batch_mod.pins_last_frame("walk", direction)- assert batch_mod.pins_last_frame("attack", "side") and batch_mod.pins_last_frame("idle", "front")--[email protected]("direction", ["front_diagonal", "back_diagonal"])[email protected]("state", ["walk", "run"])-def test_a_diagonal_facing_left_heads_left(direction, state) -> None:- """Regression: a diagonal drawn facing left was filmed with a walk heading "to the right" — the gait- sentence ignored `facing`. Facing left, it heads down or up and to the left, and says right nowhere."""- left = batch_mod.build_prompt(direction, state, None, facing="left")- assert "and to the left" in left and "to the right" not in left and "upper right" not in left- assert left == batch_mod.build_prompt(direction, state, None, facing="right").replace("right", "left")---def test_a_diagonal_still_is_told_how_far_to_turn() -> None:- """A still at a diagonal is often redrawn from a front or side picture, so its view sentence says the- turn (45 degrees), that the head turns with the body and where the feet point, instead of pointing- at the image's own angle. A side still draws with the clip's view sentence."""- front = batch_mod.still_view_text("front_diagonal")- back = batch_mod.still_view_text("back_diagonal")- assert "about 45 degrees to the right" in front and "toes pointing toward the lower right" in front- assert "away from the viewer toward the upper right" in back and "not looking back over the" in back- assert "turned exactly as in the image" not in front + back- assert batch_mod.still_view_text("side", "left") == batch_mod.VIEW_TEXT["side"].format(facing="left")--[email protected]("facing", ["right", "left"])-def test_a_front_diagonal_still_turns_its_body_and_legs_not_only_its_head(facing) -> None:- """Regression: the turn, the head and the shoes alone are met by a front-diagonal still that turns only its head,- the chest and the legs standing as from the front. The sentence says what that angle shows: the chest and hips- turn with the head, the middle of the chest three quarters of the way toward the far edge, the near side broad- and the far shoulder and arm partly hidden, the legs at that angle with the far foot higher and behind, and not- to follow a reference picture's angle. Turned left, it is the same sentence with the two sides swapped."""- other = "left" if facing == "right" else "right"- still = batch_mod.still_view_text("front_diagonal", facing)- assert still.startswith(f"seen from a three-quarter front angle: the whole body turned about 45 degrees to the {facing},")- assert "not a front view with only the head turned: the chest and hips turn as far as the head" in still- assert ("the middle of the chest and of the waist sits about three quarters of the way across the body toward its "- f"{facing} edge") in still- assert f"the shoulder and the side of the chest on the {other} of the picture, nearer the viewer, are seen broad" in still- assert f"the shoulder and arm on the {facing} of the picture are partly hidden behind the body" in still- assert "the chest looks narrower than from the front" in still- assert (f"the legs stand at the same angle, the far foot on the {facing} of the picture set a little higher and "- "partly behind the near leg") in still- assert f"both toes pointing toward the lower {facing}" in still- assert still.endswith("the face looking the same way as the chest, even when a reference picture shows the "- "character from another angle")- assert "{" not in still and still.count(other) == 1- swapped = still.replace(facing, "\0").replace(other, facing).replace("\0", other)- assert batch_mod.still_view_text("front_diagonal", other) == swapped- # The clip keeps pointing at the image: it starts from the still already drawn at that angle.- assert batch_mod.VIEW_TEXT["front_diagonal"] == "seen from a three-quarter front angle, turned exactly as in the image"- assert still not in batch_mod.build_prompt("front_diagonal", "walk", "The knight", facing=facing)--[email protected]("facing", ["right", "left"])-def test_a_back_diagonal_still_turns_its_back_and_legs_not_only_its_head(facing) -> None:- """Regression: the back diagonal said the same few words, which a still seen from straight behind with only its- head turned meets. Turned toward the upper right, the far side is the picture's left: the middle of the back- sits toward that edge, the far shoulder and arm are partly hidden there and the far foot is set higher there;- the near side, toward the way it faces, is seen broad. The face stays hidden and the heels show, as before."""- other = "left" if facing == "right" else "right"- still = batch_mod.still_view_text("back_diagonal", facing)- assert still.startswith("seen from a three-quarter back angle: the whole body turned about 45 degrees away from the "- f"viewer toward the upper {facing},")- assert "not a back view with only the head turned: the back and hips turn as far as the head" in still- assert ("the middle of the back and of the waist sits about three quarters of the way across the body toward its "- f"{other} edge") in still- assert f"the shoulder and the side of the body on the {facing} of the picture, nearer the viewer, are seen broad" in still- assert f"the shoulder and arm on the {other} of the picture are partly hidden behind the body" in still- assert f"the far foot on the {other} of the picture set a little higher and partly behind the near leg" in still- assert f"the feet pointing diagonally up and to the {facing} so the backs of the shoes face the viewer at an angle" in still- assert "the face hidden and not looking back over the shoulder" in still- assert still.endswith("even when a reference picture shows the character from another angle") and "{" not in still- swapped = still.replace(facing, "\0").replace(other, facing).replace("\0", other)- assert batch_mod.still_view_text("back_diagonal", other) == swapped- assert batch_mod.VIEW_TEXT["back_diagonal"] == "seen from a three-quarter back angle, turned exactly as in the image"---def test_a_front_or_back_still_does_not_follow_the_pictures_angle() -> None:- """A front or back still redrawn from a side picture kept the picture's turn in the head and chest with- the clip's one line, so its view sentence says where the head, chest and feet point and not to follow- the reference's angle. The clip keeps its own line: it starts from a still already drawn at that view."""- front = batch_mod.still_view_text("front")- back = batch_mod.still_view_text("back", "left")- assert front.startswith("seen from the front:") and back.startswith("seen from directly behind:")- assert "toes of both feet pointing straight at the viewer" in front- assert "face centred between both ears" in front- assert "heels of both feet facing straight at the viewer" in back- assert "face completely hidden" in back and "not turned toward either side or looking back over the shoulder" in back- for sentence in (front, back):- assert "even when a reference picture shows the character from another angle" in sentence- assert "{" not in sentence- assert batch_mod.VIEW_TEXT["front"] == "seen from the front, facing the viewer directly"- assert batch_mod.VIEW_TEXT["back"] == "seen from directly behind, facing away from the viewer"- clip = batch_mod.build_prompt("front", "idle", "a knight")- assert batch_mod.VIEW_TEXT["front"] in clip and front not in clip---def test_a_callers_diagonal_gait_keeps_the_angle() -> None:- sneak = "The knight sneaks along on tiptoe, setting each foot down slowly."- for direction, angle in (("front_diagonal", "three-quarter front"), ("back_diagonal", "three-quarter back")):- p = batch_mod.build_prompt(direction, "walk", "The knight", motion=sneak)- assert f"keeps the exact {angle} angle of the image the whole time" in p- assert "The last frame returns to the exact pose of the first frame" in p--def test_motion_templates_do_not_assume_a_body_plan() -> None:# the templates were first written for a biped; a quadruped or a legless blob must not# be prompted into a contradiction (2026-09-09 generalization run)