The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.
Python
Close export and storyboard resources at their owning boundary
Sina Atalay0f1f96ecffea
diff --git a/src/manimgx/cli/export.py b/src/manimgx/cli/export.pyindex df873e19..d3d5e8fc 100644--- a/src/manimgx/cli/export.py+++ b/src/manimgx/cli/export.py@@ -1,19 +1,23 @@-"""Offline scene exports: video, stills, checks and presentations."""+"""Offline scene exports: video, inspections and presentations."""import json-import mathimport os+import reimport timeimport webbrowserfrom fractions import Fraction+from html import escapefrom importlib.resources import filesfrom pathlib import Path-from typing import Annotated+from typing import TYPE_CHECKING, Annotated+from urllib.parse import quoteimport typerfrom PIL import Image+from manimgx.animation import clockfrom manimgx.animation.timeline import Animation+from manimgx.cli.diagnostics import Names, names, written_framefrom manimgx.cli.scenes import (File,Format,@@ -24,11 +28,15 @@ from manimgx.cli.scenes import (scene,take,)-from manimgx.cli.storyboard import PER_SHEET, Sheets, Watch, caption, tile+from manimgx.cli.storyboard import Sheets, Watch, linefrom manimgx.config import configfrom manimgx.rendering.film import Cut, Film, Frame, Play, X264Presetfrom manimgx.scene import Scene+if TYPE_CHECKING:+ from manimgx.animation.transform import Transform+ from manimgx.drawing.geometry import Path as MotionPath+def render(file: File,@@ -56,7 +64,7 @@ def render("""Render a scene to an MP4 video, with its sound.Also writes a storyboard beside the video (the frame at each play's end, layout problems- outlined and numbered) and lists those problems — see `manimgx check` — and, if the+ outlined and numbered) and lists those problems — see `manimgx inspect` — and, if thescene speaks or has subcaptions, its subtitles (.srt)."""kind = scene(file, name)video = output or file.with_name(f"{kind.__name__}.mp4")@@ -65,8 +73,10 @@ def render(look = Format.own(resolution, fps)watch = Watch(Sheets(video.with_name(f"{video.stem}.storyboard.png")))started = time.perf_counter()- made, _ = take(kind, look, video=video, plays=watch, preset=preset, crf=crf)- sheets = watch.close()+ try:+ made, _ = take(kind, look, video=video, plays=watch, preset=preset, crf=crf)+ finally:+ sheets = watch.storyboard.close()took = time.perf_counter() - startedmegabytes = video.stat().st_size / 1e6typer.echo(@@ -82,83 +92,27 @@ def render(typer.echo(watch.report(timeline=False, film=made.film))-def check(- file: File,- name: SceneName = None,- storyboard: Annotated[- Path | None,- typer.Option(- "--storyboard",- "-s",- help=(- "The storyboard (.png). [default: <Scene>.storyboard.png beside the"- " file]"- ),- ),- ] = None,-) -> None:- """Check a scene: timeline, storyboard, layout.-- Runs the scene without video. Prints its timeline (each play: when, the line of code,- what it played) and the layout problems a viewer would see when each play ends: anything- the frame cuts off, texts that overlap, lines through or touching a text, fills over a- text, text too small to read. Writes a storyboard: the frame at each play's end, problems- outlined and numbered. Exits 1 if there are problems (notes, such as a graph leaving the- frame, do not count)."""- kind = scene(file, name)- watch = Watch(- Sheets(storyboard or file.with_name(f"{kind.__name__}.storyboard.png"))- )- # the take a render makes (its frames computed, none drawn): a scene whose updaters count- # frames is the same world here as in its video- made, film = take(kind, Format.own(), plays=watch)- sheets = watch.close()- typer.echo(- f"{file}: {kind.__name__}, {float(made.clock):.2f} s, {len(film.plays)} plays"- )- typer.echo(f"storyboard: {', '.join(str(s) for s in sheets)}")- typer.echo(watch.report(film=film))- if watch.problems():- raise typer.Exit(1)---END = "end"---def moments(given: list[str]) -> list[str]:- """The times asked for, in order, once each: seconds or `end`; `-t 1,2` is `-t 1 -t 2`."""- out: list[str] = []+def moments(given: list[str]) -> set[Fraction | None]:+ """Distinct times in seconds; None means `end`. `-t 1,2` is `-t 1 -t 2`."""+ out: set[Fraction | None] = set()for part in (p.strip() for text in given for p in text.split(",")):if not part:continue- if part != END:- try:- seconds = float(part)- except ValueError:- raise fail(- f"error: {part!r} is not a time: seconds (e.g. 2.5) or 'end'"- ) from None- if not math.isfinite(seconds) or seconds < 0:- raise fail(- f"error: {part!r} is not a time: seconds from the start, or 'end'"- )- part = f"{seconds:g}"- if part not in out:- out.append(part)- return out or [END]+ try:+ moment = None if part == "end" else Fraction(part)+ if moment is not None and moment < 0:+ raise ValueError+ except (ValueError, ZeroDivisionError):+ raise fail(+ f"error: {part!r} is not a time: non-negative seconds or 'end'"+ ) from None+ out.add(moment)+ if given and not out:+ raise fail("error: --time needs seconds from the start, or 'end'")+ return out-def on_screen(plays: list[Play], time: Fraction) -> Play | None:- """The play whose frames show `time`: the last to begin by then (after the last play: it,- as it left the world)."""- shown = None- for play in plays:- if play.start <= time:- shown = play- return shown---def still(+def inspect(file: File,name: SceneName = None,time: Annotated[@@ -171,7 +125,7 @@ def still("Seconds from the start, or 'end'; several: repeat -t or separate with"" commas."),- show_default="end",+ show_default=False,),] = None,output: Annotated[@@ -179,64 +133,91 @@ def still(typer.Option("--output","-o",- help="The sheet (.png). [default: <Scene>.png beside the file]",+ help="The storyboard (.png). [default: <Scene>.storyboard.png beside the file]",),] = None,) -> None:- """Draw the frames on screen at given times, on one sheet (PNG).+ """Inspect a scene: annotated PNGs, timeline and 2D layout checks, without video.++ Samples play and wait endings by default. With -t, inspects the frames a video player+ shows at those times; 'end' is the last frame. Checks for clipped content, overlapping+ text, lines or fills over text, and small labels. 3D scenes get pictures and a timeline;+ layout checks are skipped. Only sampled moments are checked.- The frame at t seconds is the one on screen then (what a video player shows at t); `end` is- the scene's last frame. Each is captioned `#play t=… file:line`: the play on screen and the- line of code that played it. Six to a sheet (more go on `<name>-2.png`, …). Only the- frames asked for are drawn, and the scene runs no further than the play showing the last.+ Pictures are chronological, captioned #play t=… file:line, with problems outlined and+ numbered. Six fit on each sheet (more go on `<name>-2.png`, …). Default sampling omits+ consecutive identical pictures. With -t, only the requested frames are drawn, and the+ scene stops after the last requested frame's play unless 'end' is included.++ Exits 1 for layout problems; notes, such as a graph leaving the frame, do not count."""kind = scene(file, name)wanted = moments(time or [])- target = output or file.with_name(f"{kind.__name__}.png")+ target = output or file.with_name(f"{kind.__name__}.storyboard.png")if target.suffix.lower() != ".png":- raise fail(f"error: {target}: a still is a PNG image; name the output *.png")- look = (- Format.own()- ) # the frames the video shows (drawn at its size, reduced to tiles)- fps = Fraction(look.fps).limit_denominator(1000)- # the frame on screen at t shows time ⌊t·fps⌋ / fps- at = {m: math.floor(float(m) * look.fps + 1e-9) for m in wanted if m != END}- through = Fraction(max(at.values(), default=0)) / fps- drawn: dict[int, Image.Image] = {}- last: list[Frame] = []+ raise fail(+ f"error: {target}: a storyboard is a PNG image; name the output *.png"+ )+ look = Format.own()+ fps = clock.rational(look.fps)+ # The last sample no later than the requested observed instant.+ pending = sorted(+ ((clock.frame_at(t, fps, after=True) - 1, t) for t in wanted if t is not None),+ reverse=True,+ )+ known: Names | None = None+ watch = Watch(Sheets(target))- def keep(frame: Frame) -> None:- span = range(frame.index, frame.index + frame.repeat)- if hits := [k for k in at.values() if k in span and k not in drawn]:- picture = tile(frame.pixels(), look.width, look.height)- drawn.update(dict.fromkeys(hits, picture))- last[:] = [frame]+ class Sampling(Scene):+ """Observe selected frames through the scene's existing evaluation methods."""++ def _emit(self, repeat: int = 1) -> None:+ while pending and pending[-1][0] < self.frame + repeat:+ when = Fraction(pending.pop()[0]) / fps+ watch.see(self, when, known=known)+ super()._emit(repeat)- def enough(_: Scene, play: Play, __: tuple[Animation, ...]) -> None:- if END not in wanted and play.end > through:+ def _pure_tweens(+ self, anim: Animation, alpha: list[float]+ ) -> "tuple[list[tuple[Transform, MotionPath]], set[int]] | None":+ if pending and pending[-1][0] < self.frame + len(alpha):+ return None # this play needs its mutable world at the selected frames+ return super()._pure_tweens(anim, alpha)++ def ended(made: Scene, play: Play, animations: tuple[Animation, ...]) -> None:+ nonlocal known+ if not made.three_d:+ known = names(made, written_frame())+ watch.lines.append(line(play, animations))+ if None not in wanted and not pending:raise Cut # the play showing the last frame asked for is over- made, film = take(kind, look, frames=keep, plays=enough)- if END in wanted and last: # the film's last frame: nothing was sent after it- drawn[-1] = tile(last[0].pixels(), look.width, look.height)- frames = {m: -1 if m == END else at[m] for m in wanted}- if missing := [m for m, k in frames.items() if k not in drawn]:- raise fail(- f"error: the scene ends at {float(made.clock):.2f} s; there is no frame at"- f" {missing[0]} s",- 1,- )- sheets = Sheets(target)- captions: list[str] = []- for moment, k in frames.items():- shown = made.clock if k == -1 else Fraction(k) / fps- when = f"{float(made.clock):.2f}s (end)" if k == -1 else f"{moment}s"- captions.append(caption(on_screen(film.plays, shown), when))- sheets.add(captions[-1], drawn[k])- for n, sheet in enumerate(sheets.close()): # each sheet, and what is on it- typer.echo(- f"{sheet} {'; '.join(captions[n * PER_SHEET : (n + 1) * PER_SHEET])}"+ try:+ # Only an inspection with selected frames uses the adapter. Scene and render+ # keep their ordinary evaluation path, including subclasses' overrides.+ observed = (+ type(kind.__name__, (kind, Sampling), {"__module__": kind.__module__})+ if pending+ else kind)+ made, film = take(observed, look, plays=ended if wanted else watch)+ if pending:+ raise fail(+ f"error: the scene ends at {float(made.clock):.2f} s; there is no frame at"+ f" {pending[-1][1]} s",+ 1,+ )+ if None in wanted or (not wanted and not film.plays):+ watch.see(made, Fraction(film.frame_count - 1) / fps, known=known)+ finally:+ sheets = watch.storyboard.close()+ typer.echo(+ f"{file}: {kind.__name__}, {float(made.clock):.2f} s, {len(film.plays)} plays"+ )+ typer.echo(f"storyboard: {', '.join(str(s) for s in sheets)}")+ typer.echo(watch.report(film=film if not wanted or None in wanted else None))+ if watch.layout.numbers:+ raise typer.Exit(1)def present(@@ -288,7 +269,7 @@ def present(if pdf and last:pictures.append(last[0].pixels()) # the film's last picture ends the last slidehtml = video.with_suffix(".html")- html.write_text(page(film, video.name, kind.__name__), encoding="utf-8")+ html.write_text(page(film, Path(video.name), kind.__name__), encoding="utf-8")slides = len(film.sections)typer.echo(f"{video} {float(made.clock):.2f} s, {look}, {slides} slides (rendered in"@@ -311,7 +292,8 @@ def page(film: Film, video: str | os.PathLike[str], title: str = "manimgx") -> sArgs:film: The film, rendered.- video: Where the page finds its video.+ video: Where the page finds its video: a URL string, or a filesystem path+ (relative to the page, unless absolute).title: The page's title.Returns:@@ -327,8 +309,12 @@ def page(film: Film, video: str | os.PathLike[str], title: str = "manimgx") -> s"captions": [[c.start, c.end, c.text] for c in film.captions()],}html = (files("manimgx") / "cli" / "present.html").read_text(encoding="utf-8")- return (- html.replace("DECK_TITLE", title)- .replace("DECK_VIDEO", Path(video).as_posix())- .replace("DECK_JSON", json.dumps(deck).replace("</", "<\\/"))- )+ if not isinstance(video, str):+ path = Path(video)+ video = path.as_uri() if path.is_absolute() else quote(path.as_posix())+ values = {+ "DECK_TITLE": escape(title),+ "DECK_VIDEO": escape(video),+ "DECK_JSON": json.dumps(deck).replace("</", "<\\/"),+ }+ return re.sub(r"DECK_(?:TITLE|VIDEO|JSON)", lambda match: values[match[0]], html)diff --git a/src/manimgx/cli/storyboard.py b/src/manimgx/cli/storyboard.pyindex 46003c5a..cd973c63 100644--- a/src/manimgx/cli/storyboard.py+++ b/src/manimgx/cli/storyboard.py@@ -4,6 +4,7 @@ import mathfrom collections.abc import Callablefrom concurrent.futures import Future, ThreadPoolExecutorfrom dataclasses import dataclass, field+from fractions import Fractionfrom pathlib import Pathfrom PIL import Image, ImageDraw, ImageFont@@ -12,10 +13,18 @@ from manimgx.animation.timeline import Animation, AnimationGroup, Succession, Wafrom manimgx.animation.transform import Animatefrom manimgx.audio import Speechfrom manimgx.audio.sound import Sound-from manimgx.cli.diagnostics import Layout, Problem, View, report, text_of, view+from manimgx.cli.diagnostics import (+ Layout,+ Names,+ Problem,+ View,+ report,+ text_of,+ view,+)from manimgx.config import configfrom manimgx.rendering.film import Film, Play-from manimgx.scene import Scene+from manimgx.scene import Scene, _written# a tile's area: 1080p halved each way (reduced exactly: sharp text), two to a sheet's row — in# the scene's shape, so a sheet costs the same image tokens whatever the shape@@ -40,15 +49,6 @@ def tile(rgba: bytes, width: int, height: int) -> Image.Image:return image-def caption(play: Play | None, time: str) -> str:- """`#play t=… file:line`: a moment, and the play on screen then — where the code played- it."""- if play is None:- return f"t={time}"- where = "" if play.where is None else f" {Path(play.where[0]).name}:{play.where[1]}"- return f"#{play.index} t={time}{where}"--@dataclassclass Sheets:"""Captioned tiles, six to a sheet, each sheet written as it fills: `path`, `…-2`, …"""@@ -69,11 +69,11 @@ class Sheets:def close(self) -> list[Path]:"""The last sheet out; every sheet written."""- if self._tiles:- self._flush()- for write in self._writes:- write.result()- self._writer.shutdown()+ with self._writer:+ if self._tiles:+ self._flush()+ for write in self._writes:+ write.result()return self.writtendef _flush(self) -> None:@@ -112,11 +112,10 @@ RED = (255, 64, 64)@dataclassclass Watch:- """The plays of a take as it runs (its `plays` hook). With a `storyboard`, the picture at- each play's end (a wait that changes nothing left out), captioned `#play t=end file:line`,- its problems outlined in red with their numbers."""+ """A take's timeline, annotated pictures and layout report. As a `plays` hook it samples+ play endings; `see` inspects the live scene at any moment."""- storyboard: Sheets | None = None+ storyboard: Sheetslayout: Layout = field(default_factory=Layout)lines: list[str] = field(default_factory=list[str])checked: int = 0@@ -127,25 +126,42 @@ class Watch:self, made: Scene, play: Play, animations: tuple[Animation, ...]) -> None:self.lines.append(line(play, animations))+ self.see(made, play.end, play=play, distinct=True)++ def see(+ self,+ made: Scene,+ time: Fraction,+ *,+ play: Play | None = None,+ distinct: bool = False,+ known: Names | None = None,+ ) -> None:+ """Check and draw the scene now; optionally omit a consecutive identical picture."""+ play = play or (made.film.plays[-1] if made.film.plays else None)+ index = None if play is None else play.index+ where = None if play is None else play.where+ # Inside a play that has not ended yet, its source is still on the stack.+ if made.num_plays > len(made.film.plays):+ index, where = made.num_plays - 1, _written()self.three_d = made.three_d- seen = None if made.three_d else view(made)- marked = [] if seen is None else self.layout.see(play, seen)+ seen = None if made.three_d else view(made, known)+ marked = [] if seen is None else self.layout.see((time, where), seen)self.checked += seen is not None- if self.storyboard is None:- returnrgba = made.film.picture(made.camera, made.display_list())picture = tile(rgba, config.pixel_width, config.pixel_height)pixels = picture.tobytes()- if pixels == self._last:+ if distinct and pixels == self._last:returnself._last = pixels- if seen is not None:+ if seen is not None and marked:_mark(picture, seen, marked)- self.storyboard.add(caption(play, f"{float(play.end):.1f}s"), picture)-- def close(self) -> list[Path]:- """The storyboard's sheets, every one written."""- return [] if self.storyboard is None else self.storyboard.close()+ caption = f"t={float(time):g}s"+ if index is not None:+ caption = f"#{index} {caption}"+ if where is not None:+ caption += f" {Path(where[0]).name}:{where[1]}"+ self.storyboard.add(caption, picture)def report(self, *, timeline: bool = True, film: "Film | None" = None) -> str:"""The timeline (if asked), then the layout, then the sounds the film's end cuts@@ -163,9 +179,6 @@ class Watch:]return "\n".join([*(self.lines if timeline else []), layout, *sounds])- def problems(self) -> list[Problem]:- return [p for p in self.layout.found.values() if not p.note]-def _mark(picture: Image.Image, seen: View, marked: list[tuple[int, Problem]]) -> None:"""The problems seen now, outlined in red with their numbers."""diff --git a/tests/integration/test_cli_export.py b/tests/integration/test_cli_export.pynew file mode 100644index 00000000..c78bd93b--- /dev/null+++ b/tests/integration/test_cli_export.py@@ -0,0 +1,84 @@+"""Inspection selects and captions the same observed frame that the film shows."""++import math+import sys+from pathlib import Path++import pytest+import typer+from PIL import Image++from manimgx.cli import export+from manimgx.cli.export import inspect+from manimgx.cli.storyboard import Sheets+++def test_inspections_distinguish_adjacent_times_and_finish_coincident_events(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ source = tmp_path / "still_boundary.py"+ source.write_text(+ "import manimgx as m\n"+ "m.config.pixel_width = m.config.pixel_height = 16\n"+ "m.config.frame_rate = 10\n"+ "class Only(m.Scene):\n"+ " def construct(self):\n"+ " self.camera.background_color = m.RED\n"+ " self.wait(0.1)\n"+ " self.camera.background_color = m.BLUE\n"+ " self.wait(1e-18)\n"+ " self.wait(0.1)\n",+ encoding="utf-8",+ )+ captions: list[str] = []+ pictures: list[bytes] = []++ def keep(sheet: Sheets, text: str, picture: Image.Image) -> None:+ captions.append(text)+ pictures.append(picture.tobytes())++ monkeypatch.setattr(Sheets, "add", keep)+ monkeypatch.setattr(sys, "path", sys.path.copy())+ try:+ inspect(+ source,+ time=[+ str(math.nextafter(0.1, 0)),+ "0.1",+ str(math.nextafter(0.1, math.inf)),+ ],+ output=tmp_path / "still.png",+ )+ finally:+ sys.modules.pop(source.stem, None)+ assert pictures[0] != pictures[1] == pictures[2]+ assert captions[0].startswith("#0 ")+ assert all(caption.startswith("#2 ") for caption in captions[1:])+++def test_a_scene_error_finishes_its_storyboard_writer(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ source = tmp_path / "broken_scene.py"+ source.write_text(+ "import manimgx as m\n"+ "m.config.pixel_width = m.config.pixel_height = 16\n"+ "class Only(m.Scene):\n"+ " def construct(self):\n"+ " self.wait(0.1)\n"+ " raise ValueError('scene failed')\n",+ encoding="utf-8",+ )+ sheets = Sheets(tmp_path / "partial.png")+ monkeypatch.setattr(export, "Sheets", lambda _: sheets)+ monkeypatch.setattr(sys, "path", sys.path.copy())+ try:+ with pytest.raises(typer.Exit):+ export.render(source)+ assert sheets.written == [tmp_path / "partial.png"]+ assert sheets.written[0].is_file()+ with pytest.raises(RuntimeError, match="after shutdown"):+ sheets._writer.submit(lambda: None)+ finally:+ sheets._writer.shutdown()+ sys.modules.pop(source.stem, None)diff --git a/tests/unit/cli/test_storyboard.py b/tests/unit/cli/test_storyboard.pyindex 353aea47..5b0a4225 100644--- a/tests/unit/cli/test_storyboard.py+++ b/tests/unit/cli/test_storyboard.py@@ -1,12 +1,16 @@"""A take's timeline names each play as the code wrote it: a said line as what it says, with theanimations it plays (not the waits that time them), a sound by its length."""+from pathlib import Path+import numpy as np+import pytest+from PIL import Imageimport manimgx as mfrom manimgx.audio import Speech, Wordfrom manimgx.audio.sound import RATE-from manimgx.cli.storyboard import describe+from manimgx.cli.storyboard import Sheets, describedef test_an_animate_chain_names_its_methods_in_order() -> None:@@ -34,3 +38,15 @@ def test_a_sound_is_named_by_its_length() -> None:assert (describe(m.Sound(np.zeros(RATE // 2, np.float32), rate=RATE)) == "sound 0.5 s")+++def test_a_failed_sheet_write_closes_the_writer(tmp_path: Path) -> None:+ sheets = Sheets(tmp_path / "missing" / "storyboard.png")+ sheets.add("a frame", Image.new("RGB", (2, 2)))+ try:+ with pytest.raises(FileNotFoundError):+ sheets.close()+ with pytest.raises(RuntimeError, match="after shutdown"):+ sheets._writer.submit(lambda: None)+ finally:+ sheets._writer.shutdown()