Skip to content

The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.

Python

Add scene discovery to CLI

Sina Atalay281f6aeadff8
diff --git a/src/manimgx/cli/__init__.py b/src/manimgx/cli/__init__.py
new file mode 100644
index 00000000..ef8a57e8
--- /dev/null
+++ b/src/manimgx/cli/__init__.py
@@ -0,0 +1,83 @@
+"""The manimgx command line: a scene rendered to video, drawn as stills, checked, 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 present scene.py [Scene] its sections as slides, in the browser
+ manimgx preview scene.py [Scene] a window playing it, again on each save
+
+What 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
+wrong. Help is plain text when piped (an agent's shell), rich on a terminal.
+"""
+
+import sys
+
+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")
+if sys.argv[1:2] and sys.argv[1] in DRAWING and not {"-h", "--help"} & set(sys.argv):
+ _engine.start_gpu()
+
+from importlib.metadata import version
+from typing import Annotated
+
+import typer
+
+from manimgx.cli.export import check, present, render, still
+from manimgx.cli.preview import preview
+
+app = typer.Typer(
+ name="manimgx",
+ no_args_is_help=True,
+ add_completion=False,
+ rich_markup_mode="rich" if sys.stdout.isatty() else None,
+ pretty_exceptions_enable=False,
+ context_settings={"help_option_names": ["-h", "--help"]},
+)
+
+
+def _version(shown: bool) -> None:
+ if shown:
+ typer.echo(f"manimgx {version('manimgx')}")
+ raise typer.Exit
+
+
+def manimgx(
+ _: Annotated[
+ bool,
+ typer.Option(
+ "--version",
+ callback=_version,
+ is_eager=True,
+ help="Show the version and exit.",
+ ),
+ ] = False,
+) -> None:
+ """Render Manim Community Edition scenes on a fast GPU engine.
+
+ A scene file is Manim CE code: `import manimgx as m`, a class deriving m.Scene, its
+ `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 render scene.py the video (MP4), with the same report
+
+ Files are written beside the scene file; each command prints what it wrote."""
+
+
+app.command()(render)
+app.command()(still)
+app.command()(check)
+app.command()(preview)
+app.command()(present)
+
+
+def main() -> None:
+ app(prog_name="manimgx")
diff --git a/src/manimgx/cli/scenes.py b/src/manimgx/cli/scenes.py
new file mode 100644
index 00000000..8ff2968c
--- /dev/null
+++ b/src/manimgx/cli/scenes.py
@@ -0,0 +1,311 @@
+"""A command-line scene run: its arguments, source file, format, film and author-facing errors."""
+
+import dataclasses
+import difflib
+import importlib.util
+import os
+import re
+import sys
+import traceback
+from collections.abc import Callable
+from dataclasses import dataclass
+from pathlib import Path
+from types import ModuleType
+from typing import Annotated, Self
+
+import typer
+from rich.console import Console
+
+import manimgx
+from manimgx.animation.timeline import Animation
+from manimgx.config import Config, config
+from manimgx.rendering.film import Film, FrameSink, Play
+from manimgx.scene import Scene
+
+
+@dataclass(frozen=True, slots=True)
+class Size:
+ """A picture's size in pixels."""
+
+ width: int
+ height: int
+
+ def __str__(self) -> str:
+ return f"{self.width}x{self.height}"
+
+
+def size(text: str) -> Size:
+ """`WIDTHxHEIGHT` as a size."""
+ width, _, height = text.lower().partition("x")
+ try:
+ parsed = Size(int(width), int(height))
+ except ValueError:
+ raise typer.BadParameter(
+ f"{text!r} is not WIDTHxHEIGHT, e.g. 1280x720"
+ ) from None
+ if parsed.width <= 0 or parsed.height <= 0 or parsed.width % 2 or parsed.height % 2:
+ raise typer.BadParameter(
+ f"{text!r}: width and height must be even and positive"
+ )
+ return parsed
+
+
+File = Annotated[
+ Path,
+ typer.Argument(
+ metavar="FILE",
+ help="The scene file: a Python file defining manimgx scenes.",
+ show_default=False,
+ ),
+]
+SceneName = Annotated[
+ str | None,
+ typer.Argument(
+ metavar="SCENE",
+ help=(
+ "The scene (a class in the file); needed only if the file defines several."
+ ),
+ show_default=False,
+ ),
+]
+# a scene's format is its own — what its file sets in `config`, else 1920x1080 at 60 fps — unless
+# an option says otherwise
+Resolution = Annotated[
+ Size | None,
+ typer.Option(
+ "--resolution",
+ "-r",
+ parser=size,
+ metavar="WxH",
+ help=(
+ "Pixels, e.g. 1280x720. [default: the scene's config, 1920x1080 unless set]"
+ ),
+ show_default=False,
+ ),
+]
+Fps = Annotated[
+ int | None,
+ typer.Option(
+ min=1,
+ help="Frames per second. [default: the scene's config, 60 unless set]",
+ show_default=False,
+ ),
+]
+
+
+PACKAGE = str(Path(manimgx.__file__).parent)
+
+# names from older Manim (CE before 0.x renames, manimgl) and what manimgx has instead
+RENAMED = {
+ "ShowCreation": "Create",
+ "ShowCreationThenDestruction": "ShowPassingFlash",
+ "ShowCreationThenFadeOut": "ShowPassingFlash",
+ "CircleIndicate": "Circumscribe",
+ "WiggleOutThenIn": "Wiggle",
+ "TextMobject": "Text (plain text) or Tex (text with LaTeX)",
+ "TexText": "Tex",
+ "OldTexText": "Tex",
+ "TexMobject": "MathTex",
+ "OldTex": "MathTex",
+ "FadeInFrom": "FadeIn(mobject, shift=direction)",
+ "FadeInFromDown": "FadeIn(mobject, shift=UP)",
+ "FadeOutAndShift": "FadeOut(mobject, shift=direction)",
+ "FadeInFromLarge": "FadeIn(mobject, scale=factor)",
+ "GraphScene": "a Scene with Axes (axes.plot(f))",
+ "ParametricSurface": "Surface",
+ "ContinualAnimation": "mobject.add_updater(function)",
+}
+
+
+def _names() -> list[str]:
+ return [name for name in dir(manimgx) if not name.startswith("_")]
+
+
+def hints(error: BaseException) -> list[str]:
+ """What to write instead, for the mistakes a scene's author makes in names."""
+ text = str(error)
+ if isinstance(error, AttributeError) and (
+ match := re.search(r"module 'manimgx' has no attribute '(\w+)'", text)
+ ):
+ return [_instead(match.group(1))]
+ if isinstance(error, AttributeError) and error.obj is not None and error.name:
+ close = difflib.get_close_matches(error.name, dir(error.obj), n=3, cutoff=0.6)
+ if close:
+ return [f"did you mean {' or '.join(close)}?"]
+ if isinstance(error, NameError) and error.name:
+ if error.name in _names():
+ return [
+ f"{error.name} is manimgx.{error.name}: `import manimgx as m`, then "
+ f"m.{error.name}"
+ ]
+ if error.name in RENAMED:
+ return [_instead(error.name)]
+ if isinstance(error, ModuleNotFoundError) and error.name in ("manim", "manimlib"):
+ return ["manimgx is the module: `import manimgx as m` (its API is Manim CE's)"]
+ return []
+
+
+def _instead(name: str) -> str:
+ if name in RENAMED:
+ return f"{name} is {RENAMED[name]} in manimgx"
+ close = difflib.get_close_matches(name, _names(), n=3, cutoff=0.6)
+ if close:
+ return f"manimgx has no {name}; did you mean {' or '.join(close)}?"
+ return f"manimgx has no {name}"
+
+
+def report_error(error: BaseException) -> str:
+ """The error as it went through the scene's code: its last frames there (and where manimgx
+ raised it), the error, and hints."""
+ frames = traceback.extract_tb(error.__traceback__)
+ own = [
+ f
+ for f in frames
+ if not f.filename.startswith(PACKAGE)
+ and "/typer/" not in f.filename
+ and not f.filename.startswith("<")
+ ]
+ lines: list[str] = []
+ for f in own[-3:]:
+ lines.append(f"{Path(f.filename).name}:{f.lineno}: in {f.name}")
+ if f.line:
+ lines.append(f" {f.line}")
+ inside = [f for f in frames if f.filename.startswith(PACKAGE)]
+ if inside and frames[-1].filename.startswith(PACKAGE):
+ last = inside[-1]
+ where = Path(last.filename).relative_to(PACKAGE)
+ lines.append(f" (raised in manimgx/{where}:{last.lineno}, in {last.name})")
+ lines.append(f"{type(error).__name__}: {error}")
+ lines += [f"hint: {h}" for h in hints(error)]
+ return "\n".join(lines)
+
+
+class Mistake(Exception):
+ """The command was given wrong; the message says how to give it."""
+
+
+def load(path: Path) -> ModuleType:
+ """Run the file as a module named by its stem, with its directory first on the path (so it
+ imports its neighbours) — not as `__main__`, so its own `if __name__ == "__main__":` block
+ stays put."""
+ defaults = Config()
+ for field in dataclasses.fields(Config):
+ setattr(config, field.name, getattr(defaults, field.name))
+ if not path.is_file():
+ raise Mistake(f"{path}: no such file")
+ 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")
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[path.stem] = module # dataclasses and pickles resolve names through it
+ sys.path.insert(0, str(path.resolve().parent))
+ spec.loader.exec_module(module)
+ return module
+
+
+def scenes(module: ModuleType) -> list[type[Scene]]:
+ """The scenes the module defines, in the order it defines them."""
+ return [
+ value
+ for value in vars(module).values()
+ if isinstance(value, type)
+ and issubclass(value, Scene)
+ and value.__module__ == module.__name__
+ ]
+
+
+def pick(path: Path, module: ModuleType, name: str | None) -> type[Scene]:
+ """The scene `name` names — or, unnamed, the file's only scene."""
+ found = scenes(module)
+ names = [scene.__name__ for scene in found]
+ if name is not None:
+ for scene in found:
+ if scene.__name__ == name:
+ return scene
+ close = difflib.get_close_matches(name, names, n=3)
+ hint = f" Did you mean {' or '.join(close)}?" if close else ""
+ raise Mistake(
+ f"{path} has no scene {name!r}.{hint} Its scenes: {', '.join(names)}"
+ )
+ if len(found) == 1:
+ return found[0]
+ if not found:
+ raise Mistake(f"{path} defines no scene (a subclass of manimgx.Scene)")
+ raise Mistake(
+ f"{path} defines {len(found)} scenes ({', '.join(names)}): name one after the"
+ " file"
+ )
+
+
+@dataclass(frozen=True, slots=True)
+class Format:
+ """The picture a take makes: its size in pixels and frames per second."""
+
+ width: int
+ height: int
+ fps: float
+
+ @classmethod
+ def own(cls, size: Size | None = None, fps: float | None = None) -> Self:
+ """The scene's own format — as its file leaves `config` — unless `size` or `fps` say
+ otherwise."""
+ shape = size or Size(config.pixel_width, config.pixel_height)
+ return cls(shape.width, shape.height, fps or config.frame_rate)
+
+ def __str__(self) -> str:
+ return f"{self.width}x{self.height} at {self.fps:g} fps"
+
+
+def fail(message: str, code: int = 2) -> typer.Exit:
+ """Say what went wrong (on stderr) and end with `code`: 2 the command was wrong, 1 the scene
+ failed."""
+ typer.echo(message, err=True)
+ return typer.Exit(code)
+
+
+def scene(file: Path, name: str | None) -> type[Scene]:
+ """The scene the command names: its file run on manimgx's own config (whatever the file
+ sets there is the scene's, not a take's before it), and it picked."""
+ try:
+ return pick(file, load(file), name)
+ except Mistake as mistake:
+ raise fail(f"error: {mistake}") from None
+ except Exception as error:
+ raise fail(report_error(error), 1) from None
+
+
+type Watch = Callable[[Scene, Play, tuple[Animation, ...]], object]
+"""What a command does when a play ends: the scene (as the play left it), the play, and what it
+played."""
+
+
+def take(
+ kind: type[Scene],
+ look: Format,
+ *,
+ video: str | os.PathLike[str] | None = None,
+ frames: FrameSink | None = None,
+ plays: Watch | None = None,
+) -> tuple[Scene, Film]:
+ """Run the scene at `look`, making its film (and video, frames and plays, as asked). On a
+ terminal, a status line on stderr follows the plays as they end."""
+ config.pixel_width, config.pixel_height = look.width, look.height
+ config.frame_rate = look.fps
+ shown = Console(stderr=True)
+ try:
+ with shown.status(f"{kind.__name__}…", spinner="dots") as status:
+ # after the config: its camera frame follows the picture's shape
+ made = kind()
+
+ def hook(play: Play, did: tuple[Animation, ...]) -> None:
+ if shown.is_terminal:
+ status.update(
+ f"{kind.__name__} t = {float(play.end):.1f} s, play"
+ f" #{play.index}"
+ )
+ if plays is not None:
+ plays(made, play, did)
+
+ return made, made.render(video, frames=frames, plays=hook)
+ except Exception as error:
+ raise fail(report_error(error), 1) from None
diff --git a/src/manimgx/rendering/feed.py b/src/manimgx/rendering/feed.py
index ef2f399e..86b22483 100644
--- a/src/manimgx/rendering/feed.py
+++ b/src/manimgx/rendering/feed.py
@@ -24,6 +24,7 @@ from manimgx.constants import CapStyleType, LineJointType
from manimgx.drawing.geometry import (
IDENTITY,
Blend,
+ Lattice,
Shape,
grid_triangles,
subpath_ranges,
@@ -473,8 +474,8 @@ def view(
def _same_topology(
- a: "tuple[np.ndarray | tuple[int, int], np.ndarray | None] | None",
- b: "tuple[np.ndarray | tuple[int, int], np.ndarray | None] | None",
+ a: "tuple[np.ndarray | Lattice, np.ndarray | None] | None",
+ b: "tuple[np.ndarray | Lattice, np.ndarray | None] | None",
) -> bool:
"""Topology and UV values are immutable; retaining them also retains their identity."""
if a is None or b is None:
@@ -528,7 +529,7 @@ class Feeder:
int,
tuple[
Shape,
- np.ndarray | tuple[int, int],
+ np.ndarray | Lattice,
np.ndarray | None,
int,
int,
@@ -572,7 +573,11 @@ class Feeder:
stale = [k for k, t in self.last_used.items() if t < self.frames - keep]
if not stale:
return
- self.player.evict(stale)
+ # a key whose path draws nothing, or whose upload failed, never reached the player:
+ # it is only forgotten
+ resident = [k for k in stale if self.sizes.get(k, -1) != -1]
+ if resident:
+ self.player.evict(resident)
self.evictions += 1
gone = set(stale)
for key in stale:
@@ -714,13 +719,14 @@ class Feeder:
def mesh(
self,
shape: Shape,
- topology: np.ndarray | tuple[int, int],
+ topology: np.ndarray | Lattice,
uvs: np.ndarray | None,
steps: int = 0,
) -> tuple[int, np.ndarray]:
- """Upload explicit triangles or lower a sample lattice to refined spline cells."""
- grid = topology if isinstance(topology, tuple) else None
- steps = steps if grid is not None else 0
+ """Upload explicit triangles or lower a sample lattice to refined spline cells:
+ the faces it draws, cut from its whole lattice's spline."""
+ lattice = topology if isinstance(topology, Lattice) else None
+ steps = steps if lattice is not None else 0
known = self.mesh_keys.get(id(shape))
if (
known is not None
@@ -737,8 +743,8 @@ class Feeder:
else np.asarray(uvs, dtype=float)
)
form, array, a = shape.affine
- if isinstance(topology, tuple):
- indices = b"grid" + struct.pack("<3I", *topology, steps)
+ if lattice is not None:
+ indices = b"grid" + struct.pack("<5I", *lattice, steps)
else:
tri = np.ascontiguousarray(topology, dtype="<u4")
indices = b"triangles" + tri.tobytes()
@@ -749,9 +755,14 @@ class Feeder:
if key not in self.sizes:
self.last_used[key] = self.frames
block = outline = 0
- if grid is not None:
- g = np.hstack([array, uv]).reshape(grid[0] + 1, grid[1] + 1, -1)
+ if lattice is not None:
+ u, v, first, end = lattice
+ g = np.hstack([array, uv]).reshape(u + 1, v + 1, -1)
points, normals, faces, block = refine_surface(g, steps)
+ drawn = slice(first * block, end * block)
+ per = len(faces) // (u * v) # a face's triangles
+ faces = faces[first * per : end * per] - first * block
+ points, normals = points[drawn], normals[drawn]
array, uv, tri = points[:, :3], points[:, 3:], faces.astype("<u4")
outline = 4 * steps + 1
else:
@@ -772,19 +783,21 @@ class Feeder:
self.sizes[key] = len(array)
return key, a
- def per_vertex(self, rows: np.ndarray, n: int, key: int, faces: int) -> np.ndarray:
- """A mesh's rows, one per vertex the player draws: each lattice cell's paint row
- repeats on every vertex of its refined block. Zero faces means an ordinary mesh.
+ def per_vertex(
+ self, rows: np.ndarray, n: int, key: int, lattice: Lattice | None
+ ) -> np.ndarray:
+ """A mesh's rows, one per vertex the player draws: each drawn lattice cell's paint
+ row repeats on every vertex of its refined block. No lattice: an ordinary mesh's.
"""
- count = faces or n
+ count = n if lattice is None else lattice.u * lattice.v
rows = rows if len(rows) == count else stretch_array(rows, count)
- if not faces:
+ if lattice is None:
return rows
known = self.expanded.get((id(rows), key))
if known is not None and known[0] is rows:
return known[1]
- block = self.sizes[key] // faces
- out = np.repeat(rows, block, axis=0)
+ drawn = rows[lattice.first : lattice.end]
+ out = np.repeat(drawn, self.sizes[key] // max(len(drawn), 1), axis=0)
out.flags.writeable = False
if len(self.expanded) > 1 << 10:
self.expanded.clear()
@@ -1010,7 +1023,9 @@ class Feeder:
return None
terms = (Blend.of(mob.points).terms[0],)
self.materialized += 1
- faces = grid[0] * grid[1] if grid is not None and m > 0 else 0
+ # a surface's lattice, refined (m > 0): its faces are u's steps and own its rows
+ topology = mob._topology if isinstance(mob, MeshMobject) and m > 0 else None
+ lattice = topology if isinstance(topology, Lattice) else None
if isinstance(mob, VMobject):
lo, hi = p.window(g.n // 4)
params = [lo, hi, p.stroke_width * 0.01, p.background_width * 0.01]
@@ -1026,17 +1041,20 @@ class Feeder:
if len(stroke[0]) > 1:
head[3], head[5] = self.rows(stroke[0]), self.rows(stroke[1])
elif isinstance(mob, PMobject):
- params[:2] = np.clip(p.trim, 0.0, 1.0)
- gradient_a[3] = p.stroke_width / 135 # a point's size, in scene units
+ params[:2] = p.window(g.n)
+ # a point's size, in scene units: as wide as a stroke of its width
+ gradient_a[3] = p.stroke_width * 0.01
if len(fill[0]) > 1:
head[2], head[4] = self.rows(fill[0]), self.rows(fill[1])
elif isinstance(mob, MeshMobject):
- params = [*np.clip(p.trim, 0.0, 1.0), p.stroke_width * 0.01, 0.0]
+ steps = len(mob.triangles) // (1 if lattice is None else 2)
+ params = [*p.window(steps), p.stroke_width * 0.01, 0.0]
if (
len(fill[0]) > 1
): # a color per vertex (the player reads a row per vertex)
head[2], head[4] = (
- self.rows(self.per_vertex(f, g.n, keys[0][0], faces)) for f in fill
+ self.rows(self.per_vertex(f, g.n, keys[0][0], lattice))
+ for f in fill
)
if isinstance(p.texture, np.ndarray):
head[6] = self.texture(p.texture)
diff --git a/tests/unit/cli/test_scenes.py b/tests/unit/cli/test_scenes.py
new file mode 100644
index 00000000..49d0db7d
--- /dev/null
+++ b/tests/unit/cli/test_scenes.py
@@ -0,0 +1,36 @@
+"""Each scene-file load starts from shipped settings, then applies the file's own."""
+
+import sys
+from pathlib import Path
+
+import pytest
+
+from manimgx.cli.scenes import load, scene
+from manimgx.config import Config, config
+
+
[email protected]("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
+) -> None:
+ source = tmp_path / "fresh_cli_source.py"
+ source.write_text(
+ "import manimgx as m\n"
+ "m.config.pixel_width = 640\n"
+ "class Only(m.Scene):\n"
+ " pass\n",
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(sys, "path", sys.path.copy())
+ try:
+ for _ in range(2):
+ config.pixel_width, config.pixel_height, config.frame_rate = 320, 180, 12
+ if pick_scene:
+ assert scene(source, None).__name__ == "Only"
+ else:
+ load(source)
+ assert config.pixel_width == 640
+ assert config.pixel_height == Config().pixel_height
+ assert config.frame_rate == Config().frame_rate
+ finally:
+ sys.modules.pop(source.stem, None)