Skip to content

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

feat(rife): every call runs the binary's test-time augmentation -x -z

Soohong Kim5eb804e3bf5e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4c53b0e..e771fb6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,8 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the
## Unreleased
+- **Behavior change: every RIFE call runs the binary's test-time augmentation, `-x -z` (`rife.TTA`).** `-x` runs the pair as its eight flips and transposes and `-z` both ways in time, and the results are averaged, so a frame made from a to b is the one made from b to a. Neither rife-ncnn-vulkan nor Practical-RIFE has released a model since 2024; the model stays `rife-v4.6`. On the synthetic pairs of `tests/video/test_rife.py`, `-x -z` is the one setting of the four (none, `-x`, `-z`, both) that makes legs crossing far the same both ways with no ghost, and it keeps the most of a short step's outline. On the Mac's GPU it adds a tenth to half a second a frame; on Modal's CPU it costs 15 to 19 times a plain call's CPU — 12 to 30 s a 280 × 520 frame on two cores, 44 to 61 s a 960 × 960 frame. `SPRITE_GEN_RIFE_TTA` names another (`-x`, `-z`, both, or empty for none; anything else is refused before a frame is asked for), for a CPU-only machine that aligns sets. The interpolator a report names (`jump_repair.interpolator`, the alignment's `interpolator`) carries `tta`. A call past 600 s (120 s before) is stopped and reported as a RIFE that failed, where it used to end in Python's own timeout ([loop-repair](docs/loop-repair.md) section 1, "Which setting").
+- **Tests** — `tests/video/test_rife.py` (every call asks for `-x -z` and never `-g`; `SPRITE_GEN_RIFE_TTA` names either mode, both or none, and anything else is refused; a call past its time is a RIFE that failed; the real-RIFE pairs read with the augmentation: legs crossing far melt the same both ways and leave no ghost, a short step stays outlined, legs walking through each other add no dark where they cross; a refused repair names its faults whole, not by the first of a sorted list), `tests/conftest.py` (every test runs the engine's own augmentation, whatever the calling shell sets).
- **New: the flow reading of a walk loop (`repair.flow_scores`, `repair.flow_targets`) — the frames that leave the way a part is going, by direction and speed, not by the size of a step.** Each frame is a point of the loop's path, its coverage and shading blurred by 3 % of the body height, read in nine windows of the union box: how far it lies off the straight line between its neighbours (the second difference, the acceleration), in that window's usual steps. A clip filmed on twos or threes is read on its drawings, the hold `held.measure`'s. `flow_targets` takes the worst frame at or over 3.0 first and names the fewest frames around it — one, then two — whose straight in-between brings every frame it touches under 3.0, never made from a frame taken before; what two cannot bring under is `unfixed`. On the synthetic walks an ordinary loop reads at most 1.65 where the jump score names 8 to 18 steps, and a tail flung 5 % of the body height against its sway reads 2.8 to 4.1. The methods weighed beside it — interpolation error with RIFE, optical flow, a periodic fit, a Kalman predictor, Savitzky–Golay, a Hampel test — and their sources are in docs/loop-repair.md section 2, "The flow reading".
- **Behavior change: `video-loop --repair auto` (and `on`) takes out the frames off a walk's flow and makes them again between the frames either side, each at its own time.** The frames are the flow reading's (`repair.flow_targets`), not the jump score's: a step 1.4 times the loop's median no longer remakes the frame after it, so the quick swing of an ordinary walk is left as filmed, and a frame flung against the way a part is going, which the jump score read no larger than a swing, is taken out. A group is one or two drawings in a row; RIFE makes each drawing between the first frame of the drawing before the group and of the drawing after, at the drawing's own time (`repair.between_time`: a half for one frame, a third and two thirds for two, a half for a drawing on twos), and shows it on every frame the drawing was — the loop keeps its length, every frame its time, a loop on twos its hold. One call a drawing, at most three a loop; one made frame with an interpolation fault refuses its whole group, which keeps its frames as filmed, and nothing is made from or beside a frame made, given way or refused. Of the groups that bring the reading under the limit, `flow_targets` now takes the one whose every drawing the in-between moves furthest (`move`): two frames flung together are taken out whole, where the frame beside the pair was taken before and the pair left standing. A loop whose only large steps are the steps into and out of a few jumps no longer reads as held (`HELD_RUNS`: three in four runs must be the hold, a frame more or less): read on those false drawings its jumps read as ordinary, and a drawing made would have stood for five frames. `jump_repair` reads `reading: flow`, `limit`, `span`, `hold`, `drawings`, `refused`, `unfixed`, `left`, `off_max_before` / `off_max_after` (in place of `score_max_before` / `score_max_after`, also in the summary and in `video-set`'s item record), and per round `why: flow` with its group and `made` (per drawing: `frames`, `t`, `original`, `proposal`, `faults`, `look`); `unmade` names the group's `frames`, `neighbours` and `off`. `repair.JUMP_RATIO` is gone; `repair.jump_scores` stays, the size reading `video-loop-compare`'s jump guard reads with the recorded `facing` ([loop-repair](docs/loop-repair.md#2-jump-frames--video-loop---repair-auto)).
- **Tests** — `tests/video/test_loop_flow.py` (an ordinary walk the jump score would remake is left alone and RIFE is not called; a flung frame made again half way between its neighbours, every other frame the video's own; two flung frames made again at a third and two thirds; on twos a flung drawing made once from the frames two before and two after it and shown on both its frames; a group with one made frame at fault keeps both frames and is not tried again; the calls go to the worst frame first and stop at three, the group left named; no interpolator names the group; mirrored, the same) and `tests/video/test_loop_repair.py` (on its block walker: one flung frame, two side by side, the pair flung at the wrap taken out whole and made from the frames beside it rather than smoothed at its edges, jumps a few frames apart read a drawing a frame and not on threes, three outline-melted groups refused within the budget, groups made only from frames as filmed; `video-loop` playing two frames made again at their own times in a loop as long, and the flow numbers when no RIFE is installed); the ghost and cross-fade proposals of `tests/video/test_ghost_screen.py`, `tests/video/test_crossfade.py` and the real-RIFE case of `tests/video/test_rife.py` read through a group the flow reading is made to name.
diff --git a/SKILL.md b/SKILL.md
index 2b65979..efcebe8 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -12,7 +12,7 @@ depends_on:
- name: img2webp
why: "video-loop WebP with exact alpha (libwebp); Pillow's animated writer drops -exact"
- name: rife-ncnn-vulkan
- why: "video-loop jump repair and video-cycle-align (RIFE v4.6 in-betweens, release 20221029). Install once with `sprite-gen rife install` (sha256-checked, into the user data directory); SPRITE_GEN_RIFE or PATH override it; Linux without a GPU also needs libvulkan1 mesa-vulkan-drivers. Without it, walk and run loops are cut as filmed with a warning"
+ why: "video-loop jump repair and video-cycle-align (RIFE v4.6 in-betweens with the -x -z test-time augmentation, release 20221029). Install once with `sprite-gen rife install` (sha256-checked, into the user data directory); SPRITE_GEN_RIFE or PATH override it; Linux without a GPU also needs libvulkan1 mesa-vulkan-drivers. Without it, walk and run loops are cut as filmed with a warning"
required_scripts:
- scripts/prepare_sprite_run.py
- scripts/generate_sprite_image.py
@@ -144,7 +144,7 @@ Scene creation consumes finished assets and remains optional. Asset metadata own
## RIFE for walk and run loops
-`video-loop` repairs a walk's or run's jump frames and gives its filmed ghosts way (a half-drawn frame the video model left, `ghost_given_way`), and `video-set` gives a direction set one cycle length, both with RIFE in-betweens. Install it once per machine: `$SPRITE_GEN_ROOT/.venv/bin/sprite-gen rife install` (pinned rife-ncnn-vulkan 20221029 and model rife-v4.6, SHA-256 checked, into the user data directory, ending with a check frame; Linux without a GPU first needs `libvulkan1 mesa-vulkan-drivers`). Without it every loop is still cut — a jump as filmed, each filmed ghost given way to the clean frame beside it — and what was left unrepaired says so: a `warning:` line on stderr and `jump_repair.rife` with `jump_repair.unmade` (the jump left as filmed) in the loop report (`applied` alone is not the sign: a ghost given way reads true), `cycle_align.<state>.applied: false` and `warnings` in `set.report.json`. When that happens, tell the user which loops went unrepaired and offer the install; after it, cut those loops again and run `video-cycle-align`. `video-loop --repair on` and `video-cycle-align` fail without RIFE instead. [loop-repair](docs/loop-repair.md).
+`video-loop` repairs a walk's or run's jump frames and gives its filmed ghosts way (a half-drawn frame the video model left, `ghost_given_way`), and `video-set` gives a direction set one cycle length, both with RIFE in-betweens. Install it once per machine: `$SPRITE_GEN_ROOT/.venv/bin/sprite-gen rife install` (pinned rife-ncnn-vulkan 20221029 and model rife-v4.6, SHA-256 checked, into the user data directory, ending with a check frame; Linux without a GPU first needs `libvulkan1 mesa-vulkan-drivers`). Every call runs the binary's test-time augmentation `-x -z`; on a CPU it costs 15 to 19 times a plain call, so a CPU-only machine aligning a set may set `SPRITE_GEN_RIFE_TTA=` (none) or `-z`. Without it every loop is still cut — a jump as filmed, each filmed ghost given way to the clean frame beside it — and what was left unrepaired says so: a `warning:` line on stderr and `jump_repair.rife` with `jump_repair.unmade` (the jump left as filmed) in the loop report (`applied` alone is not the sign: a ghost given way reads true), `cycle_align.<state>.applied: false` and `warnings` in `set.report.json`. When that happens, tell the user which loops went unrepaired and offer the install; after it, cut those loops again and run `video-cycle-align`. `video-loop --repair on` and `video-cycle-align` fail without RIFE instead. [loop-repair](docs/loop-repair.md).
## Contracts and advanced tools
diff --git a/docs/loop-repair.md b/docs/loop-repair.md
index 9a722ec..e6f920d 100644
--- a/docs/loop-repair.md
+++ b/docs/loop-repair.md
@@ -1,6 +1,6 @@
# Loop repair — RIFE in-betweens for jump frames, the jolt index, one cycle per set
-> Owns: Where RIFE runs and what it costs, how it is installed and what runs without it, jump-frame repair in `video-loop`, the flow reading (frames off a walk's way), the jolt index and its gate, cycle alignment across a direction set · Index: [docs/README.md](README.md)
+> Owns: Where RIFE runs and what it costs, which model and augmentation it runs with, how it is installed and what runs without it, jump-frame repair in `video-loop`, the flow reading (frames off a walk's way), the jolt index and its gate, cycle alignment across a direction set · Index: [docs/README.md](README.md)
A walk loop cut from a generated clip can look right in every still and still hitch when it
plays: the video model redraws thin hair a little differently every frame, and now and then
@@ -19,7 +19,10 @@ where the appearance does not change and only the motion does — the case optic
[rife-ncnn-vulkan](https://github.com/nihui/rife-ncnn-vulkan) release **20221029**, model
**`rife-v4.6`** (shipped inside the release zip). The engine calls the binary as an external
-tool, like `ffmpeg` and `img2webp`; nothing is vendored into the package.
+tool, like `ffmpeg` and `img2webp`; nothing is vendored into the package. Every call asks for
+the binary's test-time augmentation, spatial and temporal (`-x -z`, `rife.TTA`;
+[Which setting](#which-setting--measured-2026-10-15) below); `SPRITE_GEN_RIFE_TTA` names another —
+`-x`, `-z`, both, or empty for none — and anything else is refused.
| Release zip | SHA-256 (measured 2026-10-03) |
|---|---|
@@ -118,6 +121,58 @@ Read:
- More cores barely help (8 cores: 2.7 s against 2.8–3.0 s), so the default reservation is
the right size.
+### Which setting — measured 2026-10-15
+
+What there is to choose (read 2026-10-15):
+
+| Source | Newest | What it offers |
+|---|---|---|
+| [nihui/rife-ncnn-vulkan](https://github.com/nihui/rife-ncnn-vulkan/releases) | release 20221029, the one above | models up to `rife-v4.6`; `-x`, spatial test-time augmentation (the pair run as its eight flips and transposes, the results averaged); `-z`, temporal (the pair run both ways in time as well); `-u`, a mode for 4K frames |
+| [TNTwise/rife-ncnn-vulkan](https://github.com/TNTwise/rife-ncnn-vulkan/releases) (a fork) | release 20250112 (an 830 MB zip) | adds `rife-v4.25`, `rife-v4.25-lite` and `rife-v4.26` (and `-v4.25-heavy`, `-v4.26-large`, which Practical-RIFE does not list); its README marks `-x` and `-z` "deprecated with rife-v4.25" |
+| [hzwer/Practical-RIFE](https://github.com/hzwer/Practical-RIFE) (the weights) | 4.26 (2024-09-21) and 4.25.lite (2024-10-20); no model since | "recommended to choose 4.25 by default for most scenes" |
+
+Chosen: **`rife-v4.6`, the model above, with `-x -z`**: the pair is run as its eight flips and
+transposes and both ways in time, and the results are averaged, so a frame made from a to b is the
+one made from b to a. The fork's models are not used.
+
+What each setting makes of the synthetic pairs of `tests/video/test_rife.py`: every setting through
+the engine's own `rife.between`, named by `SPRITE_GEN_RIFE_TTA`, read with its own measures
+(`rife.smear`, `rife.ghost`, `interpolation_quality.faults`), on a Radeon Pro 570 (an Apple M4 Max
+gives the same within three percentage points):
+
+| `rife-v4.6` with | legs crossing far (`_walker` 20/−20 and −5/5, t 0.5): outline lost a→b, b→a; ghost | a short step (10/−10 and 4/−4, t 0.5): outline lost, worse way | legs walking through each other (`_legs`): dark added at t 0.25 / 0.5 / 0.75 |
+|---|---|---|---|
+| nothing | 29 %, 24 %; 0.0096 a→b (a ghost) | 3.6 % | −1.0 / −2.0 / −0.9 % |
+| `-x` | 28 %, 25 %; none | **5.3 %** (over the 5 % bar) | −2.6 / −2.3 / +1.4 % |
+| `-z` | 29 %, the same both ways; 0.021 (a ghost) | 4.0 % | −1.4 / −2.6 / +0.4 % |
+| **`-x -z`** | **26 %, the same both ways; none** | **1.7 %** | +1.3 / −2.2 / +2.1 % |
+
+Only `-x -z` makes the frame between legs that cross far the same both ways and leaves no ghost
+there, and it loses the least of a short step's outline: `-x` alone is not symmetric and loses 5.3 %
+of the short step's outline one way, over the 5 % bar, and `-z` alone leaves a ghost band where legs
+cross far. Where the legs cross (t 0.5) none adds dark. Either side, the flips keep the near leg's
+outline whole over the far one — a line each neighbour draws in another place, not the black fill
+2.24 left (6 % of the body at t 0.5, `test_real_rife_between_crossing_legs_adds_no_black`).
+
+Time per frame made (two calls, wall clock, process start included; the CPU seconds, all cores,
+after it), on the walker of those pairs — legs crossing far and the short step, t 0.5 — drawn
+280 × 520, and drawn 520 × 900 on a 960 × 960 frame (the size of a 720p clip's frame):
+
+| `rife-v4.6` with | Mac M4 Max, GPU, 280 × 520 / 960 × 960 | Modal `cpu=2` (`run_job`), 280 × 520 | Modal `cpu=2`, 960 × 960 | Modal default request (`run_align`), 960 × 960 |
+|---|---|---|---|---|
+| nothing | 0.64 / 1.06 s | 2.2–3.7 s (8–24 CPU s) | 4.3–6.2 s (32–46) | 4.6–4.8 s (33–35) |
+| `-x` | 0.70 / 1.29 s | 7.1–15.8 s (59–184) | 22.7–31.4 s (296–436) | 26.3–26.5 s (327–328) |
+| `-z` | 0.65 / 1.08 s | 2.7–5.4 s (17–47) | 7.3–10.3 s (76–111) | 8.0–8.5 s (80–84) |
+| **`-x -z`** | **0.76 / 1.59 s** | **11.7–29.8 s (120–366)** | **44.0–60.5 s (596–874)** | **49.2–50.6 s (635–650)** |
+
+On the Mac's GPU the augmentation adds a tenth of a second a frame at 280 × 520 and half a second at
+960 × 960: the process start is most of a call. On Modal's CPU it is 15 to 19 times the plain call's
+CPU. Each Modal range is two runs, and hosts differ: the same 280 × 520 frame took 11.7 s on one and
+29.8 s on the other. llvmpipe gives the Mac's frame there as before (a mean difference of 0.006 to
+0.76 of 255 a byte, every setting; the outline reading within two percentage points). The first
+frame in a container takes longer (llvmpipe compiles its shaders). One call is stopped at 600 s
+(`rife.CALL_TIMEOUT_SECONDS`) and reported as a RIFE that failed.
+
### Decision
**RIFE runs where the engine runs.** On a Mac that is the Apple GPU. In the app it is the
@@ -134,11 +189,14 @@ unzip -q /tmp/rife.zip -d /opt && ln -s /opt/rife-ncnn-vulkan-20221029-ubuntu/ri
hash and unpack, and adds the check frame; CI installs RIFE that way.
Cost on Modal (prices read from modal.com/pricing on 2026-10-03: CPU $0.0000131 per core per
-second, memory $0.00000222 per GiB per second): one repaired frame is two calls, about 6 s; a
-loop repairs at most three frames, so at most about 20 s of one container — well under a cent.
-Aligning a set's cycles (section 4) makes more frames: about 6 s per frame RIFE makes, so a
-view that needs 20 made frames adds about two minutes on Modal and a few seconds on a Mac.
-That is the reason section 4 keeps every frame that lands on a source frame.
+second, memory $0.00000222 per GiB per second), with the augmentation ("Which setting" above): one
+repaired frame of 280 × 520 is 12 to 30 s and 120 to 370 CPU seconds, a fifth of a cent to half a
+cent; a loop makes at most three, so at most about a minute and a half of one container — under two
+cents. Aligning a set's cycles (section 4) makes more frames, and larger: 44 to 61 s and 600 to 870
+CPU seconds a 960 × 960 frame, about a cent, so a view that needs 20 made frames takes 15 to 20
+minutes. A deployment that aligns on a CPU names a lighter augmentation for that job:
+`SPRITE_GEN_RIFE_TTA=` (none) is 4 to 6 s a 960 × 960 frame, `-z` 7 to 10 s. On a Mac it is under
+two seconds either way. That is the reason section 4 keeps every frame that lands on a source frame.
A PyTorch RIFE was not chosen: it would add a framework of hundreds of megabytes to the image
for the same model, and llvmpipe already gives the GPU's frame.
diff --git a/sprite_gen/video/rife.py b/sprite_gen/video/rife.py
index d22a267..f8fa9dd 100644
--- a/sprite_gen/video/rife.py
+++ b/sprite_gen/video/rife.py
@@ -17,6 +17,8 @@ reading to look at, not a fault (docs/loop-repair.md section 4).
The binary's own CPU path (`-g -1`) returns a wrong frame with rife-v4.6 on both macOS and
Linux (measured 2026-10-03: mean error 39 against 3.3 through Vulkan), so it is never passed;
a machine without a GPU runs the Vulkan path on Mesa's llvmpipe, which gives the GPU's frame.
+Every call asks for the binary's test-time augmentation, spatial and temporal (`-x -z`, `TTA`;
+docs/loop-repair.md section 1, "Which setting"); SPRITE_GEN_RIFE_TTA names another (`tta()`).
The binary is found by SPRITE_GEN_RIFE, then on PATH, then where `sprite-gen rife install`
puts it (`install_root()`, docs/loop-repair.md section 1). A RIFE that cannot be found is
@@ -44,6 +46,13 @@ from sprite_gen._deps import np
BINARY = "rife-ncnn-vulkan"
MODEL = "rife-v4.6"
RELEASE = "20221029"
+# The binary's test-time augmentation, passed on every call: `-x` runs the pair as its eight flips and
+# transposes, `-z` runs it both ways in time as well, and what comes back is averaged — so a frame made
+# from a to b is the one made from b to a (docs/loop-repair.md section 1, "Which setting"). On a machine
+# without a GPU it costs 15 to 19 times the CPU of a plain call. SPRITE_GEN_RIFE_TTA names another
+# (`tta()`): either mode, or none.
+TTA = ("-x", "-z")
+TTA_MODES = ("-x", "-z")
# Coverage RIFE leaves under this is its own blur, not body: dropped so no halo is invented.
ALPHA_FLOOR = 2 / 255
# The colour pushed out around the body is read this far inside its solid edge (a fraction of the
@@ -68,7 +77,10 @@ GHOST_THICK = 5
CROSSFADE_RANGE = 7
CROSSFADE_WINDOW = 0.08
CROSSFADE_KEEP = 0.6
-CALL_TIMEOUT_SECONDS = 120
+# One call past this is stopped and reported as a RIFE that failed. TTA's slowest call measured, on a
+# 960 x 960 frame on Modal's CPU, took about 30 s, and Modal's hosts differ by up to 2.5 times on one frame
+# (2026-10-15, docs/loop-repair.md section 1).
+CALL_TIMEOUT_SECONDS = 600
Interpolate = Callable[[Image.Image, Image.Image, float], Image.Image]
@@ -142,15 +154,32 @@ def locate() -> tuple[Path, Path]:
return binary, model
+def tta() -> tuple[str, ...]:
+ """The test-time augmentation every call asks for: SPRITE_GEN_RIFE_TTA when it is set (`-x`, `-z`
+ or both, space-separated; empty for none), else TTA. Anything else is refused: a flag passed
+ through unread could be the binary's CPU path, which is wrong with this model."""
+ named = os.environ.get("SPRITE_GEN_RIFE_TTA")
+ if named is None:
+ return TTA
+ modes = tuple(named.split())
+ if any(m not in TTA_MODES for m in modes) or len(set(modes)) < len(modes):
+ raise RifeUnavailable(f"SPRITE_GEN_RIFE_TTA={named!r}: name -x, -z or both, space-separated, or leave it empty for none")
+ return modes
+
+
def _call(binary: Path, model: Path, a: Image.Image, b: Image.Image, t: float, tmp: Path) -> Image.Image:
a.save(tmp / "a.png")
b.save(tmp / "b.png")
out = tmp / "o.png"
out.unlink(missing_ok=True)
- proc = subprocess.run(
- [str(binary), "-0", str(tmp / "a.png"), "-1", str(tmp / "b.png"), "-o", str(out), "-s", f"{t:.4f}", "-m", str(model)],
- capture_output=True, text=True, timeout=CALL_TIMEOUT_SECONDS,
- )
+ try:
+ proc = subprocess.run(
+ [str(binary), "-0", str(tmp / "a.png"), "-1", str(tmp / "b.png"), "-o", str(out), "-s", f"{t:.4f}", "-m", str(model), *tta()],
+ capture_output=True, text=True, timeout=CALL_TIMEOUT_SECONDS,
+ )
+ except subprocess.TimeoutExpired as exc:
+ raise RifeUnavailable(f"{binary.name} made no frame in {CALL_TIMEOUT_SECONDS} s and was stopped "
+ f"(augmentation {' '.join(tta()) or 'none'}, SPRITE_GEN_RIFE_TTA)") from exc
if proc.returncode != 0 or not out.is_file():
raise RifeUnavailable(f"{binary.name} failed (exit {proc.returncode}): {(proc.stderr or proc.stdout).strip()[-300:]}")
with Image.open(out) as im:
@@ -315,6 +344,7 @@ class Rife:
if binary is None or model is None:
binary, model = locate()
self.binary, self.model = binary, model
+ self.tta = tta() # refused here, before a frame is asked for
self.made = 0
def __call__(self, a: Image.Image, b: Image.Image, t: float) -> Image.Image:
@@ -324,4 +354,4 @@ class Rife:
return frame
def describe(self) -> dict[str, str]:
- return {"binary": str(self.binary), "model": self.model.name}
+ return {"binary": str(self.binary), "model": self.model.name, "tta": " ".join(self.tta)}
diff --git a/tests/conftest.py b/tests/conftest.py
index a02f6ba..00e3e3b 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -94,6 +94,13 @@ def _fail_unmeasured_skip(report: pytest.TestReport | pytest.CollectReport, node
)
[email protected](autouse=True)
+def _engine_tta(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Every test runs the augmentation the engine ships (`rife.TTA`): a SPRITE_GEN_RIFE_TTA left in the
+ calling shell would change what the real-RIFE tests measure."""
+ monkeypatch.delenv("SPRITE_GEN_RIFE_TTA", raising=False)
+
+
@pytest.hookimpl(wrapper=True)
def pytest_runtest_makereport(item: pytest.Item) -> Generator[None, pytest.TestReport, pytest.TestReport]:
report = yield
diff --git a/tests/video/test_rife.py b/tests/video/test_rife.py
index d449933..c8260fa 100644
--- a/tests/video/test_rife.py
+++ b/tests/video/test_rife.py
@@ -90,6 +90,61 @@ def test_missing_model_is_refused(monkeypatch, tmp_path):
rife.locate()
+def _recording_binary(tmp_path: Path) -> tuple[Path, Path]:
+ """A stand-in binary that logs its arguments and returns its first frame: (binary, log)."""
+ log = tmp_path / "argv.txt"
+ binary = tmp_path / rife.BINARY
+ binary.write_text(f'#!/bin/sh\necho "$@" >> "{log}"\n'
+ 'while [ $# -gt 0 ]; do case "$1" in -0) a="$2"; shift;; -o) o="$2"; shift;; esac; shift; done\n'
+ 'cp "$a" "$o"\n')
+ binary.chmod(binary.stat().st_mode | stat.S_IXUSR)
+ return binary, log
+
+
+def _modes_asked(monkeypatch, tmp_path: Path, named: str | None) -> tuple[list[list[str]], dict[str, str]]:
+ """The augmentation flags of each call one made frame sends, and the interpolator's record."""
+ if named is None:
+ monkeypatch.delenv("SPRITE_GEN_RIFE_TTA", raising=False)
+ else:
+ monkeypatch.setenv("SPRITE_GEN_RIFE_TTA", named)
+ binary, log = _recording_binary(tmp_path)
+ interpolate = rife.Rife(binary, tmp_path / rife.MODEL)
+ interpolate(_disc(40), _disc(72), 0.5)
+ calls = [line.split() for line in log.read_text().splitlines()]
+ return [[a for a in argv if a in ("-x", "-z", "-u", "-g")] for argv in calls], interpolate.describe()
+
+
+def test_every_call_asks_for_both_augmentations_and_never_the_cpu_path(monkeypatch, tmp_path):
+ """The colour run and the coverage run both go out with `-x -z` (docs/loop-repair.md section 1,
+ "Which setting"), and with no `-g`: the binary's own CPU path is wrong with this model."""
+ modes, record = _modes_asked(monkeypatch, tmp_path, None)
+ assert modes == [["-x", "-z"], ["-x", "-z"]] and record["tta"] == "-x -z"
+
+
[email protected]("named, flags", [("", []), ("-x", ["-x"]), ("-z", ["-z"]), (" -z -x ", ["-z", "-x"])])
+def test_sprite_gen_rife_tta_names_another_augmentation_or_none(monkeypatch, tmp_path, named, flags):
+ modes, record = _modes_asked(monkeypatch, tmp_path, named)
+ assert modes == [flags, flags] and record["tta"] == " ".join(flags)
+
+
+def test_a_call_past_its_time_is_a_rife_that_failed(monkeypatch, tmp_path):
+ binary = tmp_path / rife.BINARY
+ binary.write_text("#!/bin/sh\nexec sleep 5\n") # exec: the stopped process is the one holding the pipes
+ binary.chmod(binary.stat().st_mode | stat.S_IXUSR)
+ monkeypatch.setattr(rife, "CALL_TIMEOUT_SECONDS", 0.2)
+ with pytest.raises(rife.RifeUnavailable, match=r"made no frame in 0.2 s .*augmentation -x -z"):
+ rife.Rife(binary, tmp_path / rife.MODEL)(_disc(40), _disc(72), 0.5)
+
+
[email protected]("named", ["-g -1", "x", "-x -x", "-u"])
+def test_sprite_gen_rife_tta_refuses_anything_but_the_two_modes(monkeypatch, tmp_path, named):
+ monkeypatch.setenv("SPRITE_GEN_RIFE_TTA", named)
+ binary, log = _recording_binary(tmp_path)
+ with pytest.raises(rife.RifeUnavailable, match="SPRITE_GEN_RIFE_TTA"):
+ rife.Rife(binary, tmp_path / rife.MODEL)
+ assert not log.exists()
+
+
def _disc(cx: int) -> Image.Image:
im = np.zeros((96, 128, 4), dtype=np.uint8)
yy, xx = np.mgrid[:96, :128]
@@ -113,13 +168,16 @@ def test_real_rife_makes_the_frame_between_in_colour_and_alpha():
@pytest.mark.real_rife
def test_real_rife_between_crossing_legs_adds_no_black():
- """Two outlined legs walk through each other (the near one forward, the far one back): the frame
- between must not be darker inside the body than either neighbour. 2.24 premultiplied the colour
- over black and left 6 % of the body dark at t=0.5 here."""
+ """Two outlined legs walk through each other (the near one forward, the far one back): where they
+ cross (t=0.5) the frame between is no darker inside the body than either neighbour. 2.24
+ premultiplied the colour over black and left 6 % of the body dark there. Either side of the crossing
+ the flips of `-x` keep the near leg's outline whole over the far one, a line each neighbour draws in
+ another place: 1.3 % and 2.1 % of the body at t=0.25 and 0.75, the same on two GPUs — a line, not
+ the black fill."""
interpolate = rife.Rife()
a, b = _legs(36, 70), _legs(60, 46)
- for t in (0.25, 0.5, 0.75):
- assert rife.smear(interpolate(a, b, t), a, b)["dark_excess"] <= 0
+ dark = [rife.smear(interpolate(a, b, t), a, b)["dark_excess"] for t in (0.25, 0.5, 0.75)]
+ assert dark[1] <= 0 and max(dark) < 0.03
def _legs(x_near: int, x_far: int) -> Image.Image:
@@ -205,7 +263,7 @@ def test_outline_loss_reads_a_melted_limb_and_not_a_moved_one():
@pytest.mark.real_rife
def test_real_rife_melts_legs_crossing_too_far_and_alignment_takes_the_nearer_frame_there():
"""Outlined legs that cross a long way between two drawings (a clip drawn on twos) come out of
- RIFE as one shape with no outline where they meet the air (measured 32 % of the edge at t=0.5);
+ RIFE as one shape with no outline where they meet the air (measured 26 % of the edge at t=0.5);
a short step comes out outlined (under 3 % at any t). `--between auto` takes the nearer source
frame for the first and keeps RIFE's for the second; `rife` keeps both and names the first."""
from sprite_gen.video import align
@@ -218,12 +276,13 @@ def test_real_rife_melts_legs_crossing_too_far_and_alignment_takes_the_nearer_fr
out, facts = align.resample(list(far), 4, interpolate) # times 0, 0.5, 1, 1.5: both made at t=0.5
assert facts["between"] == "auto" and facts["made_by_rife"] == 0 and facts["nearest_at"] == [1, 3]
assert out[1] is far[1] and out[3] is far[0]
- # the melt made a to b is left part-covered too, a ghost on its own coverage as well; the one made
- # b to a is not (RIFE is not symmetric); neither is a cross-fade of two drawings (section 4)
- assert [(m["method"], m["faults"], m["look"]) for m in facts["smear"]] == [("nearest", ["outline", "ghost"], []),
+ # the two melts are one frame, made both ways in time (`-z`), and neither is left part-covered: the
+ # augmentation takes away the ghost band the one made a to b carried without it (docs/loop-repair.md
+ # section 1, "Which setting"); neither is a cross-fade of two drawings (section 4)
+ assert [(m["method"], m["faults"], m["look"]) for m in facts["smear"]] == [("nearest", ["outline"], []),
("nearest", ["outline"], [])]
kept, facts = align.resample(list(far), 4, interpolate, between="rife")
- assert facts["made_at"] == [1, 3] and [(m["method"], m["faults"]) for m in facts["smear"]] == [("rife", ["outline", "ghost"]),
+ assert facts["made_at"] == [1, 3] and [(m["method"], m["faults"]) for m in facts["smear"]] == [("rife", ["outline"]),
("rife", ["outline"])]
out, 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"])
@@ -242,5 +301,5 @@ def test_real_rife_repair_rejects_outline_loss_and_keeps_the_original_middle(mon
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 facts["replaced"] == [] and facts["rounds"][0]["faults"] == ["outline"]
assert [f.tobytes() for f in out] == before == [f.tobytes() for f in frames]