The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.
Python
Inspect current scene sources through one CLI interface
Sina Atalay4501f6795422
diff --git a/src/manimgx/cli/__init__.py b/src/manimgx/cli/__init__.pyindex 741d524c..f75340d4 100644--- a/src/manimgx/cli/__init__.py+++ b/src/manimgx/cli/__init__.py@@ -1,14 +1,13 @@-"""The manimgx command line: a scene rendered to video, drawn as stills, checked, presented,+"""The manimgx command line: a scene rendered to video, inspected, presented,and previewed live.manimgx render scene.py [Scene] [-o video.mp4] the video, a storyboard, layout problems- manimgx still scene.py [Scene] [-t 0,2.5,end] frames at those times, on one sheet- manimgx check scene.py [Scene] timeline, storyboard, layout problems+ manimgx inspect scene.py [Scene] [-t 0,2.5,end] timeline, storyboard, layout problemsmanimgx present scene.py [Scene] its sections as slides, in the browsermanimgx preview scene.py [Scene] a window playing it, again on each saveWhat a command writes goes to stdout, one line per file, then its report; errors go to stderr.-Exit 0 on success, 1 when the scene fails (or `check` finds problems), 2 when the command is+Exit 0 on success, 1 when the scene fails (or `inspect` finds problems), 2 when the command iswrong. Help is plain text when piped (an agent's shell), rich on a terminal."""@@ -19,7 +18,7 @@ from manimgx import _engine# A command that draws starts the GPU before the rest of the command line loads (its modules,# then the scene's file), so that the GPU comes up meanwhile; `--version`, `--help` and# `preview` (its window draws its takes) never bring it up.-DRAWING = ("render", "still", "check", "present")+DRAWING = ("render", "inspect", "present")if sys.argv[1:2] and sys.argv[1] in DRAWING and not {"-h", "--help"} & set(sys.argv):_engine.start_gpu()@@ -28,7 +27,7 @@ from typing import Annotatedimport typer-from manimgx.cli.export import check, present, render, still+from manimgx.cli.export import inspect, present, renderfrom manimgx.cli.preview import previewapp = typer.Typer(@@ -65,16 +64,15 @@ def manimgx(`construct`. Work in a loop:\b- manimgx check scene.py timeline, storyboard, layout problems- manimgx still scene.py -t 1.5,end the frames at 1.5 s and at the end+ manimgx inspect scene.py timeline, storyboard, layout problems+ manimgx inspect scene.py -t 1.5,end inspect specific momentsmanimgx render scene.py the video (MP4), with the same reportFiles are written beside the scene file; each command prints what it wrote."""app.command()(render)-app.command()(still)-app.command()(check)+app.command()(inspect)app.command()(preview)app.command()(present)diff --git a/src/manimgx/cli/diagnostics.py b/src/manimgx/cli/diagnostics.pyindex be1de12e..85620024 100644--- a/src/manimgx/cli/diagnostics.py+++ b/src/manimgx/cli/diagnostics.py@@ -2,6 +2,7 @@import inspectfrom dataclasses import dataclass, field, replace+from fractions import Fractionfrom pathlib import Pathfrom types import FrameType@@ -12,7 +13,6 @@ from manimgx.config import configfrom manimgx.constants import DL, URfrom manimgx.drawing.geometry import subpath_rangesfrom manimgx.mobject import Mobject-from manimgx.rendering.film import Playfrom manimgx.scene import ScenePACKAGE = str(Path(manimgx.__file__).parent)@@ -65,9 +65,10 @@ def written_frame() -> FrameType | None:return frame-def names(- scene: Scene, frame: FrameType | None-) -> tuple[dict[int, str], dict[str, Mobject]]:+type Names = tuple[dict[int, str], dict[str, Mobject]]+++def names(scene: Scene, frame: FrameType | None) -> Names:"""The code's names for the scene's objects — its running variables, then the scene'sattributes, and indices into the groups they name, a few levels deep — and the groups bytheir bare names."""@@ -152,19 +153,22 @@ class View:framed: bool # the camera has moved or zoomed: it frames part of a larger world-def view(scene: Scene) -> View:- """What the viewer sees now — called from inside a play hook: the scene's code (whose- variables name things) is up the stack."""+def view(scene: Scene, known: Names | None = None) -> View:+ """What the viewer sees now. Names from the running code take precedence over `known`,+ which preserves local names after `construct` returns."""(x0, y0), (x1, y1) = (scene.camera.frame.get_corner(c)[:2] for c in (DL, UR))frame = (float(x0), float(y0), float(x1), float(y1))w, h = config.frame_width / 2, config.frame_height / 2framed = max(abs(a - b) for a, b in zip(frame, (-w, -h, w, h), strict=True)) > 1e-3- return View(frame, seen(scene, written_frame()), framed)+ current = names(scene, written_frame())+ if known is not None:+ current = (known[0] | current[0], known[1] | current[1])+ return View(frame, seen(scene, current), framed)-def seen(scene: Scene, frame: FrameType | None) -> list[Thing]:+def seen(scene: Scene, scope: Names) -> list[Thing]:"""What the viewer sees now, in draw order."""- named, bare = names(scene, frame)+ named, bare = scopeorder = {id(leaf): i for i, leaf in enumerate(scene.display_list())}out: list[Thing] = []@@ -281,13 +285,16 @@ TOUCH = 0.03SMALL = 20+type Moment = tuple[Fraction, tuple[str, int] | None] # time and source location++@dataclassclass Problem:kind: str # cut, runs off (a note), overlap, crossing, covered, smallsubject: Thingother: Thing | Nonedetail: str- ends: list[Play] = field(default_factory=list[Play]) # the plays it is seen after+ moments: list[Moment] = field(default_factory=list[Moment])@propertydef note(self) -> bool:@@ -452,7 +459,7 @@ def at(seen: View) -> list[Problem]:class Layout:- """A take's problems as its plays end: each once, with the plays it lasts through; the+ """A take's problems at sampled moments: each once, with the moments it appears in; theproblems (not the notes) numbered from 1 in the order they first appear — as the reportand the storyboard number them."""@@ -460,12 +467,12 @@ class Layout:self.found: dict[tuple[str, str, str | None, str | None], Problem] = {}self.numbers: dict[tuple[str, str, str | None, str | None], int] = {}- def see(self, play: Play, seen: View) -> list[tuple[int, Problem]]:- """The problems at this play's end (as they are now), and their numbers (0: a note)."""+ def see(self, moment: Moment, seen: View) -> list[tuple[int, Problem]]:+ """The problems at this moment, and their numbers (0: a note)."""out = []for problem in at(seen):key = problem.key()- self.found.setdefault(key, problem).ends.append(play)+ self.found.setdefault(key, problem).moments.append(moment)if not problem.note and key not in self.numbers:self.numbers[key] = len(self.numbers) + 1out.append((self.numbers.get(key, 0), problem))@@ -479,20 +486,22 @@ def _label(t: Thing) -> str:return f"{t.name} ({what})" if t.name != t.kind else what-def _when(ends: list[Play]) -> str:- """When a problem is seen: from the end of the play that brought it (and that play's line)."""- first, last = f"{float(ends[0].end):.1f}", f"{float(ends[-1].end):.1f}"+def _when(moments: list[Moment]) -> str:+ """When a problem is seen, and the line that played its first sample."""+ first, last = f"{float(moments[0][0]):g}", f"{float(moments[-1][0]):g}"span = f"t={first}s" if first == last else f"t={first}–{last}s"- where = ends[0].where- return span if where is None else f"{span} (after {Path(where[0]).name}:{where[1]})"+ where = moments[0][1]+ return span if where is None else f"{span} ({Path(where[0]).name}:{where[1]})"def report(layout: Layout, checked: int, similar: int = 3) -> str:"""A line per problem, by number; more than `similar` alike in a row (a label on each offour planets) show the first and fold the rest; then the notes."""found = layout.found+ if not checked:+ return "layout: not checked (no samples)"if not found:- return f"layout: no problems at the end of any of the {checked} plays"+ return f"layout: no problems in {checked} sample{'' if checked == 1 else 's'}"real = sorted((n, found[k]) for k, n in layout.numbers.items())notes = [p for p in found.values() if p.note]head = f"layout: {len(real)} problem{'' if len(real) == 1 else 's'}"@@ -527,4 +536,4 @@ def _alike(a: Problem, b: Problem) -> bool:def _line(p: Problem) -> str:other = "" if p.other is None else f" and {_label(p.other)}"- return f"{_when(p.ends)} {_label(p.subject)}{other}: {p.detail}"+ return f"{_when(p.moments)} {_label(p.subject)}{other}: {p.detail}"diff --git a/src/manimgx/cli/scenes.py b/src/manimgx/cli/scenes.pyindex 60193493..4f1fec2f 100644--- a/src/manimgx/cli/scenes.py+++ b/src/manimgx/cli/scenes.py@@ -3,14 +3,16 @@import dataclassesimport difflibimport importlib.util+import linecacheimport osimport reimport sysimport tracebackfrom collections.abc import Callablefrom dataclasses import dataclass+from importlib.machinery import SourceFileLoaderfrom pathlib import Path-from types import ModuleType+from types import CodeType, ModuleTypefrom typing import Annotated, Selfimport typer@@ -184,6 +186,14 @@ class Mistake(Exception):"""The command was given wrong; the message says how to give it."""+class Source(SourceFileLoader):+ """Current authoring source, with no timestamp-bytecode reuse or cache writes."""++ def get_code(self, fullname: str) -> CodeType:+ linecache.cache.pop(self.path, None)+ return self.source_to_code(self.get_data(self.path), self.path)++def load(path: Path) -> ModuleType:"""Run the file as a module named by its stem, with its directory first on the path (so itimports its neighbours) — not as `__main__`, so its own `if __name__ == "__main__":` block@@ -196,6 +206,7 @@ def load(path: Path) -> ModuleType:spec = importlib.util.spec_from_file_location(path.stem, path)if spec is None or spec.loader is None:raise Mistake(f"{path}: not a Python file")+ spec.loader = Source(path.stem, str(path.resolve()))module = importlib.util.module_from_spec(spec)sys.modules[path.stem] = module # dataclasses and pickles resolve names through itsys.path.insert(0, str(path.resolve().parent))diff --git a/tests/integration/test_inspect.py b/tests/integration/test_inspect.pynew file mode 100644index 00000000..f4b28b05--- /dev/null+++ b/tests/integration/test_inspect.py@@ -0,0 +1,238 @@+"""Inspection uses the video's scene state, with the same checks at default and chosen times."""++from pathlib import Path++import numpy as np+import pytest+from PIL import Image+from typer.testing import CliRunner++from manimgx.cli import app+from manimgx.cli.scenes import scene+from manimgx.cli.storyboard import CAPTION, GAP, tile+from manimgx.rendering.film import Frame+++def source(tmp_path: Path, body: str, base: str = "Scene") -> Path:+ path = tmp_path / "scene.py"+ path.write_text(+ "import manimgx as m\n"+ "m.config.pixel_width, m.config.pixel_height = 320, 180\n"+ "m.config.frame_rate = 10\n"+ f"class Example(m.{base}):\n"+ " def construct(self) -> None:\n"+ + "\n".join(f" {line}" for line in body.splitlines())+ + "\n",+ encoding="utf-8",+ )+ return path+++def test_selected_times_check_the_picture_during_the_animation(tmp_path: Path) -> None:+ path = source(+ tmp_path,+ 'moving = m.Text("moving").shift(4 * m.LEFT)\n'+ 'fixed = m.Text("fixed")\n'+ "self.add(moving, fixed)\n"+ "self.play(moving.animate.shift(8 * m.RIGHT), run_time=2, rate_func=m.linear)",+ )+ runner = CliRunner()+ default = runner.invoke(app, ["inspect", str(path)])+ assert default.exit_code == 0, default.output+ assert "no problems in 1 sample" in default.output+ chosen = runner.invoke(app, ["inspect", str(path), "-t", "1.09"])+ assert chosen.exit_code == 1, chosen.output+ assert "t=1s" in chosen.output # the frame on screen at 1.09 s is frame 10+ assert "moving (Text 'moving')" in chosen.output+ assert "texts overlap" in chosen.output+ assert "scene.py:9" in chosen.output+ with Image.open(tmp_path / "Example.storyboard.png") as image:+ pixels = np.array(image)+ assert ((pixels == [255, 64, 64]).all(axis=-1)).any() # numbered red boxes+++def test_selected_times_stop_after_their_play(tmp_path: Path) -> None:+ path = source(+ tmp_path,+ "self.add(m.Square())\nself.wait(2)\nraise RuntimeError('too far')",+ )+ chosen = CliRunner().invoke(app, ["inspect", str(path), "-t", "0.5"])+ assert chosen.exit_code == 0, chosen.output+ assert "2.00 s, 1 plays" in chosen.output+ ending = CliRunner().invoke(app, ["inspect", str(path), "-t", "end"])+ assert ending.exit_code == 1+ assert "too far" in ending.output+++def test_inspection_stops_when_a_wait_ends_on_the_requested_frame(+ tmp_path: Path,+) -> None:+ path = source(+ tmp_path,+ "self.add(m.Square())\n"+ "self.wait(stop_condition=lambda: True)\n"+ "raise RuntimeError('the frame was already inspected')",+ )+ result = CliRunner().invoke(app, ["inspect", str(path), "-t", "0"])+ assert result.exit_code == 0, result.output+++def test_default_inspection_deduplicates_pictures_but_checks_every_play(+ tmp_path: Path,+) -> None:+ path = source(+ tmp_path, 'self.add(m.Text("tiny", font_size=8))\nself.wait()\nself.wait()'+ )+ result = CliRunner().invoke(app, ["inspect", str(path)])+ assert result.exit_code == 1, result.output+ assert "t=1–2s" in result.output+ assert "#0" in result.output+ assert "#1" in result.output+ with Image.open(tmp_path / "Example.storyboard.png") as image:+ assert image.size == (960, 568)+++def test_the_last_frame_keeps_local_names_and_problem_numbers(tmp_path: Path) -> None:+ path = source(+ tmp_path,+ 'tiny = m.Text("tiny", font_size=8)\nself.add(tiny)\nself.wait()',+ )+ result = CliRunner().invoke(app, ["inspect", str(path), "-t", "end,0.5,1"])+ assert result.exit_code == 1, result.output+ assert "layout: 1 problem" in result.output+ assert "t=0.5–1s" in result.output+ assert "tiny (Text 'tiny')" in result.output+++def test_notes_do_not_fail_inspection(tmp_path: Path) -> None:+ path = source(tmp_path, "self.add(m.Line(10 * m.LEFT, 10 * m.RIGHT))\nself.wait()")+ result = CliRunner().invoke(app, ["inspect", str(path)])+ assert result.exit_code == 0, result.output+ assert "layout: 0 problems, 1 note" in result.output+++def test_end_inspects_changes_after_the_last_play(tmp_path: Path) -> None:+ path = source(+ tmp_path,+ 'tiny = m.Text("tiny", font_size=8)\nself.add(tiny)\nself.wait()\ntiny.scale(5)',+ )+ result = CliRunner().invoke(app, ["inspect", str(path), "-t", "end"])+ assert result.exit_code == 0, result.output+ assert "no problems in 1 sample" in result.output+++def test_explicit_times_keep_held_pictures_and_split_sheets(tmp_path: Path) -> None:+ path = source(tmp_path, "self.add(m.Square())\nself.wait(10)")+ output = tmp_path / "detail.png"+ result = CliRunner().invoke(+ app, ["inspect", str(path), "-t", "1,2,3", "-t", "4,5,6,end", "-o", str(output)]+ )+ assert result.exit_code == 0, result.output+ assert "no problems in 7 samples" in result.output+ with Image.open(output) as image:+ assert image.size == (1928, 1720)+ with Image.open(tmp_path / "detail-2.png") as image:+ assert image.size == (960, 568)++[email protected]("times", [[], ["-t", "end"], ["-t", "0,end"]])+def test_a_scene_without_plays_still_gets_a_picture(+ tmp_path: Path, times: list[str]+) -> None:+ path = source(tmp_path, "self.add(m.Cube())", base="ThreeDScene")+ result = CliRunner().invoke(app, ["inspect", str(path), *times])+ assert result.exit_code == 0, result.output+ assert "layout: not checked (a 3D scene)" in result.output+ assert (tmp_path / "Example.storyboard.png").is_file()++[email protected]("time", ["-1", "nan", "inf", "later", ""])+def test_invalid_times_are_command_errors(tmp_path: Path, time: str) -> None:+ path = source(tmp_path, "self.wait()")+ result = CliRunner().invoke(app, ["inspect", str(path), f"--time={time}"])+ assert result.exit_code == 2, result.output+ assert not list(tmp_path.glob("*.png"))+++def test_a_missing_frame_is_a_scene_error(tmp_path: Path) -> None:+ path = source(tmp_path, "self.wait()")+ result = CliRunner().invoke(app, ["inspect", str(path), "-t", "4"])+ assert result.exit_code == 1, result.output+ assert "there is no frame at 4" in result.output+ assert not list(tmp_path.glob("*.png"))+++def test_the_output_must_be_a_png(tmp_path: Path) -> None:+ path = source(tmp_path, "self.wait()")+ result = CliRunner().invoke(+ app, ["inspect", str(path), "-o", str(tmp_path / "x.jpg")]+ )+ assert result.exit_code == 2, result.output+ assert "*.png" in result.output+ assert not (tmp_path / "x.jpg").exists()+++ ("base", "updating", "custom_emit"),+ [+ ("Scene", False, False),+ ("Scene", True, False),+ ("Scene", True, True),+ ("ThreeDScene", True, False),+ ],+)+def test_sampling_preserves_the_video_with_tweens_holds_and_updaters(+ tmp_path: Path,+ base: str,+ updating: bool,+ custom_emit: bool,+) -> None:+ camera = (+ "self.set_camera_orientation(phi=60 * m.DEGREES, theta=-40 * m.DEGREES)\n"+ "self.begin_ambient_camera_rotation(rate=0.3)\n"+ if base == "ThreeDScene"+ else ""+ )+ shape = "Cube" if base == "ThreeDScene" else "Square"+ path = source(+ tmp_path,+ camera + f"moving = m.{shape}(fill_opacity=1).shift(2 * m.LEFT)\n"+ "self.add(moving)\n"+ + (+ "moving.add_updater(lambda mob: mob.shift(0.01 * m.UP))\n"+ if updating+ else ""+ )+ + "self.play(moving.animate.shift(4 * m.RIGHT), rate_func=m.linear)\n"+ "self.wait(0.25)",+ base=base,+ )+ if custom_emit:+ # With an updater, both takes emit each frame rather than batching the tween.+ with path.open("a", encoding="utf-8") as out:+ out.write(+ " def _emit(self, repeat: int = 1) -> None:\n"+ " for mob in self.mobjects:\n"+ " mob.set_color(m.RED)\n"+ " super()._emit(repeat)\n"+ )++ frames: dict[int, bytes] = {}++ def keep(frame: Frame) -> None:+ pixels = frame.pixels()+ for index in range(frame.index, frame.index + frame.repeat):+ frames[index] = pixels++ normal = scene(path, None)().render(frames=keep)+ result = CliRunner().invoke(app, ["inspect", str(path), "-t", "1.3,0,1,0.5,1.2"])+ assert result.exit_code == 0, result.output+ assert normal.frame_count == 14+ with Image.open(tmp_path / "Example.storyboard.png") as sheet:+ for position, index in enumerate((0, 5, 10, 12, 13)):+ expected = tile(frames[index], 320, 180)+ row, column = divmod(position, 2)+ x = column * (expected.width + GAP)+ y = row * (expected.height + CAPTION + GAP) + CAPTION+ actual = sheet.crop((x, y, x + expected.width, y + expected.height))+ assert actual.tobytes() == expected.tobytes(), f"frame {index}"diff --git a/tests/integration/test_present.py b/tests/integration/test_present.pyindex e36ec4e7..2c6fa7b5 100644--- a/tests/integration/test_present.py+++ b/tests/integration/test_present.py@@ -4,6 +4,7 @@ video, the page and a handout of the pictures the slides end on."""import json+from html.parser import HTMLParserfrom pathlib import Pathimport av@@ -72,6 +73,54 @@ def test_the_pages_help_names_the_key_that_opens_the_presenter_view() -> None:assert "Shift+P: presenter view" in shown+ ("video", "expected"),+ [+ (+ 'https://example.org/talk.mp4?a=1&label="DECK_JSON"',+ 'https://example.org/talk.mp4?a=1&label="DECK_JSON"',+ ),+ (Path("slides/DECK_TITLE & #1.mp4"), "slides/DECK_TITLE%20%26%20%231.mp4"),+ ],+)+def test_the_page_preserves_urls_paths_and_text(+ video: str | Path, expected: str+) -> None:+ class Document(HTMLParser):+ def __init__(self) -> None:+ super().__init__()+ self.tags: list[tuple[str, dict[str, str | None]]] = []+ self.title = ""+ self.in_title = False++ def handle_starttag(+ self, tag: str, attrs: list[tuple[str, str | None]]+ ) -> None:+ self.tags.append((tag, dict(attrs)))+ self.in_title = tag == "title"++ def handle_endtag(self, tag: str) -> None:+ if tag == "title":+ self.in_title = False++ def handle_data(self, data: str) -> None:+ if self.in_title:+ self.title += data++ title = "A & B </title><img> DECK_VIDEO DECK_JSON"+ film = m.Film(take=lambda _: None)+ html = page(film, video, title)+ document = Document()+ document.feed(html)+ assert document.title == title+ assert "img" not in [tag for tag, _ in document.tags]+ assert [+ (attrs["src"], set(attrs)) for tag, attrs in document.tags if tag == "video"+ ] == [(expected, {"id", "src", "preload", "playsinline"})]+ deck = json.loads(html.split("const deck = ", 1)[1].split(";", 1)[0])+ assert deck["frames"] == film.frame_count++def test_present_writes_the_video_the_page_and_a_handout(tmp_path: Path) -> None:scene = tmp_path / "talk.py"scene.write_text(TALK, encoding="utf-8")diff --git a/tests/unit/cli/test_scenes.py b/tests/unit/cli/test_scenes.pyindex 49d0db7d..c1167f99 100644--- a/tests/unit/cli/test_scenes.py+++ b/tests/unit/cli/test_scenes.py@@ -1,14 +1,51 @@"""Each scene-file load starts from shipped settings, then applies the file's own."""+import os+import py_compileimport sysfrom pathlib import Pathimport pytest-from manimgx.cli.scenes import load, scene+from manimgx.cli.scenes import load, report_error, scenefrom manimgx.config import Config, config+def test_scene_edits_are_read_even_when_bytecode_metadata_matches(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ source = tmp_path / "edited_cli_source.py"+ source.write_text("value = 'one'\n", encoding="utf-8")+ stamp = source.stat()+ py_compile.compile(+ str(source), invalidation_mode=py_compile.PycInvalidationMode.TIMESTAMP+ )+ source.write_text("value = 'two'\n", encoding="utf-8")+ os.utime(source, ns=(stamp.st_atime_ns, stamp.st_mtime_ns))+ monkeypatch.setattr(sys, "path", sys.path.copy())+ try:+ assert load(source).value == "two"+ finally:+ sys.modules.pop(source.stem, None)+++def test_scene_errors_show_the_current_source(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ source = tmp_path / "failing_cli_source.py"+ monkeypatch.setattr(sys, "path", sys.path.copy())+ try:+ for value in ("one", "two"):+ line = f"raise ValueError('{value}')"+ source.write_text(line, encoding="utf-8")+ os.utime(source, (1_700_000_000, 1_700_000_000))+ with pytest.raises(ValueError, match=value) as error:+ load(source)+ assert line in report_error(error.value)+ finally:+ sys.modules.pop(source.stem, None)++@pytest.mark.parametrize("pick_scene", [False, True])def test_a_loaded_file_starts_from_defaults_and_sets_its_own_format(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, pick_scene: bool