The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.
Python
Build scene comparison corpus runner
Sina Atalay47cc235938cf
diff --git a/tests/integration/__init__.py b/tests/integration/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/tests/integration/corpus/__init__.py b/tests/integration/corpus/__init__.pynew file mode 100644index 00000000..5ee0aa69--- /dev/null+++ b/tests/integration/corpus/__init__.py@@ -0,0 +1,4 @@+"""The integration corpus: real Manim CE scenes, each rendered by manimgx and by CE from one+source, compared, and reviewed. See `case` for what a case holds, `python -m+tests.integration.corpus --help` for the tool that renders and reviews, and `test_corpus` for+the three checks."""diff --git a/tests/integration/corpus/__main__.py b/tests/integration/corpus/__main__.pynew file mode 100644index 00000000..6fbddc22--- /dev/null+++ b/tests/integration/corpus/__main__.py@@ -0,0 +1,269 @@+"""The corpus tool: render references, compare them, review them.++ python -m tests.integration.corpus render [CASE…] [--all | --stale] [--engine E] [-j N]+ python -m tests.integration.corpus compare [CASE…] [--all] [-j N]+ python -m tests.integration.corpus status [--list STATE…]+ python -m tests.integration.corpus review CASE VERDICT [--note TEXT]+ python -m tests.integration.corpus settings [--metric M] [--tolerance T]+ python -m tests.integration.corpus diff CASE [--frames N]+ python -m tests.integration.corpus types+ python -m tests.integration.corpus leaks++`render` rewrites a video only when its pixels change, and a `case.json` only when its facts+do: rendering an unchanged corpus changes no file. The review panel+(`python -m tests.integration.review`) does the same by hand.+"""++import argparse+import collections+import json+import shutil+import subprocess+import sys+import tempfile+from collections.abc import Callable+from concurrent.futures import ThreadPoolExecutor, as_completed+from pathlib import Path++import numpy as np+from PIL import Image+from tests.integration.corpus import engines, references, typecheck+from tests.integration.corpus.case import (+ ENGINES,+ METRICS,+ VERDICTS,+ Case,+ Engine,+ Facts,+ Frames,+ Settings,+ State,+ discover,+ save_settings,+ settings,+)+from tests.integration.corpus.frames import decode++DIFFS = Path(__file__).resolve().parents[1] / "_diffs"+STATES: tuple[State, ...] = (*VERDICTS, "stale", "unrendered")+++def _verdict(facts: Facts, current: Settings) -> str:+ reasons = facts.reasons(current)+ worst = (+ f", worst {facts.comparison.worst(current.metric):.1f} {current.metric}"+ if facts.comparison is not None+ else ""+ )+ said = f" ({', '.join(reasons)})" if reasons else ""+ return f"{facts.verdict(current)}{said}{worst}"+++def _select(names: list[str], every: bool, stale: bool = False) -> list[Case]:+ cases = discover()+ if names:+ known = {case.name: case for case in cases}+ unknown = [name for name in names if name not in known]+ if unknown:+ sys.exit(f"unknown case(s): {', '.join(unknown)}")+ return [known[name] for name in names]+ if stale:+ return [case for case in cases if not case.current(case.facts())]+ if every:+ return cases+ sys.exit("name the cases, or pass --all")+++def _parallel(cases: list[Case], jobs: int, work: Callable[[Case], str]) -> int:+ """Run `work` on every case, a line per case as it finishes; how many raised."""+ failures = 0+ with ThreadPoolExecutor(max_workers=jobs) as pool:+ futures = {pool.submit(work, case): case for case in cases}+ for n, future in enumerate(as_completed(futures), 1):+ case = futures[future]+ try:+ line = future.result()+ except Exception as error:+ failures += 1+ line = f"ERROR {type(error).__name__}: {error}"+ print(f"[{n}/{len(cases)}] {case.name}: {line}", flush=True)+ return failures+++def status(listed: list[str]) -> None:+ current = settings()+ names: dict[str, list[str]] = collections.defaultdict(list)+ reasons: collections.Counter[str] = collections.Counter()+ reviewed = 0+ for case in discover():+ standing = case.standing(current)+ names[standing.state].append(case.name)+ reviewed += standing.reviewed+ if standing.facts is not None and standing.state == "not_matching":+ reasons.update(standing.facts.reasons(current))+ trusted = len(names["working"])+ print(f"{sum(map(len, names.values()))} cases, {trusted} trusted (working)")+ print(f"comparison: {current.metric} <= {current.tolerance}; {reviewed} reviewed")+ for state in STATES:+ print(f" {state:13s} {len(names[state]):4d}")+ if reasons:+ print(+ "not matching: " + ", ".join(f"{k} {v}" for k, v in reasons.most_common())+ )+ for state in listed:+ print(f"\n{state}:")+ for name in names.get(state, []):+ print(f" {name}")+++def diff(case: Case, count: int) -> None:+ """Write the most different CE/manimgx pairs side by side, with their difference."""+ facts = case.facts()+ if facts is None or facts.comparison is None:+ sys.exit(f"{case.name}: nothing compared yet")+ column = METRICS.index(settings().metric)+ worst = sorted(facts.comparison.pairs, key=lambda p: -p[2][column])[:count]+ wanted_ce = {i for i, _, _ in worst}+ wanted_mx = {k for _, k, _ in worst}+ ce = {+ i: f+ for i, f in enumerate(decode(case.video("ce"), facts.size))+ if i in wanted_ce+ }+ mx = {+ k: f+ for k, f in enumerate(decode(case.video("manimgx"), facts.size))+ if k in wanted_mx+ }+ out = DIFFS / case.name+ shutil.rmtree(out, ignore_errors=True)+ out.mkdir(parents=True)+ width, height = facts.size+ for i, k, errors in worst:+ d = np.abs(ce[i].astype(np.int16) - mx[k].astype(np.int16)).max(axis=2)+ heat = np.stack([d, d, d], axis=2).clip(0, 255).astype(np.uint8)+ sheet = Image.new("RGB", (width * 3, height))+ for x, frame in enumerate((ce[i], mx[k], heat)):+ sheet.paste(Image.fromarray(frame), (x * width, 0))+ name = f"ce{i:04d}_manimgx{k:04d}_err{errors[column]:.0f}.png"+ sheet.save(out / name)+ print(out / name)+++def leaks(cases: list[Case]) -> None:+ """Render every scene in one process, in order; name those that come out differently from+ their references — the engine carried state over from an earlier scene."""+ with tempfile.TemporaryDirectory() as tmp:+ out = Path(tmp) / "sequence.json"+ subprocess.run(+ [sys.executable, "-m", "tests.integration.corpus.run_manimgx"]+ + [str(case.scene) for case in cases]+ + ["--out", str(out), "--sequence"],+ env=engines.environment(),+ check=True,+ )+ rendered = json.loads(out.read_text(encoding="utf-8"))+ leaked = []+ for case in cases:+ facts = case.facts()+ if facts is None or not isinstance(facts.manimgx, Frames):+ continue+ runs = [(str(h), int(n)) for h, n in rendered[case.name]]+ if runs != list(facts.manimgx.runs):+ leaked.append(case.name)+ print(f"{len(leaked)} of {len(cases)} scenes render differently after others:")+ for name in leaked:+ print(f" {name}")+++def types() -> None:+ cases = discover()+ report = typecheck.report(cases)+ failing = 0+ for case in cases:+ problems = report.problems(case)+ if problems:+ failing += 1+ print(f"{case.name}:")+ for line in problems:+ print(f" {line}")+ print(+ f"\n{failing} of {len(cases)} scenes fail: {len(report.diagnostics)} with ty"+ f" diagnostics, {len(report.escapes)} with escapes, {len(report.imprecise)}"+ " with types manimgx leaves Any/Unknown"+ )+++def main() -> None:+ parser = argparse.ArgumentParser(prog="python -m tests.integration.corpus")+ commands = parser.add_subparsers(dest="command", required=True)+ p = commands.add_parser("render", help="render references, then compare them")+ p.add_argument("cases", nargs="*")+ p.add_argument("--all", action="store_true")+ p.add_argument("--stale", action="store_true", help="unrendered or stale cases")+ p.add_argument("--engine", choices=("manimgx", "ce", "both"), default="both")+ p.add_argument("-j", "--jobs", type=int, default=8)+ p = commands.add_parser("compare", help="compare existing references again")+ p.add_argument("cases", nargs="*")+ p.add_argument("--all", action="store_true")+ p.add_argument("-j", "--jobs", type=int, default=8)+ p = commands.add_parser("status", help="where every case stands")+ p.add_argument("--list", nargs="*", default=[], metavar="STATE")+ p = commands.add_parser("review", help="set a verdict (auto: the comparison's)")+ p.add_argument("case")+ p.add_argument("verdict", choices=("auto", *VERDICTS))+ p.add_argument("--note", default="")+ p = commands.add_parser("settings", help="the comparison's metric and tolerance")+ p.add_argument("--metric", choices=METRICS)+ p.add_argument("--tolerance", type=float)+ p = commands.add_parser("diff", help="write the most different pairs as images")+ p.add_argument("case")+ p.add_argument("--frames", type=int, default=5)+ commands.add_parser("types", help="the type report for every scene")+ commands.add_parser("leaks", help="scenes that render differently after others")+ args = parser.parse_args()++ match args.command:+ case "render":+ wanted: set[Engine] = (+ set(ENGINES) if args.engine == "both" else {args.engine}+ )+ current = settings()++ def work(case: Case) -> str:+ facts, notes = references.render(case, wanted)+ return f"{notes}; {_verdict(facts, current)}"++ cases = _select(args.cases, args.all, args.stale)+ sys.exit(1 if _parallel(cases, args.jobs, work) else 0)+ case "compare":+ cases = _select(args.cases, args.all)+ sys.exit(1 if _parallel(cases, args.jobs, references.recompare) else 0)+ case "status":+ status(args.list)+ case "review":+ (case,) = _select([args.case], every=False)+ verdict = next((v for v in VERDICTS if v == args.verdict), None)+ review = case.write_review(verdict, args.note)+ reviewed = " (reviewed)" if review is not None else ""+ print(f"{case.name}: {case.state(settings())}{reviewed}")+ case "settings":+ current = settings()+ if args.metric is not None or args.tolerance is not None:+ tolerance = (+ current.tolerance if args.tolerance is None else args.tolerance+ )+ current = Settings(args.metric or current.metric, tolerance)+ save_settings(current)+ print(f"{current.metric} <= {current.tolerance}")+ case "diff":+ (case,) = _select([args.case], every=False)+ diff(case, args.frames)+ case "types":+ types()+ case "leaks":+ leaks(discover())+++if __name__ == "__main__":+ main()diff --git a/tests/integration/corpus/case.py b/tests/integration/corpus/case.pynew file mode 100644index 00000000..8d571c66--- /dev/null+++ b/tests/integration/corpus/case.py@@ -0,0 +1,506 @@+"""A case, and everything recorded about it.++A case is a directory under `cases/`:++- `scene.py`: the only source. It is Manim CE's code, and it reaches the engine only through+ `manimgx`'s top level (and its types, `manimgx.typing`): manimgx runs it as written, and CE+ runs the same bytes with `manimgx` resolving to `manim` (`run_ce.py`).+- `manimgx.mkv`, `ce.mkv`: each engine's frames, lossless.+- `case.json`: facts, written by the tool — the source both renders came from, every frame's+ hash (so a change is found without decoding video), and how the two compare, frame by frame,+ in every metric.+- `review.json`: a person's verdict and note, pinned to the hashes they were given for.++A case's state is a verdict — `working`, `not_matching` or `not_working` — or `stale` /+`unrendered` while it has no current renders to judge. The comparison gives a verdict under+the metric and tolerance of `settings.json`: working when, at every manimgx frame's scene time,+the frame CE has on screen is within tolerance of it and the scenes last as long; not_matching+otherwise, or when CE could not render the scene; not_working when manimgx could not. A+person's verdict on exactly these renders overrides it: CE is a reference to look at, not a+definition of correct.+"""++import datetime+import hashlib+import json+from dataclasses import dataclass+from fractions import Fraction+from pathlib import Path+from typing import Literal, cast++ROOT = Path(__file__).resolve().parents[3]+PACKAGE = ROOT / "src" / "manimgx"+CASES = ROOT / "tests" / "integration" / "cases"+SETTINGS = ROOT / "tests" / "integration" / "settings.json"+SIZE = (960, 540)+FPS = 10++type Engine = Literal["manimgx", "ce"]+ENGINES: tuple[Engine, ...] = ("manimgx", "ce")++METRICS: tuple[str, ...] = ("local_max", "mae", "rmse", "max")+"""How a pair of frames is measured (see `compare`); every pair is measured in all of them."""++type Run = tuple[str, int]+"""A frame's hash, and how many frames in a row show it."""++type Stretch = tuple[Fraction, int]+"""Frames 1/fps apart: the scene time of the first, and how many."""++type Verdict = Literal["working", "not_matching", "not_working"]+VERDICTS: tuple[Verdict, ...] = ("working", "not_matching", "not_working")++type State = Literal["working", "not_matching", "not_working", "stale", "unrendered"]+++def seconds(value: Fraction) -> float:+ """A time as JSON holds it."""+ return round(float(value), 9)+++def exact(value: float | str) -> Fraction:+ """A time read back, or a CE duration, as the rational number it stands for."""+ return Fraction(value).limit_denominator(10**6)+++@dataclass(frozen=True, slots=True)+class Settings:+ """The comparison's metric and tolerance (`settings.json`)."""++ metric: str+ tolerance: float+++def settings() -> Settings:+ data = _object(json.loads(SETTINGS.read_text(encoding="utf-8")))+ metric = _str(data["metric"])+ if metric not in METRICS:+ msg = f"unknown metric {metric!r}; one of {METRICS}"+ raise ValueError(msg)+ return Settings(metric=metric, tolerance=_number(data["tolerance"]))+++def save_settings(value: Settings) -> None:+ if value.metric not in METRICS:+ msg = f"unknown metric {value.metric!r}; one of {METRICS}"+ raise ValueError(msg)+ SETTINGS.write_text(+ dump({"metric": value.metric, "tolerance": value.tolerance}), encoding="utf-8"+ )+++@dataclass(frozen=True, slots=True)+class Frames:+ """What one engine drew from one source: its frames, the scene's length, and when each+ frame shows the scene (manimgx's frame k shows k/fps; CE places each play's frames from the+ play's start)."""++ runs: tuple[Run, ...]+ duration: Fraction+ timeline: tuple[Stretch, ...]++ @property+ def count(self) -> int:+ return sum(n for _, n in self.runs)++ def hashes(self) -> list[str]:+ return [h for h, n in self.runs for _ in range(n)]++ def times(self, fps: int) -> list[Fraction]:+ dt = Fraction(1, fps)+ return [start + j * dt for start, n in self.timeline for j in range(n)]++ def identity(self, size: tuple[int, int], fps: int) -> str:+ """One hash for the whole render: what a review is pinned to."""+ payload = json.dumps([list(size), fps, [list(run) for run in self.runs]])+ return "sha256:" + hashlib.sha256(payload.encode()).hexdigest()+++@dataclass(frozen=True, slots=True)+class Failure:+ """An engine could not render the source."""++ error: str+++@dataclass(frozen=True, slots=True)+class Comparison:+ """CE's frames against manimgx's at the same scene times: `pairs` are (the CE frame on+ screen at a manimgx frame's time, that manimgx frame, their difference in each of+ `METRICS`); `unpaired` are the CE frames on screen at no manimgx frame's time."""++ pairs: tuple[tuple[int, int, tuple[float, ...]], ...]+ unpaired: tuple[int, ...]++ def errors(self, metric: str) -> list[float]:+ column = METRICS.index(metric)+ return [errors[column] for _, _, errors in self.pairs]++ def worst(self, metric: str) -> float:+ return max(self.errors(metric), default=0.0)+++@dataclass(frozen=True, slots=True)+class Facts:+ """Everything the tool recorded about a case (`case.json`)."""++ source: str+ size: tuple[int, int]+ fps: int+ manimgx: Frames | Failure+ ce: Frames | Failure+ ce_version: str+ comparison: Comparison | None++ def render(self, engine: Engine) -> Frames | Failure:+ return self.manimgx if engine == "manimgx" else self.ce++ def identity(self, engine: Engine) -> str | None:+ render = self.render(engine)+ return (+ None+ if isinstance(render, Failure)+ else render.identity(self.size, self.fps)+ )++ def reasons(self, settings: Settings) -> tuple[str, ...]:+ """Why the renders are not the same under these settings (none: they are)."""+ if isinstance(self.manimgx, Failure):+ return ("manimgx failed",)+ if isinstance(self.ce, Failure):+ return ("ce failed",)+ if self.comparison is None:+ return ("not compared",)+ found: list[str] = []+ if abs(self.ce.duration - self.manimgx.duration) > 1e-6:+ found.append("duration")+ if self.comparison.worst(settings.metric) > settings.tolerance:+ found.append("pixels")+ return tuple(found)++ def verdict(self, settings: Settings) -> Verdict:+ """The comparison's own verdict."""+ if isinstance(self.manimgx, Failure):+ return "not_working"+ return "not_matching" if self.reasons(settings) else "working"+++@dataclass(frozen=True, slots=True)+class Review:+ """A person's word on a case (`review.json`): a verdict that overrides the comparison's,+ or none (a note alone). The verdict holds only for the source and renders it names.+ """++ verdict: Verdict | None+ note: str+ source: str+ manimgx: str | None+ ce: str | None+ at: str+++@dataclass(frozen=True, slots=True)+class Standing:+ """Where a case stands: its state, what the comparison alone says, and its review."""++ state: State+ auto: State+ review: Review | None+ reviewed: bool # the review's verdict decides the state+ facts: Facts | None+++@dataclass(frozen=True, slots=True)+class Case:+ name: str++ @property+ def dir(self) -> Path:+ return CASES / self.name++ @property+ def scene(self) -> Path:+ return self.dir / "scene.py"++ def video(self, engine: Engine) -> Path:+ return self.dir / f"{engine}.mkv"++ @property+ def facts_path(self) -> Path:+ return self.dir / "case.json"++ @property+ def review_path(self) -> Path:+ return self.dir / "review.json"++ def source_hash(self) -> str:+ return source_hash(self.scene.read_bytes())++ def facts(self) -> Facts | None:+ path = self.facts_path+ return (+ facts_from_json(json.loads(path.read_text(encoding="utf-8")))+ if path.exists()+ else None+ )++ def review(self) -> Review | None:+ path = self.review_path+ return (+ review_from_json(json.loads(path.read_text(encoding="utf-8")))+ if path.exists()+ else None+ )++ def current(self, facts: Facts | None) -> bool:+ """Whether these facts were rendered from today's scene.py, at the corpus's size."""+ return (+ facts is not None+ and facts.source == self.source_hash()+ and (facts.size, facts.fps) == (SIZE, FPS)+ )++ def standing(self, settings: Settings) -> Standing:+ facts, review = self.facts(), self.review()+ if facts is None:+ return Standing("unrendered", "unrendered", review, False, None)+ if not self.current(facts):+ return Standing("stale", "stale", review, False, facts)+ auto: State = facts.verdict(settings)+ if review is not None and review.verdict is not None and pinned(review, facts):+ return Standing(review.verdict, auto, review, True, facts)+ return Standing(auto, auto, review, False, facts)++ def state(self, settings: Settings) -> State:+ return self.standing(settings).state++ def write_facts(self, facts: Facts) -> bool:+ """Record the facts; whether the file changed (equal facts leave it untouched)."""+ text = dump(facts_to_json(facts))+ path = self.facts_path+ if path.exists() and path.read_text(encoding="utf-8") == text:+ return False+ path.write_text(text, encoding="utf-8")+ return True++ def write_review(self, verdict: Verdict | None, note: str) -> Review | None:+ """Record a verdict (None: the comparison's stands) and a note on exactly the current+ source and renders; with neither, the case has no review."""+ facts = self.facts()+ if facts is None or not self.current(facts):+ msg = f"{self.name}: its renders are missing or stale; render it first"+ raise ValueError(msg)+ if verdict is None and not note.strip():+ self.review_path.unlink(missing_ok=True)+ return None+ review = Review(+ verdict=verdict,+ note=note.strip(),+ source=facts.source,+ manimgx=facts.identity("manimgx"),+ ce=facts.identity("ce"),+ at=datetime.date.today().isoformat(),+ )+ self.review_path.write_text(dump(review_to_json(review)), encoding="utf-8")+ return review+++def pinned(review: Review, facts: Facts) -> bool:+ """Whether a review speaks for these renders (it names their source and both renders)."""+ return (review.source, review.manimgx, review.ce) == (+ facts.source,+ facts.identity("manimgx"),+ facts.identity("ce"),+ )+++def source_hash(source: bytes) -> str:+ return "sha256:" + hashlib.sha256(source).hexdigest()+++def discover() -> list[Case]:+ """Every case: each directory under `cases/` holding a `scene.py`."""+ return sorted(+ (Case(p.parent.name) for p in CASES.glob("*/scene.py")), key=lambda c: c.name+ )+++# ── JSON ──────────────────────────────────────────────────────────────────────+# Written by hand so that equal facts are equal bytes, and each frame run is one line.++type Json = bool | int | float | str | list[Json] | dict[str, Json] | None+++def dump(value: Json) -> str:+ return _dump(value, 0) + "\n"+++def _dump(value: Json, depth: int) -> str:+ pad, inner = " " * depth, " " * (depth + 1)+ if isinstance(value, dict):+ if not value:+ return "{}"+ items = [+ f"{inner}{json.dumps(k)}: {_dump(v, depth + 1)}" for k, v in value.items()+ ]+ return "{\n" + ",\n".join(items) + f"\n{pad}}}"+ if isinstance(value, list):+ if all(not isinstance(v, (list, dict)) for v in value):+ return json.dumps(value)+ return (+ "[\n" + ",\n".join(inner + _dump(v, depth + 1) for v in value) + f"\n{pad}]"+ )+ return json.dumps(value)+++def frames_to_json(render: Frames | Failure) -> Json:+ if isinstance(render, Failure):+ return {"error": render.error}+ return {+ "duration": seconds(render.duration),+ "frames": [[h, n] for h, n in render.runs],+ "timeline": [[seconds(start), n] for start, n in render.timeline],+ }+++def facts_to_json(facts: Facts) -> Json:+ comparison: Json = None+ if facts.comparison is not None:+ comparison = {+ "metrics": list(METRICS),+ "pairs": [+ [i, k, *(round(e, 2) for e in errors)]+ for i, k, errors in facts.comparison.pairs+ ],+ "unpaired": list(facts.comparison.unpaired),+ }+ manimgx, ce = frames_to_json(facts.manimgx), frames_to_json(facts.ce)+ for render, engine in ((manimgx, "manimgx"), (ce, "ce")):+ identity = facts.identity(engine)+ if identity is not None and isinstance(render, dict):+ render["id"] = identity+ ce_json = {"manim": facts.ce_version, **ce} if isinstance(ce, dict) else ce+ return {+ "source": facts.source,+ "size": list(facts.size),+ "fps": facts.fps,+ "manimgx": manimgx,+ "ce": ce_json,+ "comparison": comparison,+ }+++def review_to_json(review: Review) -> Json:+ return {+ "verdict": review.verdict,+ "note": review.note,+ "source": review.source,+ "manimgx": review.manimgx,+ "ce": review.ce,+ "at": review.at,+ }+++def _object(value: object) -> dict[str, object]:+ if not isinstance(value, dict):+ msg = f"expected a JSON object, got {value!r}"+ raise TypeError(msg)+ return {str(k): v for k, v in cast("dict[object, object]", value).items()}+++def _list(value: object) -> list[object]:+ if not isinstance(value, list):+ msg = f"expected a JSON array, got {value!r}"+ raise TypeError(msg)+ return list(cast("list[object]", value))+++def _str(value: object) -> str:+ if not isinstance(value, str):+ msg = f"expected a string, got {value!r}"+ raise TypeError(msg)+ return value+++def _int(value: object) -> int:+ if not isinstance(value, int) or isinstance(value, bool):+ msg = f"expected an integer, got {value!r}"+ raise TypeError(msg)+ return value+++def _number(value: object) -> float:+ if isinstance(value, bool) or not isinstance(value, (int, float)):+ msg = f"expected a number, got {value!r}"+ raise TypeError(msg)+ return float(value)+++def _pair(value: object) -> tuple[object, object]:+ items = _list(value)+ if len(items) != 2:+ msg = f"expected a pair, got {value!r}"+ raise TypeError(msg)+ return items[0], items[1]+++def frames_from_json(value: object) -> Frames | Failure:+ data = _object(value)+ if "error" in data:+ return Failure(_str(data["error"]))+ return Frames(+ runs=tuple((_str(h), _int(n)) for h, n in map(_pair, _list(data["frames"]))),+ duration=exact(_number(data["duration"])),+ timeline=tuple(+ (exact(_number(t)), _int(n)) for t, n in map(_pair, _list(data["timeline"]))+ ),+ )+++def comparison_from_json(value: object) -> Comparison | None:+ """The comparison, or None when there is none — or it measured other metrics than+ `METRICS` (then it is measured again)."""+ if value is None:+ return None+ data = _object(value)+ if tuple(_str(m) for m in _list(data.get("metrics", []))) != METRICS:+ return None+ pairs: list[tuple[int, int, tuple[float, ...]]] = []+ for item in _list(data["pairs"]):+ i, k, *errors = _list(item)+ pairs.append((_int(i), _int(k), tuple(_number(e) for e in errors)))+ return Comparison(+ pairs=tuple(pairs), unpaired=tuple(_int(i) for i in _list(data["unpaired"]))+ )+++def facts_from_json(value: object) -> Facts:+ data = _object(value)+ width, height = map(_int, _pair(data["size"]))+ ce = _object(data["ce"])+ return Facts(+ source=_str(data["source"]),+ size=(width, height),+ fps=_int(data["fps"]),+ manimgx=frames_from_json(data["manimgx"]),+ ce=frames_from_json(ce),+ ce_version=_str(ce.get("manim", "")),+ comparison=comparison_from_json(data["comparison"]),+ )+++def review_from_json(value: object) -> Review:+ data = _object(value)+ verdict = data.get("verdict")+ if verdict is not None and verdict not in VERDICTS:+ msg = f"unknown verdict {verdict!r}; one of {VERDICTS} or null"+ raise ValueError(msg)+ manimgx, ce = data.get("manimgx"), data.get("ce")+ return Review(+ verdict=next((v for v in VERDICTS if v == verdict), None),+ note=_str(data.get("note", "")),+ source=_str(data["source"]),+ manimgx=None if manimgx is None else _str(manimgx),+ ce=None if ce is None else _str(ce),+ at=_str(data.get("at", "")),+ )diff --git a/tests/integration/corpus/compare.py b/tests/integration/corpus/compare.pynew file mode 100644index 00000000..089a0aa5--- /dev/null+++ b/tests/integration/corpus/compare.py@@ -0,0 +1,153 @@+"""CE's frames against manimgx's, at the same scene times.++Each manimgx frame (frame k shows the scene at k/fps, exactly) is compared with the frame CE has+on screen at that scene time: CE's latest frame at or before it, since a frame stays up until+the next one. Never by index: CE rounds each play to whole frames (after a 0.75 s play at 10 fps+its frames fall at .75, .85, … while manimgx's stay at .8, .9, …), floors frozen waits, and+never shows a scene's last animation landing, and none of that may count against manimgx.+From the end of CE's scene on, only a CE frame of exactly the same time is compared — the+landed scene, which CE shows only when its float arithmetic gives a play one frame too many —+so manimgx's closing frame is otherwise its own. A CE frame on screen at no manimgx frame's+time (up for less than a frame, or after manimgx's scene ended) is unpaired.++Each pair is measured in every metric (all 0–255), so the metric and tolerance a reviewer picks+(`settings.json`) apply without measuring again:++- `local_max`: the largest mean, over any 7×7 window, of each pixel's largest channel+ difference. A lone wrong pixel fades to 1/49 of itself; a wrong stroke or shape survives —+ edge noise between two rasterizers stays low.+- `mae`: the mean channel difference over the frame.+- `rmse`: its root mean square.+- `max`: the largest channel difference anywhere.++The verdict this feeds only sorts cases for review: CE has bugs of its own, "same" is not+"correct", and a person's review overrides it either way.+"""++from collections.abc import Generator+from dataclasses import dataclass+from fractions import Fraction+from pathlib import Path++import numpy as np+from tests.integration.corpus.case import METRICS, Comparison, Frames+from tests.integration.corpus.frames import Pixels, decode++WINDOW = 7+++def measure(a: Pixels, b: Pixels) -> tuple[float, ...]:+ """The pair's difference in each metric, in the order of `METRICS`."""+ d = np.abs(a.astype(np.int16) - b.astype(np.int16))+ per_pixel = d.max(axis=2).astype(np.float64)+ k = WINDOW+ s = np.zeros((per_pixel.shape[0] + 1, per_pixel.shape[1] + 1))+ s[1:, 1:] = per_pixel.cumsum(axis=0).cumsum(axis=1)+ windows = s[k:, k:] - s[:-k, k:] - s[k:, :-k] + s[:-k, :-k]+ squared = np.square(d, dtype=np.float64)+ found = {+ "local_max": float(windows.max() / (k * k)),+ "mae": float(d.mean()),+ "rmse": float(np.sqrt(squared.mean())),+ "max": float(d.max()),+ }+ return tuple(found[metric] for metric in METRICS)+++def pair(+ ce: Frames, manimgx: Frames, fps: int+) -> tuple[list[tuple[int, int]], list[int]]:+ """(the CE frame on screen at a manimgx frame's scene time, that manimgx frame); and the+ CE frames on screen at none."""+ times = ce.times(fps) # in order: plays follow one another+ pairs: list[tuple[int, int]] = []+ shown = -1 # the CE frame on screen+ for k in range(manimgx.count):+ time = Fraction(k, fps)+ while shown + 1 < len(times) and times[shown + 1] <= time:+ shown += 1+ if shown < 0 or (time >= ce.duration and times[shown] != time):+ continue # nothing yet, or CE's scene is over and it never showed this moment+ pairs.append((shown, k))+ used = {i for i, _ in pairs}+ return pairs, [i for i in range(len(times)) if i not in used]+++def compare(+ ce: Frames,+ manimgx: Frames,+ ce_video: Path,+ manimgx_video: Path,+ size: tuple[int, int],+ fps: int,+) -> Comparison:+ pairs, unpaired = pair(ce, manimgx, fps)+ ce_hashes, mx_hashes = ce.hashes(), manimgx.hashes()+ known: dict[tuple[str, str], tuple[float, ...]] = {} # held frames repeat pairs+ rows: list[tuple[int, int, tuple[float, ...]]] = []+ ce_frames = _Cursor(decode(ce_video, size))+ mx_frames = _Cursor(decode(manimgx_video, size))+ try:+ for i, k in pairs: # both indices only grow: each video is read once+ key = (ce_hashes[i], mx_hashes[k])+ if key not in known:+ known[key] = measure(ce_frames.at(i), mx_frames.at(k))+ rows.append((i, k, known[key]))+ finally:+ ce_frames.close()+ mx_frames.close()+ return Comparison(pairs=tuple(rows), unpaired=tuple(unpaired))+++@dataclass(frozen=True, slots=True)+class Slot:+ """A step of the timeline: a scene time, and the frame each engine has on screen then+ (`ce_time`: the scene time CE's frame shows, which may be up to a frame earlier)."""++ time: Fraction+ ce: int | None+ ce_time: Fraction | None+ manimgx: int | None+++def slots(ce: Frames | None, manimgx: Frames | None, fps: int) -> list[Slot]:+ """The timeline: a slot per manimgx frame, with the CE frame on screen at its time, then+ CE's frames that no manimgx frame is compared with, where their time falls."""+ ce_times = [] if ce is None else ce.times(fps)+ if manimgx is None:+ return [Slot(t, i, t, None) for i, t in enumerate(ce_times)]+ pairs, unpaired = ([], []) if ce is None else pair(ce, manimgx, fps)+ partner = {k: i for i, k in pairs}+ found = [+ Slot(+ Fraction(k, fps),+ partner.get(k),+ None if k not in partner else ce_times[partner[k]],+ k,+ )+ for k in range(manimgx.count)+ ]+ found += [Slot(ce_times[i], i, ce_times[i], None) for i in unpaired]+ return sorted(found, key=lambda s: (s.time, s.manimgx is None))+++class _Cursor:+ """Random access, forward only, into a stream of frames."""++ def __init__(self, frames: Generator[Pixels]) -> None:+ self._frames = frames+ self._index = -1+ self._frame: Pixels | None = None++ def at(self, index: int) -> Pixels:+ if index < self._index:+ msg = f"frame {index} is behind the stream (at {self._index})"+ raise ValueError(msg)+ while self._index < index:+ self._frame = next(self._frames)+ self._index += 1+ assert self._frame is not None+ return self._frame++ def close(self) -> None:+ self._frames.close()diff --git a/tests/integration/corpus/engines.py b/tests/integration/corpus/engines.pynew file mode 100644index 00000000..b3dcf603--- /dev/null+++ b/tests/integration/corpus/engines.py@@ -0,0 +1,90 @@+"""Running an engine on a case: each render in a fresh process of its own, in the case's+directory, with a fixed hash seed — the only way the corpus renders anything."""++import json+import os+import subprocess+import sys+import tempfile+from dataclasses import dataclass+from pathlib import Path++from tests.integration.corpus.case import (+ ROOT,+ Case,+ Engine,+ Failure,+ Frames,+ frames_from_json,+)++TIMEOUT: dict[Engine, float] = {"manimgx": 300, "ce": 900}+++@dataclass(frozen=True, slots=True)+class Result:+ # the hash of the bytes the engine ran (None if it never got that far)+ source: str | None+ frames: Frames | Failure+ # CE's version+ manim: str | None = None+ # manimgx asked for an MP4: the film's own frame count, and the MP4's+ film_frames: int | None = None+ mp4_frames: int | None = None+++def environment() -> dict[str, str]:+ env = dict(os.environ)+ env["PYTHONPATH"] = os.pathsep.join(+ p for p in (str(ROOT), env.get("PYTHONPATH", "")) if p+ )+ env["PYTHONHASHSEED"] = "0"+ env["PYTHONDONTWRITEBYTECODE"] = "1"+ return env+++def run(+ case: Case, engine: Engine, *, video: Path | None = None, mp4: bool = False+) -> Result:+ """Render `case` with `engine`; its frames go to `video` too, if given."""+ with tempfile.TemporaryDirectory() as tmp:+ out = Path(tmp) / "result.json"+ command = [sys.executable, "-m", f"tests.integration.corpus.run_{engine}"]+ command += [str(case.scene), "--out", str(out)]+ if video is not None:+ command += ["--video", str(video)]+ if mp4:+ command.append("--mp4")+ try:+ proc = subprocess.run(+ command,+ cwd=case.dir,+ env=environment(),+ capture_output=True,+ text=True,+ timeout=TIMEOUT[engine],+ check=False,+ )+ except subprocess.TimeoutExpired:+ return Result(None, Failure(f"timed out after {TIMEOUT[engine]:.0f}s"))+ if proc.returncode != 0 or not out.exists():+ return Result(None, Failure(_error(proc.stderr, proc.returncode)))+ data = json.loads(out.read_text(encoding="utf-8"))+ return Result(+ source=str(data["source"]),+ frames=frames_from_json(data["render"]),+ manim=data.get("manim"),+ film_frames=data.get("film_frames"),+ mp4_frames=data.get("mp4_frames"),+ )+++def _error(stderr: str, code: int) -> str:+ """The line that says what went wrong: a traceback's last line, or whatever came last."""+ lines = [line.strip() for line in stderr.splitlines() if line.strip()]+ for line in reversed(lines):+ if not line.startswith(("File ", "^", "~")) and (+ "Error" in line or "Exception" in line+ ):+ return line[:300]+ return (lines[-1] if lines else f"exited with {code}")[:300]diff --git a/tests/integration/corpus/frames.py b/tests/integration/corpus/frames.pynew file mode 100644index 00000000..8725effd--- /dev/null+++ b/tests/integration/corpus/frames.py@@ -0,0 +1,104 @@+"""Frames: their identity (a hash of their pixels) and their storage (lossless video).++A frame is identified by its RGB pixels alone, never by the bytes of a file, so a video is+rewritten only when its pixels change: re-rendering an unchanged scene changes no file.+Videos are x264 in RGB at QP 0 — lossless, and byte-reproducible for a given encoder (one+thread, bit-exact muxing) — written and read with PyAV (FFmpeg's libraries, in its wheel).+"""++import hashlib+from collections.abc import Generator+from fractions import Fraction+from pathlib import Path++import av+import numpy as np+from tests.integration.corpus.case import Run++type Pixels = np.ndarray[tuple[int, int, int], np.dtype[np.uint8]]+"""One frame: height × width × RGB."""+++def frame_hash(rgb: bytes) -> str:+ return hashlib.sha256(rgb).hexdigest()[:16]+++def rgb(pixels: bytes | np.ndarray, size: tuple[int, int]) -> bytes:+ """RGB bytes of a frame given as RGBA (or RGB) rows, top to bottom."""+ width, height = size+ array = np.frombuffer(pixels, np.uint8) if isinstance(pixels, bytes) else pixels+ channels = array.size // (width * height)+ frame = array.reshape(height, width, channels)+ return np.ascontiguousarray(frame[:, :, :3]).tobytes()+++class Recorder:+ """Frames as an engine draws them: their hashes, as runs, and, given a path, a video."""++ def __init__(self, size: tuple[int, int], fps: int, video: Path | None) -> None:+ self.size = size+ self.runs: list[list[str | int]] = []+ self.count = 0+ self._video = None if video is None else _Video(video, size, fps)++ def add(self, frame: bytes, repeat: int = 1) -> None:+ """One drawn frame (RGB bytes), shown `repeat` times."""+ if repeat <= 0:+ return+ h = frame_hash(frame)+ if self.runs and self.runs[-1][0] == h:+ self.runs[-1][1] = int(self.runs[-1][1]) + repeat+ else:+ self.runs.append([h, repeat])+ self.count += repeat+ if self._video is not None:+ self._video.write(frame, repeat)++ def close(self) -> tuple[Run, ...]:+ if self._video is not None:+ self._video.close()+ return tuple((str(h), int(n)) for h, n in self.runs)+++class _Video:+ """Lossless video: x264 in RGB (libx264rgb) at QP 0, its slowest preset, one thread."""++ def __init__(self, path: Path, size: tuple[int, int], fps: int) -> None:+ self.size, self.rate, self.shown = size, Fraction(1, fps), 0+ self.container = av.open(str(path), "w", options={"fflags": "+bitexact"})+ options = {+ "preset": "veryslow",+ "qp": "0",+ "threads": "1",+ "flags": "+bitexact",+ }+ self.stream = self.container.add_stream("libx264rgb", fps, options=options)+ self.stream.width, self.stream.height = size+ self.stream.pix_fmt = "rgb24"++ def write(self, frame: bytes, repeat: int) -> None:+ width, height = self.size+ pixels = np.frombuffer(frame, np.uint8).reshape(height, width, 3)+ picture = av.VideoFrame.from_ndarray(pixels, format="rgb24")+ picture.time_base = self.rate+ for _ in range(repeat):+ picture.pts = self.shown+ self.shown += 1+ self.container.mux(self.stream.encode(picture))++ def close(self) -> None:+ self.container.mux(self.stream.encode(None))+ self.container.close()+++def decode(path: Path, size: tuple[int, int]) -> Generator[Pixels]:+ """Every frame of a video, in order. A reader may stop early; a video that fails to decode+ to its end raises."""+ width, height = size+ with av.open(str(path)) as container:+ for frame in container.decode(video=0):+ if (frame.width, frame.height) != size:+ msg = f"{path}: a frame of {frame.width}x{frame.height}"+ raise RuntimeError(msg)+ pixels = frame.to_ndarray(format="rgb24").astype(np.uint8, copy=False)+ yield pixels.reshape(height, width, 3)diff --git a/tests/integration/corpus/references.py b/tests/integration/corpus/references.pynew file mode 100644index 00000000..e0755850--- /dev/null+++ b/tests/integration/corpus/references.py@@ -0,0 +1,107 @@+"""Making a case's references: render each engine, keep a video only when its pixels change,+compare the two, and record the facts."""++import importlib.metadata+import importlib.util+import shutil+import tempfile+from pathlib import Path++from tests.integration.corpus import compare as comparing+from tests.integration.corpus import engines+from tests.integration.corpus.case import (+ ENGINES,+ FPS,+ SIZE,+ Case,+ Comparison,+ Engine,+ Facts,+ Failure,+ Frames,+)+++def render(case: Case, wanted: set[Engine]) -> tuple[Facts, str]:+ """Render `case` with the wanted engines (both when its source changed), compare, and+ record the facts; them, and what changed."""+ old = case.facts()+ source = case.source_hash()+ if not case.current(old):+ wanted = set(ENGINES)+ renders_ce = "ce" in wanted or old is None or old.render("ce") is None+ if renders_ce and importlib.util.find_spec("manim") is None:+ msg = f"{case.name}: CE's references need Manim CE (`uv sync --group ce`)"+ raise RuntimeError(msg)+ renders: dict[Engine, Frames | Failure] = {}+ notes: list[str] = []+ changed = False+ ce_version = old.ce_version if old is not None else ""+ with tempfile.TemporaryDirectory() as tmp:+ for engine in ENGINES:+ previous = None if old is None else old.render(engine)+ if engine not in wanted and previous is not None:+ renders[engine] = previous+ continue+ fresh = Path(tmp) / f"{engine}.mkv"+ result = engines.run(case, engine, video=fresh)+ if result.source is not None and result.source != source:+ msg = f"{case.name}: scene.py changed while it rendered"+ raise RuntimeError(msg)+ if engine == "ce":+ ce_version = result.manim or importlib.metadata.version("manim")+ renders[engine] = result.frames+ changed |= previous != result.frames+ video = case.video(engine)+ if isinstance(result.frames, Failure):+ video.unlink(missing_ok=True)+ notes.append(f"{engine} failed: {result.frames.error}")+ elif (+ isinstance(previous, Frames)+ and previous.runs == result.frames.runs+ and video.exists()+ ):+ notes.append(f"{engine} unchanged")+ else:+ shutil.move(fresh, video)+ notes.append(f"{engine} {'new' if previous is None else 'changed'}")+ kept = None if old is None or changed else old.comparison+ facts = _facts(case, source, renders["manimgx"], renders["ce"], ce_version, kept)+ case.write_facts(facts)+ return facts, "; ".join(notes)+++def recompare(case: Case) -> str:+ """Compare a case's references again (after the metrics changed)."""+ facts = case.facts()+ if facts is None:+ return "not rendered"+ facts = _facts(+ case, facts.source, facts.manimgx, facts.ce, facts.ce_version, kept=None+ )+ case.write_facts(facts)+ return "compared" if facts.comparison is not None else "nothing to compare"+++def _facts(+ case: Case,+ source: str,+ manimgx: Frames | Failure,+ ce: Frames | Failure,+ ce_version: str,+ kept: Comparison | None,+) -> Facts:+ comparison = None+ if isinstance(manimgx, Frames) and isinstance(ce, Frames):+ comparison = kept or comparing.compare(+ ce, manimgx, case.video("ce"), case.video("manimgx"), SIZE, FPS+ )+ return Facts(+ source=source,+ size=SIZE,+ fps=FPS,+ manimgx=manimgx,+ ce=ce,+ ce_version=ce_version,+ comparison=comparison,+ )diff --git a/tests/integration/corpus/run_ce.py b/tests/integration/corpus/run_ce.pynew file mode 100644index 00000000..71275bb6--- /dev/null+++ b/tests/integration/corpus/run_ce.py@@ -0,0 +1,187 @@+"""Render a scene with Manim CE in this process: the same bytes manimgx runs, with `manimgx`+resolving to `manim`.++ python -m tests.integration.corpus.run_ce SCENE --out RESULT [--video OUT.mkv]++Frames are taken where CE makes them (its renderer's `add_frame`), losslessly, each with the+scene time it shows: a play's frames are 1/fps apart from the play's start, and a frozen wait+repeats one frame. CE's own PNG and MP4 writers are bypassed (a dry run): its PNGs keep one+image per frozen wait and its MP4s are lossy. The run fails if the real manimgx is ever+imported, so a CE render can never be a manimgx render in disguise.+"""++import argparse+import importlib+import importlib.abc+import importlib.machinery+import sys+import tempfile+import types+from collections.abc import Sequence+from fractions import Fraction+from pathlib import Path++from tests.integration.corpus.case import FPS, PACKAGE, SIZE, Frames, exact+from tests.integration.corpus.frames import Recorder, rgb+from tests.integration.corpus.runtime import load, seed, the_scene, write_result++# where CE keeps names that manimgx has at its top level and CE's top level lacks: a scene names+# them as manimgx's (`from manimgx import polylabel`), and CE finds them here+HOMES = (+ "manim.utils.paths",+ "manim.utils.space_ops",+ "manim.utils.unit",+ "manim.utils.polylabel",+ "manim.utils.qhull",+ "manim.utils.rate_functions",+ "manim.animation.transform_matching_parts",+)+++def _from_homes(name: str) -> object:+ """`manim`'s module `__getattr__` (PEP 562): CE's object of that name in `HOMES`."""+ if not name.startswith("_"):+ for home in HOMES:+ module = importlib.import_module(home)+ if hasattr(module, name):+ return getattr(module, name)+ msg = f"module 'manim' has no attribute {name!r}"+ raise AttributeError(msg)+++class ManimgxIsManim(importlib.abc.MetaPathFinder, importlib.abc.Loader):+ """Resolves `manimgx` and `manimgx.X…` to the modules `manim` and `manim.X…` themselves (not+ copies), so a scene's `import manimgx as m` is CE; `manimgx`'s top-level names that CE keeps+ only in `HOMES` resolve there."""++ def __init__(self) -> None:+ self._specs: dict[str, importlib.machinery.ModuleSpec | None] = {}++ def find_spec(+ self,+ fullname: str,+ path: Sequence[str] | None,+ target: types.ModuleType | None = None,+ ) -> importlib.machinery.ModuleSpec | None:+ if fullname == "manimgx" or fullname.startswith("manimgx."):+ # not a package spec: that would give plain manim modules an empty __path__+ return importlib.machinery.ModuleSpec(fullname, self, is_package=False)+ return None++ def create_module(self, spec: importlib.machinery.ModuleSpec) -> types.ModuleType:+ module = importlib.import_module("manim" + spec.name.removeprefix("manimgx"))+ if spec.name == "manimgx":+ vars(module)["__getattr__"] = _from_homes+ self._specs[spec.name] = module.__spec__+ return module++ def exec_module(self, module: types.ModuleType) -> None:+ # the import system gave CE's module the alias's spec; give it its own back+ alias = module.__spec__+ assert alias is not None+ module.__spec__ = self._specs.pop(alias.name)+++def render(scene_path: Path, video: Path | None, media: Path) -> tuple[bytes, Frames]:+ source = scene_path.read_bytes()+ seed()+ sys.meta_path.insert(0, ManimgxIsManim())++ import manim+ import manim.scene.scene+ from manim.animation.animation import Animation+ from manim.mobject.mobject import Mobject, _AnimationBuilder+ from manim.renderer.cairo_renderer import CairoRenderer+ from manim.typing import PixelArray++ config = manim.config+ config.pixel_width, config.pixel_height = SIZE+ config.frame_rate = FPS+ config.media_dir = str(media)+ # what CE still writes (its subtitles) goes to the temporary media directory+ config.output_file = str(media / "scene")+ config.dry_run = True+ config.disable_caching = True+ config.progress_bar = "none"+ config.verbosity = "WARNING"+ config.seed = 0++ recorder = Recorder(SIZE, FPS, video)+ timeline: list[tuple[Fraction, int]] = []++ class Recording(CairoRenderer):+ """CE's renderer, keeping each frame it makes and the scene time the frame shows."""++ clock = Fraction(0) # the scene time at which the next play starts+ playing = False # inside a play+ stretch = False # the play's frames have begun a stretch of the timeline++ def play(+ self,+ scene: manim.Scene,+ *args: Animation | Mobject | _AnimationBuilder,+ **kwargs: object,+ ) -> None:+ start = self.clock+ self.playing, self.stretch = True, False+ try:+ super().play(scene, *args, **kwargs)+ finally:+ self.playing = False+ self.clock = start + exact(scene.duration)++ def add_frame(self, frame: PixelArray, num_frames: int = 1) -> None:+ if self.skip_animations:+ return+ self.time += num_frames / self.camera.frame_rate+ if self.stretch:+ start, count = timeline[-1]+ timeline[-1] = (start, count + num_frames)+ else:+ timeline.append((self.clock, num_frames))+ self.stretch = self.playing+ recorder.add(rgb(frame, SIZE), num_frames)++ def scene_finished(self, scene: manim.Scene) -> None:+ super().scene_finished(scene)+ if recorder.count == 0: # a scene that never plays is its last frame+ timeline.append((self.clock, 1))+ recorder.add(rgb(self.get_frame(), SIZE), 1)++ # CE's Scene makes its renderer by this name, with the camera its class needs+ setattr(manim.scene.scene, "CairoRenderer", Recording) # noqa: B010++ module = load(scene_path, source, f"corpus_scene_{scene_path.parent.name}")+ scene = the_scene(module, manim.Scene)()+ scene.render()+ runs = recorder.close()++ impostors = [+ name+ for name, loaded in sys.modules.items()+ if (file := getattr(loaded, "__file__", None))+ and Path(file).resolve().is_relative_to(PACKAGE)+ ]+ if impostors:+ msg = f"the real manimgx was imported during a CE render: {impostors[:3]}"+ raise RuntimeError(msg)+ renderer = scene.renderer+ assert isinstance(renderer, Recording)+ return source, Frames(runs=runs, duration=renderer.clock, timeline=tuple(timeline))+++def main() -> None:+ parser = argparse.ArgumentParser()+ parser.add_argument("scene", type=Path)+ parser.add_argument("--out", type=Path, required=True)+ parser.add_argument("--video", type=Path)+ args = parser.parse_args()+ with tempfile.TemporaryDirectory() as media:+ source, frames = render(args.scene, args.video, Path(media))+ import manim # imported by `render`, after the random sources were seeded++ write_result(args.out, source, frames, {"manim": manim.__version__})+++if __name__ == "__main__":+ main()diff --git a/tests/integration/corpus/run_manimgx.py b/tests/integration/corpus/run_manimgx.pynew file mode 100644index 00000000..eb874ac5--- /dev/null+++ b/tests/integration/corpus/run_manimgx.py@@ -0,0 +1,106 @@+"""Render scenes with manimgx in this process, reading every frame back from the player.++ python -m tests.integration.corpus.run_manimgx SCENE --out RESULT [--video OUT.mkv] [--mp4]++One scene per process: a scene rendered after another can differ (the engine may leak state+between scenes), so references and checks render each scene alone. `--mp4` also sends the+scene through the product's exporter and counts the frames of the MP4 it writes. `--sequence`+renders several scenes in one process, in order, to find exactly such leaks.+"""++import argparse+import dataclasses+import json+import sys+import tempfile+from fractions import Fraction+from pathlib import Path++import av+from tests.integration.corpus.case import FPS, SIZE, Frames, Json+from tests.integration.corpus.frames import Recorder, rgb+from tests.integration.corpus.runtime import load, seed, the_scene, write_result++import manimgx+from manimgx.config import Config, config+++def render(+ scene_path: Path, video: Path | None, mp4: Path | None+) -> tuple[bytes, Frames, int]:+ """(source, frames, frame count of the film)."""+ source = scene_path.read_bytes()+ seed()+ config.pixel_width, config.pixel_height = SIZE+ config.frame_rate = FPS+ module = load(scene_path, source, f"corpus_scene_{scene_path.parent.name}")+ scene = the_scene(module, manimgx.Scene)()+ recorder = Recorder(SIZE, FPS, video)+ film = scene.render(+ mp4, frames=lambda frame: recorder.add(rgb(frame.pixels(), SIZE), frame.repeat)+ )+ runs = recorder.close()+ frames = Frames(+ runs=runs, duration=scene.clock, timeline=((Fraction(0), recorder.count),)+ )+ return source, frames, film.frame_count+++def mp4_frames(path: Path) -> int:+ """How many frames an MP4 shows at the corpus rate: its samples' durations (a held frame is+ one sample that lasts), every sample decoded."""+ with av.open(str(path)) as container:+ stream = container.streams.video[0]+ durations, decoded = [], 0+ for packet in container.demux(stream):+ if packet.size: # the last packet, empty, drains the decoder+ durations.append(packet.duration or 0)+ decoded += len(packet.decode())+ time_base = stream.time_base+ if decoded != len(durations):+ msg = f"{path}: {decoded} of its {len(durations)} samples decode"+ raise ValueError(msg)+ assert time_base is not None+ shown = time_base * sum(durations) * FPS+ if shown.denominator != 1:+ msg = f"{path} lasts {shown} frames"+ raise ValueError(msg)+ return int(shown)+++def main() -> None:+ parser = argparse.ArgumentParser()+ parser.add_argument("scene", type=Path, nargs="+")+ parser.add_argument("--out", type=Path, required=True)+ parser.add_argument("--video", type=Path)+ parser.add_argument("--mp4", action="store_true")+ parser.add_argument("--sequence", action="store_true")+ args = parser.parse_args()++ if args.sequence:+ # each scene starts from the same config: only the engine's own state may carry over+ defaults = {f.name: getattr(config, f.name) for f in dataclasses.fields(Config)}+ results: dict[str, Json] = {}+ for path in args.scene:+ for name, value in defaults.items():+ setattr(config, name, value)+ _, frames, _ = render(path, None, None)+ results[path.parent.name] = [[h, n] for h, n in frames.runs]+ args.out.write_text(json.dumps(results), encoding="utf-8")+ return++ (scene_path,) = args.scene+ extra: dict[str, Json] = {}+ with tempfile.TemporaryDirectory() as tmp:+ mp4 = Path(tmp) / "product.mp4" if args.mp4 else None+ source, frames, film_frames = render(scene_path, args.video, mp4)+ if mp4 is not None:+ extra = {"film_frames": film_frames, "mp4_frames": mp4_frames(mp4)}+ if "manim" in sys.modules:+ msg = "the scene imported Manim CE; a manimgx render must not"+ raise RuntimeError(msg)+ write_result(args.out, source, frames, extra)+++if __name__ == "__main__":+ main()diff --git a/tests/integration/corpus/runtime.py b/tests/integration/corpus/runtime.pynew file mode 100644index 00000000..7ef766e2--- /dev/null+++ b/tests/integration/corpus/runtime.py@@ -0,0 +1,70 @@+"""What both engine runners share: a deterministic random regime, loading a scene from the exact+bytes that were hashed, and the result file they hand back."""++import json+import random+import sys+import types+from pathlib import Path++import numpy as np+from tests.integration.corpus.case import (+ FPS,+ SIZE,+ Frames,+ Json,+ frames_to_json,+ source_hash,+)++_default_rng = np.random.default_rng+++def _seeded_default_rng(+ seed: int | None = None,+) -> np.random.Generator:+ return _default_rng(0 if seed is None else seed)+++def seed() -> None:+ """Seed every random source a scene or engine may draw from, before the scene is loaded."""+ random.seed(0)+ np.random.seed(0)+ # an unseeded generator (CE's QuickHull makes one) draws from seed 0+ setattr(np.random, "default_rng", _seeded_default_rng) # noqa: B010+++def load(path: Path, source: bytes, name: str) -> types.ModuleType:+ """Execute `source` (the bytes of `path` that were hashed) as a fresh module."""+ module = types.ModuleType(name)+ module.__file__ = str(path)+ sys.modules[name] = module # dataclasses and typing resolve names through it+ exec(compile(source, str(path), "exec"), module.__dict__)+ return module+++def the_scene[T](module: types.ModuleType, base: type[T]) -> type[T]:+ """The one class the module defines that derives from `base`."""+ found = [+ value+ for value in vars(module).values()+ if isinstance(value, type)+ and issubclass(value, base)+ and value.__module__ == module.__name__+ ]+ if len(found) != 1:+ msg = f"expected exactly one scene class, found {len(found)}"+ raise ValueError(msg)+ return found[0]+++def write_result(+ out: Path, source: bytes, frames: Frames, extra: dict[str, Json] | None = None+) -> None:+ result: dict[str, Json] = {+ "source": source_hash(source),+ "size": list(SIZE),+ "fps": FPS,+ "render": frames_to_json(frames),+ }+ out.write_text(json.dumps(result | (extra or {})), encoding="utf-8")diff --git a/tests/integration/corpus/typecheck.py b/tests/integration/corpus/typecheck.pynew file mode 100644index 00000000..a891e871--- /dev/null+++ b/tests/integration/corpus/typecheck.py@@ -0,0 +1,398 @@+"""Whether each scene is statically type safe as written for manimgx — and safe because+manimgx's types are precise, not because they are loose.++Three findings, all shown in full:++- `diagnostics`: `ty` with every rule an error, except `missing-override-decorator` (CE code+ never writes `@override`) and `deprecated` (CE code uses CE's names, some of which+ manimgx deprecates in favor of one of its own).+- `escapes`: ways a scene could quiet the checker — suppression comments, `Any`, `cast`,+ `TYPE_CHECKING`, and dynamic access (`vars`, `getattr` with a literal name, …).+- `imprecise`: expressions whose type manimgx leaves `Any` or `Unknown`. Every call and+ attribute in every scene is wrapped in `reveal_type` and checked in one run; a value counts+ when manimgx produced it — a manimgx function, or a method or attribute of a manimgx class.+ (numpy's and the standard library's own imprecision is theirs.)++`ty` is given the files, never a directory: `[tool.ty.src]` includes only what it names, and+a directory outside it is walked as empty and "passes". Each scene must also show up in the reveal run.+"""++import ast+import io+import re+import subprocess+import sys+import tempfile+import tokenize+from collections import defaultdict+from dataclasses import dataclass, field+from functools import cache+from pathlib import Path++from tests.integration.corpus.case import PACKAGE, ROOT, Case++# every rule an error, but two: CE code overrides without the decorator, and uses CE's+# names that manimgx deprecates (its examples are written with them, on purpose)+STRICT = (+ "--error",+ "all",+ "--ignore",+ "missing-override-decorator",+ "--ignore",+ "deprecated",+)++_DIAGNOSTIC = re.compile(r"^(?P<path>.+?):(?P<line>\d+):(?P<col>\d+): (?P<rest>.*)$")+_REVEAL = re.compile(r"^info\[revealed-type\] Revealed type: `(?P<type>.*)`$")+_SUPPRESSION = re.compile(r"#\s*(?:type|ty|pyright)\s*:\s*ignore")+_IMPRECISE = re.compile(r"\bUnknown\b|\bAny\b|@Todo")+_CALLABLE = re.compile(+ r"^(bound method |Overload\[|def |<class |<module |<bound method |<function"+ r" |type\[)"+)+_TYPING_ESCAPES = frozenset({"Any", "cast", "TYPE_CHECKING"})+_DYNAMIC_CALLS = frozenset({"vars", "globals", "locals", "eval", "exec"})+_NAMED_ACCESS = frozenset({"getattr", "setattr", "delattr"})+++@dataclass(slots=True)+class TypeReport:+ diagnostics: dict[str, list[str]] = field(default_factory=dict)+ escapes: dict[str, list[str]] = field(default_factory=dict)+ imprecise: dict[str, list[str]] = field(default_factory=dict)++ def problems(self, case: Case) -> list[str]:+ sections = (+ ("ty (every rule an error)", self.diagnostics),+ ("escapes from the checker", self.escapes),+ ("types manimgx leaves Any/Unknown", self.imprecise),+ )+ lines: list[str] = []+ for title, found in sections:+ if found.get(case.name):+ lines.append(f"{title}:")+ lines.extend(f" {line}" for line in found[case.name])+ return lines+++def report(cases: list[Case]) -> TypeReport:+ result = TypeReport()+ by_path = {case.scene.resolve(): case for case in cases}+ for path, line, rest in _ty([case.scene for case in cases], STRICT):+ case = by_path.get(path)+ if case is not None:+ result.diagnostics.setdefault(case.name, []).append(f"line {line}: {rest}")+ for case in cases:+ found = escapes(case.scene.read_bytes())+ if found:+ result.escapes[case.name] = found+ result.imprecise = imprecise(cases)+ return result+++def _ty(files: list[Path], flags: tuple[str, ...]) -> list[tuple[Path, int, str]]:+ """(file, line, message) for every diagnostic `ty` reports on exactly these files."""+ if not files:+ return []+ proc = subprocess.run(+ [sys.executable, "-m", "ty", "check", "--output-format", "concise"]+ + ["--no-progress", *flags, *map(str, files)],+ capture_output=True,+ text=True,+ cwd=ROOT,+ check=False,+ )+ if "No python files found" in proc.stdout + proc.stderr:+ msg = "ty checked no files"+ raise RuntimeError(msg)+ if proc.returncode not in (0, 1):+ msg = f"ty failed ({proc.returncode}):\n{proc.stdout}{proc.stderr}"+ raise RuntimeError(msg)+ found: list[tuple[Path, int, str]] = []+ for line in proc.stdout.splitlines():+ match = _DIAGNOSTIC.match(line)+ if match:+ path = (ROOT / match["path"]).resolve()+ found.append((path, int(match["line"]), match["rest"]))+ return found+++def escapes(source: bytes) -> list[str]:+ found: list[str] = []+ for token in tokenize.tokenize(io.BytesIO(source).readline):+ if token.type == tokenize.COMMENT and _SUPPRESSION.search(token.string):+ found.append(f"line {token.start[0]}: {token.string}")+ for node in ast.walk(ast.parse(source)):+ if isinstance(node, ast.ImportFrom) and node.module in {+ "typing",+ "typing_extensions",+ }:+ names = sorted(a.name for a in node.names if a.name in _TYPING_ESCAPES)+ if names:+ found.append(f"line {node.lineno}: imports {', '.join(names)}")+ elif isinstance(node, ast.Attribute) and node.attr in _TYPING_ESCAPES:+ if isinstance(node.value, ast.Name) and node.value.id in {"typing", "t"}:+ found.append(f"line {node.lineno}: uses typing.{node.attr}")+ elif isinstance(node, ast.Call) and isinstance(node.func, ast.Name):+ name = node.func.id+ literal = (+ len(node.args) >= 2+ and isinstance(node.args[1], ast.Constant)+ and isinstance(node.args[1].value, str)+ )+ if name in _DYNAMIC_CALLS or (name in _NAMED_ACCESS and literal):+ found.append(f"line {node.lineno}: {ast.unparse(node)[:80]}")+ return sorted(found, key=lambda s: int(s.split()[1].rstrip(":")))+++# ── precision ─────────────────────────────────────────────────────────────────+++@cache+def _manimgx_methods() -> dict[str, frozenset[str]]:+ """Methods owned by each package class, including those inherited from its bases.++ A revealed short class name alone is not provenance: NetworkX also has a Graph.+ """+ methods: dict[str, set[str]] = defaultdict(set)+ bases: dict[str, set[str]] = defaultdict(set)+ for path in PACKAGE.rglob("*.py"):+ for node in ast.walk(ast.parse(path.read_bytes())):+ if not isinstance(node, ast.ClassDef):+ continue+ methods[node.name].update(+ child.name+ for child in node.body+ if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef))+ )+ for base in node.bases:+ if isinstance(base, ast.Subscript):+ base = base.value+ if isinstance(base, ast.Name):+ bases[node.name].add(base.id)+ elif isinstance(base, ast.Attribute):+ bases[node.name].add(base.attr)+ changed = True+ while changed:+ changed = False+ for name, parents in bases.items():+ before = len(methods[name])+ for parent in parents:+ methods[name].update(methods.get(parent, ()))+ changed |= len(methods[name]) != before+ return {name: frozenset(found) for name, found in methods.items()}+++def _manimgx_names(tree: ast.Module) -> frozenset[str]:+ """The names a scene binds to manimgx: `m` in `import manimgx as m`, and the like."""+ names: set[str] = set()+ for node in ast.walk(tree):+ if isinstance(node, ast.Import):+ for alias in node.names:+ if alias.name.split(".")[0] == "manimgx":+ names.add(alias.asname or "manimgx")+ elif isinstance(node, ast.ImportFrom) and (node.module or "").startswith(+ "manimgx"+ ):+ names.update(alias.asname or alias.name for alias in node.names)+ return frozenset(names)+++class _Reveal(ast.NodeTransformer):+ """Wraps every call and every read attribute in `reveal_type`, remembering what each wrapper+ stands for: the scene's own expression, and its line."""++ def __init__(self) -> None:+ self.site: dict[int, tuple[str, int]] = {} # id(wrapper) -> (expression, line)++ def _wrap(self, node: ast.expr, text: str) -> ast.expr:+ call = ast.copy_location(+ ast.Call(ast.Name("reveal_type", ast.Load()), [node], []), node+ )+ self.site[id(call)] = (text, node.lineno)+ return call++ def visit_Call(self, node: ast.Call) -> ast.expr:+ text = ast.unparse(node)+ self.generic_visit(node)+ return self._wrap(node, text)++ def visit_Attribute(self, node: ast.Attribute) -> ast.expr:+ if not isinstance(node.ctx, ast.Load):+ self.generic_visit(node)+ return node+ text = ast.unparse(node)+ self.generic_visit(node)+ return self._wrap(node, text)++ # annotations, bases and decorators are types, not values+ def visit_FunctionDef(self, node: ast.FunctionDef) -> ast.FunctionDef:+ node.body = [self.visit(s) for s in node.body]+ return node++ def visit_ClassDef(self, node: ast.ClassDef) -> ast.ClassDef:+ node.body = [self.visit(s) for s in node.body]+ return node++ def visit_AnnAssign(self, node: ast.AnnAssign) -> ast.AnnAssign:+ if node.value is not None:+ node.value = self.visit(node.value)+ return node+++def _reveal_calls(tree: ast.AST) -> list[ast.Call]:+ """The `reveal_type` wrappers, in an order that survives unparsing and parsing again."""+ return [+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.Call)+ and isinstance(node.func, ast.Name)+ and node.func.id == "reveal_type"+ ]+++def imprecise(cases: list[Case]) -> dict[str, list[str]]:+ classes = _manimgx_methods()+ found: dict[str, list[str]] = defaultdict(list)+ with tempfile.TemporaryDirectory() as tmp:+ plans: list[tuple[Case, Path, str, list[tuple[str, int]], frozenset[str]]] = []+ for case in cases:+ tree = ast.parse(case.scene.read_bytes())+ bound = _manimgx_names(tree)+ reveal = _Reveal()+ instrumented = reveal.visit(tree)+ sites = [reveal.site[id(w)] for w in _reveal_calls(instrumented)]+ instrumented.body.insert(+ 0, ast.ImportFrom("typing", [ast.alias("reveal_type")], 0)+ )+ text = ast.unparse(ast.fix_missing_locations(instrumented))+ path = Path(tmp) / case.name / "scene.py"+ path.parent.mkdir()+ path.write_text(text, encoding="utf-8")+ plans.append((case, path.resolve(), text, sites, bound))++ revealed = _reveal_positions([path for _, path, _, _, _ in plans])++ for case, path, text, sites, bound in plans:+ lines = text.splitlines()+ wrappers = _reveal_calls(ast.parse(text))+ if len(wrappers) != len(sites):+ msg = f"{case.name}: instrumentation lost track of its sites"+ raise RuntimeError(msg)+ types: dict[int, str] = {}+ for wrapper in wrappers:+ arg = wrapper.args[0]+ column = (+ len(lines[arg.lineno - 1].encode()[: arg.col_offset].decode()) + 1+ )+ type_ = revealed.get((path, arg.lineno, column))+ if type_ is not None:+ types[id(arg)] = type_+ if wrappers and not types:+ msg = f"ty revealed nothing in {case.name}: was it checked?"+ raise RuntimeError(msg)+ for (expression, line), wrapper in zip(sites, wrappers, strict=True):+ type_ = types.get(id(wrapper.args[0]))+ if (+ type_ is None+ or _CALLABLE.match(type_)+ or not _IMPRECISE.search(type_)+ ):+ continue+ producer = _producer(wrapper.args[0], types, classes, bound)+ if producer is not None:+ found[case.name].append(+ f"line {line}: {expression[:70]} is {type_[:70]} (from"+ f" {producer})"+ )+ return dict(found)+++def _reveal_positions(files: list[Path]) -> dict[tuple[Path, int, int], str]:+ """Revealed types by (file, line, column of the revealed expression), from one ty run."""+ proc = subprocess.run(+ [sys.executable, "-m", "ty", "check", "--output-format", "concise"]+ + ["--no-progress", *map(str, files)],+ capture_output=True,+ text=True,+ cwd=ROOT,+ check=False,+ )+ if proc.returncode not in (0, 1):+ msg = f"ty failed ({proc.returncode}):\n{proc.stdout}{proc.stderr}"+ raise RuntimeError(msg)+ revealed: dict[tuple[Path, int, int], str] = {}+ for line in proc.stdout.splitlines():+ match = _DIAGNOSTIC.match(line)+ if match is None:+ continue+ reveal = _REVEAL.match(match["rest"])+ if reveal is not None:+ path = Path(match["path"]).resolve()+ revealed[(path, int(match["line"]), int(match["col"]))] = reveal["type"]+ return revealed+++def _unwrap(node: ast.expr) -> ast.expr:+ while (+ isinstance(node, ast.Call)+ and isinstance(node.func, ast.Name)+ and node.func.id == "reveal_type"+ ):+ node = node.args[0]+ return node+++def _root(node: ast.expr) -> str | None:+ node = _unwrap(node)+ while isinstance(node, (ast.Attribute, ast.Call, ast.Subscript)):+ node = _unwrap(node.func if isinstance(node, ast.Call) else node.value)+ return node.id if isinstance(node, ast.Name) else None+++def _type_of(node: ast.expr, types: dict[int, str]) -> str:+ """The revealed type of an instrumented subexpression, if it was wrapped."""+ if (+ isinstance(node, ast.Call)+ and isinstance(node.func, ast.Name)+ and node.func.id == "reveal_type"+ ):+ return types.get(id(node.args[0]), "")+ return ""+++def _producer(+ node: ast.expr,+ types: dict[int, str],+ classes: dict[str, frozenset[str]],+ bound: frozenset[str],+) -> str | None:+ """Who made this value, if manimgx did: `Class.method()`, `Class.attribute`, `m.name…`."""+ if isinstance(node, ast.Call):+ callee = _type_of(node.func, types)+ method = re.match(r"bound method (\w+)(?:\[.*?\])?\.(\w+)", callee)+ if method:+ if method[2] in classes.get(method[1], ()):+ return f"{method[1]}.{method[2]}()"+ return None+ if _root(node.func) in bound:+ return ast.unparse(_strip(node.func)) + "()"+ elif isinstance(node, ast.Attribute):+ receiver = _type_of(node.value, types)+ head = re.match(r"(\w+)", receiver)+ if head and head[1] in classes:+ return f"{head[1]}.{node.attr}"+ if _root(node) in bound:+ return ast.unparse(_strip(node))+ return None+++def _strip(node: ast.expr) -> ast.expr:+ """The expression without its `reveal_type` wrappers."""++ class Strip(ast.NodeTransformer):+ def visit_Call(self, node: ast.Call) -> ast.expr:+ self.generic_visit(node)+ return _unwrap(node)++ return Strip().visit(ast.parse(ast.unparse(node), mode="eval")).bodydiff --git a/tests/integration/settings.json b/tests/integration/settings.jsonnew file mode 100644index 00000000..b9d056b2--- /dev/null+++ b/tests/integration/settings.json@@ -0,0 +1,4 @@+{+ "metric": "local_max",+ "tolerance": 30.0+}diff --git a/tests/integration/test_corpus.py b/tests/integration/test_corpus.pynew file mode 100644index 00000000..8ff112fd--- /dev/null+++ b/tests/integration/test_corpus.py@@ -0,0 +1,150 @@+"""The corpus's three checks, per case.++1. `test_same_source`: both references were rendered from this exact `scene.py`, which is the+ case's only code and reaches the engine only through `manimgx`'s top level (and its types,+ `manimgx.typing`) — so CE and manimgx ran the same program.+2. `test_types`: the scene is type safe as written for manimgx — `ty` with every rule, no+ escape from the checker, and no value manimgx leaves `Any` or `Unknown`.+3. `test_regression`: the scene renders and the product exports it; today's manimgx holds+ exactly to its stored frames, duration and timeline, regardless of CE's result or the+ case's review status.++This module only checks. `python -m tests.integration.corpus` renders and reviews.+"""++import ast+import tempfile+from pathlib import Path++import pytest+from PIL import Image+from tests.integration.corpus import compare, engines, typecheck+from tests.integration.corpus.case import (+ FPS,+ METRICS,+ SIZE,+ Case,+ Failure,+ Frames,+ discover,+ settings,+)+from tests.integration.corpus.frames import decode++CASES = discover()+IDS = [case.name for case in CASES]+SETTINGS = settings()+DIFFS = Path(__file__).resolve().parent / "_diffs"++[email protected]("case", CASES, ids=IDS)+def test_same_source(case: Case) -> None:+ others = sorted(p.name for p in case.dir.glob("*.py") if p.name != "scene.py")+ assert not others, f"a case has one source, scene.py; it also holds {others}"+ imported = _imported(ast.parse(case.scene.read_bytes()))+ direct = sorted({line for line, name in imported if name.split(".")[0] == "manim"})+ assert not direct, f"imports Manim CE directly (lines {direct}): use manimgx"+ inner = sorted(+ {+ line+ for line, name in imported+ if name.startswith("manimgx.") and name != "manimgx.typing"+ }+ )+ assert not inner, f"imports manimgx's modules (lines {inner}): use its top level"+ facts = case.facts()+ assert facts is not None, f"no references yet: just corpus render {case.name}"+ assert facts.source == case.source_hash(), (+ "scene.py changed since its references were rendered: "+ f"just corpus render {case.name}"+ )+ assert (facts.size, facts.fps) == (SIZE, FPS), "rendered at another size or rate"+ for engine in ("manimgx", "ce"):+ if isinstance(facts.render(engine), Frames):+ assert case.video(engine).exists(), f"{engine}.mkv is missing"+++def _imported(tree: ast.Module) -> list[tuple[int, str]]:+ """Each module a scene imports, with the line that imports it."""+ found: list[tuple[int, str]] = []+ for node in ast.walk(tree):+ if isinstance(node, ast.Import):+ found += [(node.lineno, alias.name) for alias in node.names]+ elif isinstance(node, ast.ImportFrom) and node.module is not None:+ found.append((node.lineno, node.module))+ return found++[email protected](scope="session")+def type_report() -> typecheck.TypeReport:+ return typecheck.report(CASES)++[email protected]("case", CASES, ids=IDS)+def test_types(case: Case, type_report: typecheck.TypeReport) -> None:+ problems = type_report.problems(case)+ if problems:+ pytest.fail("\n".join(problems), pytrace=False)++[email protected]("case", CASES, ids=IDS)+def test_regression(case: Case) -> None:+ result = engines.run(case, "manimgx", mp4=True)+ if isinstance(result.frames, Failure):+ pytest.fail(f"the scene does not render: {result.frames.error}", pytrace=False)+ assert result.mp4_frames == result.film_frames, (+ f"the product's MP4 shows {result.mp4_frames} frames of the film's "+ f"{result.film_frames}"+ )+ facts = case.facts()+ assert facts is not None+ expected = facts.manimgx+ assert isinstance(expected, Frames)+ if result.frames != expected:+ pytest.fail(_explain(case, expected, result.frames), pytrace=False)+++def _explain(case: Case, expected: Frames, fresh: Frames) -> str:+ """What changed in the film (the worst frame pair is written under `_diffs/`)."""+ was, now = expected.hashes(), fresh.hashes()+ changed = [i for i, (a, b) in enumerate(zip(was, now, strict=False)) if a != b]+ lines = [f"{case.name}: today's manimgx differs from its reference"]+ if fresh.duration != expected.duration:+ lines.append(f" duration {fresh.duration}s instead of {expected.duration}s")+ if fresh.timeline != expected.timeline:+ lines.append(f" timeline {fresh.timeline!r} instead of {expected.timeline!r}")+ if len(was) != len(now):+ lines.append(f" {len(now)} frames instead of {len(was)}")+ if changed:+ lines.append(+ f" {len(changed)} frames differ, first {changed[0]}, last {changed[-1]}"+ )+ with tempfile.TemporaryDirectory() as tmp:+ video = Path(tmp) / "fresh.mkv"+ engines.run(case, "manimgx", video=video)+ wanted = set(changed[:200])+ old = {+ i: f+ for i, f in enumerate(decode(case.video("manimgx"), SIZE))+ if i in wanted+ }+ new = {i: f for i, f in enumerate(decode(video, SIZE)) if i in wanted}+ column = METRICS.index(SETTINGS.metric)+ errors = {i: compare.measure(old[i], new[i])[column] for i in sorted(wanted)}+ worst = max(errors, key=lambda i: errors[i])+ lines.append(+ f" largest change {errors[worst]:.1f} ({SETTINGS.metric}) at frame {worst}"+ )+ out = DIFFS / case.name+ out.mkdir(parents=True, exist_ok=True)+ sheet = Image.new("RGB", (SIZE[0] * 2, SIZE[1]))+ sheet.paste(Image.fromarray(old[worst]), (0, 0))+ sheet.paste(Image.fromarray(new[worst]), (SIZE[0], 0))+ sheet.save(out / f"reference_vs_today_{worst:04d}.png")+ lines.append(+ f" reference | today: {out / f'reference_vs_today_{worst:04d}.png'}"+ )+ lines.append(+ f" intended? just corpus render {case.name} (its review then needs renewing)"+ )+ return "\n".join(lines)diff --git a/tests/integration/test_corpus_tools.py b/tests/integration/test_corpus_tools.pynew file mode 100644index 00000000..53a5eb34--- /dev/null+++ b/tests/integration/test_corpus_tools.py@@ -0,0 +1,142 @@+"""The corpus's tools hold to their rules.++- A stored manimgx film is a baseline whatever CE did and however the case was reviewed:+ `test_regression` fails exactly when today's film differs from it (its frames, duration or+ timeline), and never skips; a difference of timing alone is explained without rendering.+- A type report's imprecision is manimgx's: an untyped value from another package is not+ manimgx's output, but manimgx's outputs stay imprecise however untyped their inputs, each+ named by the call or attribute it comes from (a generic class's inherited methods too).+"""++from dataclasses import replace+from fractions import Fraction+from pathlib import Path++import pytest+from tests.integration import test_corpus as corpus+from tests.integration.corpus import case, engines, typecheck+from tests.integration.corpus.case import (+ FPS,+ METRICS,+ SIZE,+ Case,+ Comparison,+ Engine,+ Facts,+ Failure,+ Frames,+)++STORED = Frames((("before", 2),), Fraction(1, 5), ((Fraction(0), 2),))+CHANGES = {+ "same": STORED,+ "pixels": replace(STORED, runs=(("after", 2),)),+ "duration": replace(STORED, duration=Fraction(3, 10)),+ "timeline": replace(STORED, timeline=((Fraction(1, 10), 2),)),+}+++def cases(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ """An empty corpus of the test's own."""+ monkeypatch.setattr(case, "CASES", tmp_path)+ return tmp_path+++def made(name: str, scene: str) -> Case:+ example = Case(name)+ example.dir.mkdir()+ example.scene.write_text(scene, encoding="utf-8")+ return example++[email protected]("cases")[email protected]("ce", ["same", "different", "failure"])[email protected]("change", CHANGES)+def test_a_stored_film_holds_whatever_ce_did(+ ce: str, change: str, monkeypatch: pytest.MonkeyPatch+) -> None:+ example = made("baseline", "import manimgx\n")+ theirs = {"same": STORED, "different": replace(STORED, runs=(("ce", 2),))}+ error = 0.0 if ce == "same" else 255.0+ compared = Comparison(((0, 0, (error,) * len(METRICS)),), ())+ ce_render = theirs.get(ce, Failure("CE cannot render this scene"))+ facts = Facts(example.source_hash(), SIZE, FPS, STORED, ce_render, "", compared)+ example.write_facts(facts)+ assert example.state(corpus.SETTINGS) == (+ "working" if ce == "same" else "not_matching"+ )++ def render(+ _: Case, engine: Engine, *, video: Path | None = None, mp4: bool = False+ ) -> engines.Result:+ assert (engine, video, mp4) == ("manimgx", None, True)+ return engines.Result(+ example.source_hash(), CHANGES[change], film_frames=2, mp4_frames=2+ )++ monkeypatch.setattr(engines, "run", render)+ monkeypatch.setattr(corpus, "_explain", lambda *_: "the stored film changed")+ try:+ if change == "same":+ corpus.test_regression(example)+ else:+ with pytest.raises(pytest.fail.Exception, match="the stored film changed"):+ corpus.test_regression(example)+ except pytest.skip.Exception as skipped:+ pytest.fail(f"a stored baseline cannot be skipped: {skipped}", pytrace=False)++[email protected]("change", ["duration", "timeline"])+def test_a_change_of_timing_alone_is_explained_without_rendering(+ change: str, monkeypatch: pytest.MonkeyPatch+) -> None:+ def render(*_: object, **__: object) -> engines.Result:+ pytest.fail("timing diagnostics should not render or decode unchanged pixels")++ monkeypatch.setattr(engines, "run", render)+ message = corpus._explain(Case("timing"), STORED, CHANGES[change])+ said = {+ "duration": ("3/10s", "1/5s"),+ "timeline": ("Fraction(1, 10)", "Fraction(0, 1)"),+ }+ assert all(part in message for part in (change, "instead of", *said[change]))++[email protected]("cases")+def test_an_untyped_namesake_is_not_manimgxs_output() -> None:+ example = made(+ "external",+ "import manimgx as m\n"+ "import networkx as nx\n"+ "graph = nx.Graph()\n"+ "graph.add_node(0)\n"+ "graph.add_nodes_from([1, 2])\n"+ "graph.add_edge(0, 1)\n"+ "graph.add_edges_from([(1, 2)])\n",+ )+ assert typecheck.imprecise([example]) == {}++[email protected]("cases")+def test_manimgxs_outputs_from_untyped_inputs_are_named_by_their_source() -> None:+ example = made(+ "package",+ "import manimgx as m\n"+ "import networkx as nx\n"+ "def untyped_factory():\n"+ " return m.Dot()\n"+ "m.always_redraw(untyped_factory)\n"+ "graph = m.Graph(list(nx.Graph().nodes), [])\n"+ "graph.copy()\n"+ "m.Graph(list(nx.Graph().nodes), []).vertices\n",+ )+ findings = "\n".join(typecheck.imprecise([example])[example.name])+ for source in ("m.always_redraw()", "m.Graph()", "Graph.copy()", "Graph.vertices"):+ assert f"(from {source})" in findings+++def test_a_generic_class_keeps_its_inherited_methods() -> None:+ methods = typecheck._manimgx_methods()["Graph"]+ assert {"add_vertices", "copy"} <= set(methods)+ assert not {"add_node", "add_nodes_from"} & set(methods)