The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.
Python
Generate API docs and examples
Sina Atalay57ad37727003
diff --git a/docs/deprecated.py b/docs/deprecated.pynew file mode 100644index 00000000..b413c71e--- /dev/null+++ b/docs/deprecated.py@@ -0,0 +1,85 @@+"""A griffe extension: what is deprecated is left out of the API reference.++A name manimgx keeps for code written for Manim CE, and no longer teaches (another name of a+class, an empty subclass, a method's second name), is decorated with PEP 702's+`@deprecated(message, category=None)`: ty flags each use of it, and nothing warns as it runs.+The reference documents the name to use instead. So each object so decorated is taken out of+the package as griffe loads it, for mkdocstrings (its `extensions` option names this module)+and for the reference's tests alike: it has no entry and no place among its class's members,+and a link to it stops resolving. A deprecated class stays where it is defined, for the+classes made from it, whose constructor and members are its (TransformMatchingShapes', its+base's): only its other names go, the package's among them, and no page shows it.++The decorator is read from the source, as ty reads it, not as `__deprecated__` at run time:+another name kept the same class as it runs (a decorated class `if TYPE_CHECKING:`, an+assignment `else:`) has no `__deprecated__`, and a class's is inherited by its subclasses. A+property is decorated on its getter, which griffe turns into an attribute without decorators:+its getter's are read from the module's source.+"""++import ast+from functools import cache+from pathlib import Path++import griffe++# where `deprecated` is imported from: Python's own, since 3.13, or its backport+DECORATORS = {"warnings.deprecated", "typing_extensions.deprecated"}+++def deprecated(obj: griffe.Object) -> bool:+ """Whether a class, a function or a property is decorated with `@deprecated`."""+ if isinstance(obj, griffe.Class | griffe.Function):+ return any(+ decorator.callable_path in DECORATORS for decorator in obj.decorators+ )+ if isinstance(obj, griffe.Attribute) and "property" in obj.labels:+ imports = obj.module.imports+ return any(+ imports.get(name, name) in DECORATORS for name in getter_decorators(obj)+ )+ return False+++def getter_decorators(prop: griffe.Attribute) -> list[str]:+ """The names of a property's getter's decorators, as its module writes them."""+ if prop.filepath is None or isinstance(prop.filepath, list):+ return []+ for node in ast.walk(tree(Path(prop.filepath))):+ if isinstance(node, ast.FunctionDef) and (node.name, node.lineno) == (+ prop.name,+ prop.lineno,+ ):+ return [+ ast.unparse(d.func if isinstance(d, ast.Call) else d)+ for d in node.decorator_list+ ]+ return []+++@cache+def tree(path: Path) -> ast.Module:+ return ast.parse(path.read_text(encoding="utf-8"))+++def drop(obj: griffe.Object) -> None:+ """Take every deprecated object out of a module or a class, at every depth, with each+ import of one (the package's `import *`, expanded before the hook, names it too). A+ deprecated class keeps its definition, for its subclasses: only its imports go."""+ for name, member in list(obj.members.items()):+ try:+ target = member.final_target if isinstance(member, griffe.Alias) else member+ except (griffe.AliasResolutionError, griffe.CyclicAliasError):+ continue # another package's+ if deprecated(target):+ if isinstance(member, griffe.Alias) or not isinstance(member, griffe.Class):+ obj.del_member(name)+ elif not isinstance(member, griffe.Alias) and isinstance(+ member, griffe.Module | griffe.Class+ ):+ drop(member)+++class Deprecated(griffe.Extension):+ def on_package(self, *, pkg: griffe.Module, **kwargs: object) -> None:+ drop(pkg)diff --git a/docs/examples.py b/docs/examples.pynew file mode 100644index 00000000..ffa1ba3b--- /dev/null+++ b/docs/examples.py@@ -0,0 +1,317 @@+"""The docs' examples, rendered: a Python block that defines a scene is shown with its film.++`python -m docs.examples [PATH...]` gathers the Python blocks of the pages (`content/`), of+the README and of the docstrings (`src/manimgx/`) and renders each scene+among them — those written under the given paths, if any — into `content/films/`: a still of+its last frame with anything on it, and a video too if anything moves. A film is named after its scene and+a digest of its code, so an example renders once per version. GitHub and PyPI play no video,+so a README scene is also `readme-<scene>.svg`, a name the README can show: the scene as an+SVG that plays itself (`docs.svg`).++While the site builds, `fence` (SuperFences' formatter for Python blocks, set in+`docs/zensical.toml`) puts each block's film above its code.+"""++import ast+import hashlib+import html+import re+import shutil+import sys+import textwrap+import types+from concurrent.futures import ProcessPoolExecutor, as_completed+from dataclasses import dataclass+from functools import cached_property+from pathlib import Path+from typing import TYPE_CHECKING, cast++if TYPE_CHECKING:+ from markdown import Markdown+ from pymdownx.superfences import SuperFencesBlockPreprocessor++ from manimgx import Scene++DOCS = Path(__file__).parent+PAGES = DOCS / "content"+README = DOCS.parent / "README.md"+SOURCE = DOCS.parent / "src" / "manimgx"+FILMS = PAGES / "films"+VOICE = DOCS / "voice"+URL = "/films"+# how a film is made: at the films' own rate (60 frames a second, the default), encoded for the+# web, where slow and CRF 28 make a tenth of the default's file (ultrafast, 18), alike to the eye,+# in the same time. A film's name digests this with its code, so a change here makes them again.+SIZE, FPS = (1280, 720), 60+PRESET, CRF = "slow", 28+FORMAT = f"{SIZE[0]}x{SIZE[1]} at {FPS} fps, {PRESET}, CRF {CRF}"++FENCE = re.compile(+ r"^(?P<indent>[ \t]*)```(?:python|py)\b[^\n]*\n(?P<code>.*?)^(?P=indent)```",+ re.MULTILINE | re.DOTALL,+)+++@dataclass(frozen=True)+class Example:+ """A Python block of the docs, and where it is written (`path:line`)."""++ code: str+ where: str = ""++ @cached_property+ def scene(self) -> str | None:+ """The scene it renders: the last class it defines on a scene, if any."""+ try:+ tree = ast.parse(self.code)+ except SyntaxError:+ return None+ scenes: list[str] = []+ for node in tree.body:+ if isinstance(node, ast.ClassDef) and any(+ (name := _name(base)).endswith("Scene") or name in scenes+ for base in node.bases+ ):+ scenes.append(node.name)+ return scenes[-1] if scenes else None++ @cached_property+ def stem(self) -> str:+ """Its film's name: the scene's, and a digest of the code and of how films are+ made (`FORMAT`)."""+ code = textwrap.dedent(self.code).strip() + "\n"+ digest = hashlib.sha256(f"{FORMAT}\n{code}".encode()).hexdigest()[:10]+ return f"{self.scene}-{digest}"+++def _name(node: ast.expr) -> str:+ """A base class as written, by its last name (`Scene` and `m.Scene` are "Scene")."""+ if isinstance(node, ast.Attribute):+ return node.attr+ return node.id if isinstance(node, ast.Name) else ""+++def blocks(text: str, path: Path, line: int = 1) -> list[Example]:+ """The Python blocks of a text written in a file (from a given line of it)."""+ where = path.relative_to(DOCS.parent)+ return [+ Example(+ textwrap.dedent(match["code"]),+ f"{where}:{line + text.count(chr(10), 0, match.start())}",+ )+ for match in FENCE.finditer(text)+ ]+++def examples() -> list[Example]:+ """Every scene the docs show: the pages', the README's, then the docstrings'."""+ found = [+ block+ for page in [*sorted(PAGES.rglob("*.md")), README]+ for block in blocks(page.read_text(encoding="utf-8"), page)+ ]+ for module in sorted(SOURCE.rglob("*.py")):+ for node in ast.walk(ast.parse(module.read_text(encoding="utf-8"))):+ if isinstance(+ node, ast.Module | ast.ClassDef | ast.FunctionDef | ast.AsyncFunctionDef+ ) and (doc := ast.get_docstring(node)):+ found += blocks(doc, module, node.body[0].lineno)+ return [example for example in found if example.scene is not None]+++def load(example: Example) -> "type[Scene]":+ """An example's scene, its code run as a module whose file is in docs/: a narrated+ example keeps what it says in docs/voice/ (committed, so the build speaks only a line+ that is new)."""+ import manimgx as m++ module = types.ModuleType("__example__")+ module.__file__ = str(VOICE.parent / "examples.py")+ sys.modules[module.__name__] = module+ exec(compile(example.code, example.where, "exec"), module.__dict__)+ scene = module.__dict__[str(example.scene)]+ if not (isinstance(scene, type) and issubclass(scene, m.Scene)):+ raise TypeError(f"{example.scene} is not a scene")+ return scene+++def render(example: Example, readme: bool = False) -> None:+ """Render an example's scene into its film — in a process of its own, since an example+ may change the configuration — and, for the README's, into its SVGs too: one for a dark+ page, one for a light page (`<stem>-light.svg`)."""+ from docs import svg+ from PIL import Image++ import manimgx as m+ from manimgx.rendering.film import Frame++ m.config.pixel_width, m.config.pixel_height = SIZE+ m.config.frame_rate = FPS+ scene = load(example)+ drawn, poster = 0, b""++ def keep(frame: Frame) -> None:+ """Count the frames (each is sent once, however long it holds), and keep the last one+ with anything on it: a scene that ends empty is shown as it was before."""+ nonlocal drawn, poster+ drawn += 1+ pixels = frame.pixels()+ if not poster or pixels.count(pixels[:4]) * 4 != len(pixels):+ poster = pixels++ video = FILMS / f"{example.stem}.mp4"+ size = m.config.pixel_width, m.config.pixel_height+ scene().render(video, frames=keep, preset=PRESET, crf=CRF)+ still = Image.frombytes("RGBA", size, poster).convert("RGB")+ still.save(FILMS / f"{example.stem}.webp", quality=90, method=6)+ if drawn == 1: # nothing moves: the still is the film+ video.unlink()+ if readme:+ recording = svg.record(scene)+ svg.write(recording, FILMS / f"{example.stem}.svg")+ svg.write(recording, FILMS / f"{example.stem}-light.svg", light=True)+++def main(only: list[str]) -> None:+ """Render every example whose film is missing — only those written under the paths in+ `only`, if any — and, rendering them all, delete the films of none."""+ FILMS.mkdir(parents=True, exist_ok=True)+ scenes: dict[str, Example] = {}+ for example in examples():+ seen = scenes.setdefault(str(example.scene), example)+ if seen.stem != example.stem:+ sys.exit(+ f"{example.where}: {example.scene} is also defined at {seen.where}"+ " (a scene's name is its film's: it must be unique)"+ )+ readme = _readme()+ if only:+ scenes = {+ name: e for name, e in scenes.items() if e.where.startswith(tuple(only))+ }+ else:+ stems = {example.stem for example in scenes.values()}+ shown = {e.stem for e in scenes.values() if e.scene in readme}+ shown |= {f"readme-{name}" for name in readme}+ stems |= shown | {f"{stem}-light" for stem in shown}+ for (+ film+ ) in FILMS.iterdir(): # a film's files: <stem>.webp, .mp4, .svg, -light.svg+ if film.name.split(".")[0] not in stems:+ film.unlink()+ todo = [e for e in scenes.values() if not _rendered(e, e.scene in readme)]+ if todo: # a long render shows nothing until it ends: say what is being made+ names = ", ".join(str(e.scene) for e in todo[:6])+ print(f"rendering {len(todo)}: {names}{', ...' * (len(todo) > 6)}", flush=True)+ failed = 0+ with ProcessPoolExecutor(max_tasks_per_child=1) as pool:+ futures = {pool.submit(render, e, e.scene in readme): e for e in todo}+ for done, future in enumerate(as_completed(futures), 1):+ example = futures[future]+ if (error := future.exception()) is not None:+ failed += 1+ print(f"{example.where}: {example.scene} failed: {error!r}")+ else:+ print(f"[{done}/{len(todo)}] {example.scene}")+ print(f"{len(scenes)} scenes: {len(todo) - failed} rendered, {failed} failed")+ for example in scenes.values():+ for variant in ("", "-light") if example.scene in readme else ():+ if (film := FILMS / f"{example.stem}{variant}.svg").exists():+ shutil.copyfile(film, FILMS / f"readme-{example.scene}{variant}.svg")+ if failed:+ sys.exit(1)+++def _readme() -> set[str]:+ """The names of the README's scenes, which it shows under names of their own."""+ text = README.read_text(encoding="utf-8")+ return {str(e.scene) for e in blocks(text, README) if e.scene}+++def _rendered(example: Example, readme: bool) -> bool:+ """Whether an example's film is made: its still, and, for the README's, its SVGs (a+ scene rendered before the README showed it has none yet)."""+ film = FILMS / example.stem+ return film.with_suffix(".webp").exists() and (+ not readme+ or all((FILMS / f"{example.stem}{v}.svg").exists() for v in ("", "-light"))+ )+++def validate(+ language: str,+ inputs: dict[str, str],+ options: dict[str, object],+ attrs: dict[str, object],+ md: "Markdown",+) -> bool:+ """SuperFences' validator for Python blocks: Highlight's options (a title, line+ numbers, lines to mark), and `fold` and `show`, which `fence` takes (an option the+ validator leaves unknown fails the block)."""+ from pymdownx.superfences import highlight_validator++ if (fold := inputs.pop("fold", None)) is not None:+ options["fold"] = fold+ if (show := inputs.pop("show", None)) is not None:+ if show not in ("code", "film"):+ return False+ options["show"] = show+ return highlight_validator(language, inputs, options, attrs, md)+++def fence(+ source: str,+ language: str,+ class_name: str,+ options: dict[str, object],+ md: "Markdown",+ **kwargs: object,+) -> str:+ """SuperFences' formatter for Python blocks: the block highlighted as any other, under+ its scene's film if it has one. A block marked `fold` (a gallery film's file) is folded+ under its title, the film above it. `show="code"` shows the code alone and+ `show="film"` the film alone, so that a page can put words between a program and its+ video (the two blocks hold the same code: a scene's name is its film's, one film)."""+ fenced = cast("SuperFencesBlockPreprocessor", md.preprocessors["fenced_code_block"])+ fold = options.pop("fold", None) is not None+ show = options.pop("show", None)+ title = options.pop("title", "Code") if fold else None+ film = None if show == "code" else _film(Example(source))+ if show == "film":+ return "" if film is None else f'<figure class="mx-example">{film}</figure>'+ code = fenced.highlight(+ src=source, language=language, options=options, md=md, **kwargs+ )+ if fold:+ code = (+ f'<details class="mx-code"><summary>{html.escape(str(title))}</summary>'+ f"{code}</details>"+ )+ return code if film is None else f'<figure class="mx-example">{film}{code}</figure>'+++def _film(example: Example) -> str | None:+ """A rendered example's film, as HTML: its video, or its still if nothing moves. A+ film taller than wide (9:16) is marked, so that it is not as wide as the page."""+ if example.scene is None or not (still := FILMS / f"{example.stem}.webp").exists():+ return None+ from PIL import Image++ with Image.open(still) as image:+ width, height = image.size+ size = f'width="{width}" height="{height}"'+ kind = "mx-film mx-film--tall" if height > width else "mx-film"+ if (FILMS / f"{example.stem}.mp4").exists():+ return (+ f'<video class="{kind}" src="{URL}/{example.stem}.mp4"'+ f' poster="{URL}/{still.name}" {size} aria-label="{example.scene}"'+ ' muted loop playsinline controls preload="none"></video>'+ )+ return (+ f'<img class="{kind}" src="{URL}/{still.name}" {size}'+ f' alt="{example.scene}" loading="lazy">'+ )+++if __name__ == "__main__":+ main(sys.argv[1:])diff --git a/docs/films.py b/docs/films.pynew file mode 100644index 00000000..7121fb1d--- /dev/null+++ b/docs/films.py@@ -0,0 +1,47 @@+"""A Markdown extension: a picture named by the scene it shows, ``.++A film's file is named after its scene and a digest of its code (`docs/examples.py`), so a page+can't write the name of a film whose code may change. A picture whose source is `film:` and a+scene's name shows that scene's still, wherever its code is: on a page or in a docstring. A+scene that has no film yet stops the build: a card is never without its picture.+"""++from xml.etree.ElementTree import Element++from docs import examples+from markdown import Extension, Markdown+from markdown.treeprocessors import Treeprocessor++PREFIX = "film:"+++def still(scene: str) -> str:+ """The URL of a scene's still: its film's, the newest if an old one is left."""+ found = sorted(+ examples.FILMS.glob(f"{scene}-*.webp"), key=lambda path: path.stat().st_mtime+ )+ stills = [path for path in found if path.stem.rsplit("-", 1)[0] == scene]+ if not stills:+ raise ValueError(+ f"film:{scene}: no film of that scene (python -m docs.examples)"+ )+ return f"{examples.URL}/{stills[-1].name}"+++class Films(Treeprocessor):+ def run(self, root: Element) -> None:+ for image in root.iter("img"):+ source = image.get("src", "")+ if source.startswith(PREFIX):+ image.set("src", still(source.removeprefix(PREFIX)))+ image.set("loading", "lazy")+++class FilmsExtension(Extension):+ def extendMarkdown(self, md: Markdown) -> None:+ # after inline images are made (InlineProcessor runs at 20 as a treeprocessor)+ md.treeprocessors.register(Films(md), "films", 5)+++def makeExtension(**kwargs: object) -> FilmsExtension:+ return FilmsExtension(**kwargs)diff --git a/docs/links.py b/docs/links.pynew file mode 100644index 00000000..edd73f39--- /dev/null+++ b/docs/links.py@@ -0,0 +1,67 @@+"""A Markdown extension: a page's links and images on the site's own host, as its paths.++The README is written for GitHub and PyPI, so it reaches the site's images and pages by+absolute URLs (`https://manimgx.academa.ai/...`); included as the Welcome page, they would ask+the deployed site for them, even in a preview. Once a page is rendered, every URL an element+holds (`src`, `srcset`, `href`, `poster`) whose host is the site's keeps only its path, so a+page shows the images and links of the site it is on, as it was built, whatever wrote the+URL. Text is left as it is: a code block's `<` is escaped, so no tag is ever in it.+"""++import re+import tomllib+from pathlib import Path+from urllib.parse import urlsplit, urlunsplit++from markdown import Extension, Markdown+from markdown.postprocessors import Postprocessor++CONFIG = tomllib.loads(+ (Path(__file__).parent / "zensical.toml").read_text(encoding="utf-8")+)+HOST = urlsplit(CONFIG["project"]["site_url"]).netloc+# an element's start tag (a quoted value may hold ">"), and one of its URLs, quoted+TAG = re.compile(r"""<[a-zA-Z](?:"[^"]*"|'[^']*'|[^'">])*>""")+URL = re.compile(r"""(\s(src|srcset|href|poster)\s*=\s*)(["'])(.*?)\3""", re.DOTALL)+++def local(url: str) -> str:+ """A URL whose host is the site's, as its path on the site; any other, as it is."""+ parts = urlsplit(url)+ if parts.netloc != HOST:+ return url+ return urlunsplit(("", "", parts.path or "/", parts.query, parts.fragment))+++def _attribute(match: re.Match[str]) -> str:+ start, name, quote, value = match.groups()+ if HOST not in value: # not the site's: as written, to the byte+ return match.group()+ if name == "srcset": # candidates: a URL each, and a size or a density+ value = ", ".join(+ " ".join([local(url), *rest])+ for url, *rest in (c.split() for c in value.split(",") if c.strip())+ )+ else:+ value = local(value)+ return f"{start}{quote}{value}{quote}"+++def paths(html: str) -> str:+ """A rendered page, its URLs on the site's host made the site's paths."""+ return TAG.sub(lambda tag: URL.sub(_attribute, tag.group()), html)+++class Paths(Postprocessor):+ def run(self, text: str) -> str:+ return paths(text)+++class SitePaths(Extension):+ def extendMarkdown(self, md: Markdown) -> None:+ # after the raw HTML (the README's images) is put back in (30)+ md.postprocessors.register(Paths(md), "site_paths", 10)+++def makeExtension(**kwargs: object) -> SitePaths:+ return SitePaths(**kwargs)diff --git a/docs/mkdocstrings.py b/docs/mkdocstrings.pynew file mode 100644index 00000000..c1274880--- /dev/null+++ b/docs/mkdocstrings.py@@ -0,0 +1,36 @@+"""A Markdown extension: mkdocstrings finds manimgx's templates, `docs/templates/`.++mkdocstrings' `custom_templates` names a folder. MkDocs makes it absolute, from the folder of+its settings, before mkdocstrings reads it; Zensical passes it on as written. Then mkdocstrings+reads it from the working directory (the repository's root, where the build runs) and finds+nothing there, so its default templates show the reference, while mkdocstrings-python reads it+from the settings' folder (`docs/`). This extension makes it absolute, from the settings'+folder, as MkDocs does. It is listed before mkdocstrings, whose extension Zensical adds last, so+it does this before mkdocstrings reads the setting.+"""++from pathlib import Path++from markdown import Extension, Markdown++MKDOCSTRINGS = "zensical.extensions.mkdocstrings"+++def resolve() -> None:+ """Make the settings' `custom_templates` absolute, from the settings' folder."""+ from zensical.config import get_config++ config = get_config()+ options = config["mdx_configs"].get(MKDOCSTRINGS) or {}+ templates = options.get("custom_templates")+ if templates and not Path(templates).is_absolute():+ options["custom_templates"] = str(Path(config["root_dir"]) / templates)+++class Templates(Extension):+ def extendMarkdown(self, md: Markdown) -> None:+ resolve()+++def makeExtension(**kwargs: object) -> Templates:+ return Templates(**kwargs)diff --git a/docs/previews.py b/docs/previews.pynew file mode 100644index 00000000..7c158640--- /dev/null+++ b/docs/previews.py@@ -0,0 +1,45 @@+"""A Markdown extension: a reference to the API previews its target on hover, as a link does.++The theme previews a link marked `data-preview` when the pointer rests on it, and Zensical's+preview extension marks the links it finds as each page is converted. A reference to the API is+no link yet then: it is an `<autoref>` tag, from a page's Markdown (`[Scene][manimgx.Scene]`) or+from the reference's templates (a signature's types), which Zensical makes a link once every+page's URL is known, keeping the tag's attributes. So each tag is marked in the rendered page.+Text is left as it is: a code block's `<` is escaped, so no tag is ever in it.++A card's link previews nothing: the card, a link as a whole, shows its page's still, name and+words already, and a preview would cover it and the cards beside it.+"""++import re++from markdown import Extension, Markdown+from markdown.postprocessors import Postprocessor++# a reference's tag not marked yet: a docstring's pass here twice, as mkdocstrings converts the+# docstring and then as its page is converted+UNMARKED = re.compile(r"<autoref\b(?![^>]*\sdata-preview\b)")+# the cards of an index (the reference's, the Gallery's), whose links Zensical marked+CARDS = re.compile(r'<div class="grid cards mx-cards">.*?</div>', re.DOTALL)+++def marked(html: str) -> str:+ """A rendered page, each reference to the API in it marked to preview its target, and+ each card's link not."""+ html = UNMARKED.sub("<autoref data-preview", html)+ return CARDS.sub(lambda cards: cards[0].replace(' data-preview=""', ""), html)+++class References(Postprocessor):+ def run(self, text: str) -> str:+ return marked(text)+++class Previews(Extension):+ def extendMarkdown(self, md: Markdown) -> None:+ # after the raw HTML (the reference's templates) is put back in (30)+ md.postprocessors.register(References(md), "previews", 10)+++def makeExtension(**kwargs: object) -> Previews:+ return Previews(**kwargs)diff --git a/docs/svg.py b/docs/svg.pynew file mode 100644index 00000000..35e2d1cf--- /dev/null+++ b/docs/svg.py@@ -0,0 +1,407 @@+"""Scenes as animated SVGs: what manimgx draws, frame by frame, as paths an SVG plays.++GitHub and PyPI show a README's images but play no video, and a video made into an animated+image is large and soft. A scene made of paths (curves, shapes, text; no surfaces, meshes or+point clouds) is shown instead as an SVG that plays itself (SMIL), sharp at any size:+`record` runs the scene and reads, at every frame, its view and each path's paint (the+stretch of it drawn, its stroke, its fill), and `write` turns the recording into the SVG.+Each path is written at its whole shape, seen through the camera at keyframes the browser+interpolates (if the camera moves), drawn as far as its reveal has come by an animated+dash, and painted as its frames paint it. A path must keep its shape (the camera may move):+a scene whose paths change shape is refused. The SVG has no background: the page's shows+through, and a light page takes its own variant, whose white ink is dark.+"""++import itertools+from dataclasses import dataclass, field+from pathlib import Path++import numpy as np++import manimgx as m+from manimgx.rendering import feed++KEYFRAME = 0.6 # seconds between the views of a moving camera that are written+SAMPLES = 16 # points a long subpath seen by a moving camera is written through+EXACT = 24 # curves a subpath may have to be written as it is, however the camera moves+INK = "#1F2328" # GitHub's text on a light page: what a scene's white ink is drawn in there++type Paint = tuple[float, float, np.ndarray, float, np.ndarray]+"""A path's paint at a frame: the stretch drawn (from, to, in curve parameter), its stroke+(RGBA), its stroke's width (pixels) and its fill (RGBA)."""+++@dataclass+class Drawn:+ """A path the scene draws: its control points (four a curve), whether it is fixed in+ the frame, and its paint at each frame it is drawn."""++ points: np.ndarray+ fixed: bool+ paints: dict[int, Paint] = field(default_factory=dict)+++@dataclass+class Recording:+ """What a scene drew: its size in pixels and frame rate, the view of what is fixed in+ the frame, its length in frames, its view (world → clip) at each frame, and its paths,+ in the order they are drawn."""++ size: tuple[int, int]+ fps: int+ overlay: np.ndarray+ frames: int = 0+ three_d: bool = False+ views: dict[int, np.ndarray] = field(default_factory=dict)+ paths: dict[int, Drawn] = field(default_factory=dict)++ def capture(+ self, frame: int, repeat: int, camera: m.Camera, mobjects: list[m.Mobject]+ ) -> None:+ """Keep a frame, shown `repeat` times: its view, and each path's paint."""+ width, height = self.size+ unit = height / camera.frame_height # pixels a scene unit, as the engine's+ _, self.views[frame], self.three_d = feed.view(camera, width, height)+ fixed = camera.fixed_in_frame_mobjects+ for mob in mobjects:+ if isinstance(mob, m.PMobject | m.MeshMobject): # (an image is a mesh)+ raise ValueError(f"an SVG shows paths only, not a {type(mob).__name__}")+ if not isinstance(mob, m.VMobject):+ continue # nothing the engine draws either (a value tracker)+ drawn = self.paths.setdefault(id(mob), Drawn(mob.points, mob in fixed))+ if mob.points is not drawn.points and not ( # a tween's rounding aside+ mob.points.shape == drawn.points.shape+ and np.allclose(mob.points, drawn.points, rtol=0, atol=1e-9)+ ):+ raise ValueError(f"a {type(mob).__name__} changes shape")+ paint = mob.paint+ lo, hi = paint.window(len(mob.points) // 4)+ stroke, fill = paint.stroke[0].copy(), paint.fill[0].copy()+ drawn.paints[frame] = (+ lo,+ hi,+ stroke,+ paint.stroke_width * 0.01 * unit,+ fill,+ )+ self.frames = frame + repeat+++def record(scene: type[m.Scene]) -> Recording:+ """Run a scene, keeping every frame it draws. None is played at once: a scene updater+ that does nothing has every frame computed, and those are the same frames."""+ width, height = m.config.pixel_width, m.config.pixel_height+ hw, hh = m.config.frame_width / 2, m.config.frame_height / 2+ recording = Recording(+ (width, height),+ int(m.config.frame_rate),+ np.diag([1 / hw, 1 / hh, 0.0, 1.0]),+ )++ def setup(self: m.Scene) -> None:+ scene.setup(self)+ self.add_updater(lambda dt: None)++ def emit(self: m.Scene, repeat: int = 1) -> None:+ if repeat > 0:+ recording.capture(self.frame, repeat, self.camera, self.display_list())+ scene._emit(self, repeat)++ type(scene.__name__, (scene,), {"setup": setup, "_emit": emit})().render()+ return recording+++def write(+ recording: Recording, file: Path, fade: float = 0.4, light: bool = False+) -> None:+ """Write a recording as an SVG that loops, fading out over its last `fade` seconds, on+ no background. For a light page (`light`), the scene's white ink (a color whose every+ channel is at least 0.75: its text, say) is drawn in the page's (`INK`)."""+ width, height = recording.size+ total, fps = recording.frames, recording.fps+ first = recording.views[0]+ moving = any(not np.array_equal(v, first) for v in recording.views.values())+ step = max(1, round(KEYFRAME * fps))+ keys = sorted({*range(0, total, step), total - 1} & recording.views.keys())+ timing = Timing(total, total / fps)+ body = []+ for drawn in _order(recording, keys):+ body += _elements(drawn, recording, timing, keys if moving else [0], light)+ out = timing.frames - round(fade * fps)+ fading = timing.animate("opacity", ["1", "1", "0"], [0, out, timing.frames])+ file.write_text(+ '<svg xmlns="http://www.w3.org/2000/svg"'+ f' viewBox="0 0 {width} {height}" width="{width}" height="{height}">'+ f"<g>{fading}{''.join(body)}</g></svg>\n",+ encoding="utf-8",+ )+++@dataclass(frozen=True)+class Timing:+ """A film's length, in frames and in seconds: an attribute's values at frames, as an+ animation that loops with it."""++ frames: int+ seconds: float++ def animate(+ self, name: str, values: list[str], at: list[int], discrete: bool = False+ ) -> str:+ times = ";".join(f"{f / self.frames:.5g}" for f in at)+ mode = ' calcMode="discrete"' if discrete else ""+ return (+ f'<animate attributeName="{name}" dur="{self.seconds:g}s"'+ f' repeatCount="indefinite"{mode} keyTimes="{times}"'+ f' values="{";".join(values)}"/>'+ )++ def track(+ self, name: str, texts: list[str], values: np.ndarray, tolerance: float+ ) -> tuple[str, str]:+ """An attribute through the frames: its first value, and its animation (none if+ it holds), through the frames that keep it within `tolerance` of every frame."""+ if all(t == texts[0] for t in texts):+ return texts[0], ""+ keep = _breakpoints(values, tolerance)+ return texts[0], self.animate(+ name, [texts[k] for k in keep] + [texts[-1]], keep + [self.frames]+ )+++def _elements(+ drawn: Drawn, recording: Recording, timing: Timing, keys: list[int], light: bool+) -> list[str]:+ """A path's elements: its fill (one element for all its subpaths, so that holes stay+ holes), then its stroke (one element a subpath, dashed as far as it is drawn)."""+ frames = sorted(drawn.paints)+ everything = np.arange(timing.frames)+ # a frame the path is not drawn at takes the paint of the last it is drawn at+ at = np.maximum(np.searchsorted(frames, everything, side="right") - 1, 0)+ paints = [drawn.paints[frames[i]] for i in at]+ stroke = np.array([p[2] for p in paints])+ width = np.array([p[3] for p in paints])+ fill = np.array([p[4] for p in paints])+ curves = drawn.points.reshape(-1, 4, 3)+ parts = _subpaths(curves)+ keys = [0] if drawn.fixed else keys+ views = [_view(drawn, recording, f) for f in keys]+ digits = 0 if len(keys) > 1 else 1 # whole pixels for a moving camera's paths+ shapes = [+ [_shape(curves[a:b], v, recording.size, digits) for v in views]+ for a, b in parts+ ]+ shown = np.isin(everything, frames)+ common = []+ if not shown.all():+ states = ["visible" if s else "hidden" for s in shown]+ changes = [0, *(k for k in everything[1:] if states[k] != states[k - 1])]+ common.append(+ timing.animate(+ "visibility",+ [states[k] for k in changes] + [states[-1]],+ [*changes, timing.frames],+ discrete=True,+ )+ )+ elements = []+ if (fill[:, 3] > 0).any():+ data = [" ".join(shape[i] for shape in shapes) for i in range(len(keys))]+ attributes = {"d": data[0], "stroke": "none"}+ animations = [_keyframes("d", data, keys, timing), *common]+ _paint("fill", fill, timing, attributes, animations, light)+ elements.append(_element(attributes, animations))+ if (stroke[:, 3] > 0).any() and (width > 0).any():+ lo_hi = np.array([(p[0], p[1]) for p in paints])+ for (a, b), shape in zip(parts, shapes, strict=True):+ attributes = {"d": shape[0], "fill": "none", "stroke-linejoin": "round"}+ animations = [_keyframes("d", shape, keys, timing), *common]+ _paint("stroke", stroke, timing, attributes, animations, light)+ texts = [_number(w, 2) for w in width]+ attributes["stroke-width"], moving = timing.track(+ "stroke-width", texts, width[:, None], 0.05+ )+ animations.append(moving)+ windows = _windows(drawn, a, b, lo_hi, recording)+ if not ((windows[:, 0] <= 1e-4) & (windows[:, 1] >= 1 - 1e-4)).all():+ attributes["pathLength"] = "1"+ texts = [f"0 {_number(x, 4)} {_number(y - x, 4)} 2" for x, y in windows]+ attributes["stroke-dasharray"], moving = timing.track(+ "stroke-dasharray", texts, windows, 0.002+ )+ animations.append(moving)+ elements.append(_element(attributes, animations))+ return elements+++def _order(recording: Recording, keys: list[int]) -> list[Drawn]:+ """The paths in the order an SVG draws them: as the scene draws them in 2D; in 3D,+ which has a depth test and an SVG none, from the farthest on average to the nearest,+ then what is fixed in the frame, over everything."""+ paths = list(recording.paths.values())+ if not recording.three_d:+ return paths++ def distance(drawn: Drawn) -> float: # clip w grows with the distance from the eye+ anchors = drawn.points[::4]+ views = [recording.views[f] for f in keys]+ return float(np.mean([anchors @ v[3, :3] + v[3, 3] for v in views]))++ seen = sorted((d for d in paths if not d.fixed), key=distance, reverse=True)+ return seen + [d for d in paths if d.fixed]+++def _paint(+ name: str,+ rgba: np.ndarray,+ timing: Timing,+ attributes: dict[str, str],+ animations: list[str],+ light: bool,+) -> None:+ """A fill's or a stroke's color and opacity, each animated if it changes: on a light+ page, white ink in the page's."""+ colors = [+ INK if light and (c[:3] >= 0.75).all() else m.ManimColor(c[:3]).to_hex()+ for c in rgba+ ]+ attributes[name], moving = timing.track(name, colors, rgba[:, :3], 1 / 255)+ animations.append(moving)+ opacity = [_number(a, 3) for a in rgba[:, 3]]+ attributes[f"{name}-opacity"], moving = timing.track(+ f"{name}-opacity", opacity, rgba[:, 3:], 0.004+ )+ animations.append(moving)+++def _keyframes(name: str, values: list[str], keys: list[int], timing: Timing) -> str:+ """An attribute through its values at keyframes (none if it has one), the last held."""+ if len(values) < 2:+ return ""+ return timing.animate(name, [*values, values[-1]], [*keys, timing.frames])+++def _element(attributes: dict[str, str], animations: list[str]) -> str:+ text = "".join(f' {name}="{value}"' for name, value in attributes.items())+ inner = "".join(animations)+ return f"<path{text}>{inner}</path>" if inner else f"<path{text}/>"+++def _view(drawn: Drawn, recording: Recording, frame: int) -> np.ndarray:+ """The view a path is seen through at a frame: the frame's own, fixed in the frame."""+ if drawn.fixed:+ return recording.overlay+ return recording.views[max(f for f in recording.views if f <= frame)]+++def _windows(+ drawn: Drawn, a: int, b: int, lo_hi: np.ndarray, recording: Recording+) -> np.ndarray:+ """The stretch of the subpath of curves a … b drawn at each frame, from and to, as+ fractions of its length on screen."""+ curves = drawn.points.reshape(-1, 4, 3)[a:b]+ u = np.linspace(0, b - a, 4 * (b - a) + 1) # four samples a curve+ dense = _evaluate(curves, u)+ local = np.clip(lo_hi - a, 0, b - a)+ windows = np.where(local[:, 1:] > local[:, :1], [0.0, 1.0], [0.0, 0.0])+ for k in np.flatnonzero(+ (local[:, 1] > local[:, 0]) & ((local[:, 0] > 0) | (local[:, 1] < b - a))+ ):+ screen = _screen(dense, _view(drawn, recording, int(k)), recording.size)+ steps = np.linalg.norm(np.diff(screen, axis=0), axis=1)+ length = np.concatenate([[0.0], np.cumsum(steps)])+ windows[k] = np.interp(local[k], u, length) / max(length[-1], 1e-9)+ return windows+++def _subpaths(curves: np.ndarray) -> list[tuple[int, int]]:+ """Where a path's subpaths are: the ranges of its curves that join end to start."""+ gaps = np.linalg.norm(curves[1:, 0] - curves[:-1, 3], axis=1) > 1e-6+ edges = [0, *(int(g) + 1 for g in np.flatnonzero(gaps)), len(curves)]+ return list(itertools.pairwise(edges))+++def _shape(+ curves: np.ndarray, view: np.ndarray, size: tuple[int, int], digits: int+) -> str:+ """A subpath as SVG path data, on screen through a view: its own curves if they are+ few, else a smooth curve through points evenly spaced along it (the same points at+ every keyframe, so that the browser interpolates between them)."""+ closed = bool(np.linalg.norm(curves[0, 0] - curves[-1, 3]) < 1e-6)+ if len(curves) <= EXACT:+ points = _screen(curves.reshape(-1, 3), view, size).reshape(-1, 4, 2)+ data = "M" + _pair(points[0, 0], digits)+ data += "".join("C" + " ".join(_pair(q, digits) for q in c[1:]) for c in points)+ return data + ("Z" if closed else "")+ u = np.arange(len(curves) + 1, dtype=float)+ anchors = _evaluate(curves, u)+ steps = np.linalg.norm(np.diff(anchors, axis=0), axis=1)+ length = np.concatenate([[0.0], np.cumsum(steps)])+ count = SAMPLES if closed else SAMPLES + 1+ at = np.linspace(0, length[-1], count, endpoint=not closed)+ p = _screen(_evaluate(curves, np.interp(at, length, u)), view, size)+ if closed: # Catmull-Rom's tangents, as Bézier handles+ before, after, beyond = (np.roll(p, s, axis=0) for s in (1, -1, -2))+ else:+ before = np.vstack([p[:1], p[:-1]])+ after = np.vstack([p[1:], p[-1:]])+ beyond = np.vstack([p[2:], p[-1:], p[-1:]])+ first, second = p + (after - before) / 6, after - (beyond - p) / 6+ data = "M" + _pair(p[0], digits)+ for i in range(len(p) if closed else len(p) - 1):+ data += "C" + " ".join(+ _pair(q, digits) for q in (first[i], second[i], after[i])+ )+ return data + ("Z" if closed else "")+++def _evaluate(curves: np.ndarray, u: np.ndarray) -> np.ndarray:+ """Points of a path's cubic Bézier curves at curve parameters u ∈ [0, curves]."""+ i = np.clip(np.floor(u).astype(int), 0, len(curves) - 1)+ t = (u - i)[:, None]+ c = curves[i]+ return (+ (1 - t) ** 3 * c[:, 0]+ + 3 * (1 - t) ** 2 * t * c[:, 1]+ + 3 * (1 - t) * t**2 * c[:, 2]+ + t**3 * c[:, 3]+ )+++def _screen(points: np.ndarray, view: np.ndarray, size: tuple[int, int]) -> np.ndarray:+ """Scene points on screen, in pixels from the top left, through a view (world → clip)."""+ clip = points @ view[:, :3].T + view[:, 3]+ ndc = clip[:, :2] / clip[:, 3:4]+ width, height = size+ return np.column_stack([(ndc[:, 0] + 1) / 2 * width, (1 - ndc[:, 1]) / 2 * height])+++def _breakpoints(values: np.ndarray, tolerance: float) -> list[int]:+ """The frames to keep of a series (frames × dimensions) for the lines between them to+ stay within `tolerance` of every frame (Ramer–Douglas–Peucker)."""+ keep = {0, len(values) - 1}+ stack = [(0, len(values) - 1)]+ while stack:+ a, b = stack.pop()+ if b - a < 2:+ continue+ t = (np.arange(a + 1, b) - a) / (b - a)+ line = values[a] + t[:, None] * (values[b] - values[a])+ error = np.abs(values[a + 1 : b] - line).max(axis=1)+ worst = int(np.argmax(error))+ if error[worst] > tolerance:+ k = a + 1 + worst+ keep.add(k)+ stack += [(a, k), (k, b)]+ return sorted(keep)+++def _pair(p: np.ndarray, digits: int) -> str:+ return f"{_number(p[0], digits)} {_number(p[1], digits)}"+++def _number(v: float, digits: int) -> str:+ text = f"{v:.{digits}f}"+ if "." in text:+ text = text.rstrip("0").rstrip(".")+ return "0" if text in ("-0", "") else textdiff --git a/scripts/docs/gallery.py b/scripts/docs/gallery.pynew file mode 100644index 00000000..fbd76b02--- /dev/null+++ b/scripts/docs/gallery.py@@ -0,0 +1,159 @@+"""The Gallery: the example films (`examples/`), a card each on its first page, and a page+each.++`python -m scripts.docs.gallery` writes `docs/content/gallery/` (not committed) from+`examples/` alone, before `docs.examples` renders the examples. The examples' README says+what the Gallery says: its introduction's first paragraph opens it, its groups are the+Gallery's, in their order, and its line for a film, `- [Title](file.py): What it shows.`,+gives the film its title, its card's sentence (the line's first) and its page's words. A+film's page holds its file, which `docs.examples` renders as it renders every example, and+`fence` folds under the film; its card shows the film's still, named by its scene+(`docs/films.py`).+"""++import json+import re+import shutil+import sys+from dataclasses import dataclass+from pathlib import Path++from docs.examples import Example++ROOT = Path(__file__).parents[2]+EXAMPLES = ROOT / "examples"+GALLERY = ROOT / "docs" / "content" / "gallery"+# a film's line in the README: its title, its file, and what it shows, on as many lines as it+# wraps to+LINE = re.compile(+ r"^- \[(?P<title>[^\]]+)\]\((?P<name>\w+)\.py\): (?P<words>.+?)(?=^- |\Z)",+ re.MULTILINE | re.DOTALL,+)+++@dataclass(frozen=True)+class Film:+ """An example film: its file's name (`hopf_fibration`), its title and what it shows."""++ name: str+ title: str+ words: str++ @property+ def page(self) -> str:+ """Its page's file in the Gallery: `hopf-fibration.md`."""+ return f"{self.name.replace('_', '-')}.md"++ @property+ def lead(self) -> str:+ """What its card says: the first sentence of what it shows."""+ first, stop, _ = self.words.partition(". ")+ return first + "." if stop else self.words++ @property+ def code(self) -> str:+ return (EXAMPLES / f"{self.name}.py").read_text(encoding="utf-8").rstrip()++ @property+ def scene(self) -> str:+ """The scene its film is made of, whose name the card gives its still."""+ scene = Example(self.code).scene+ if scene is None:+ sys.exit(f"examples/{self.name}.py defines no scene")+ return scene+++def readme() -> tuple[str, list[tuple[str, list[Film]]]]:+ """The README's introduction (its first paragraph) and its groups: a title each, and its+ films, in order. Every example must be in one, once."""+ text = (EXAMPLES / "README.md").read_text(encoding="utf-8")+ intro, *sections = re.split(r"^## ", text, flags=re.MULTILINE)+ groups = []+ for section in sections:+ title, _, body = section.partition("\n")+ films = [+ Film(found["name"], found["title"], " ".join(found["words"].split()))+ for found in LINE.finditer(body)+ ]+ groups.append((title.strip(), films))+ listed = [film.name for _, films in groups for film in films]+ files = sorted(path.stem for path in EXAMPLES.glob("*.py"))+ if sorted(listed) != files:+ sys.exit(+ "examples/README.md must list every example once, as `- [Title](file.py): …`: "+ f"unlisted {sorted(set(files) - set(listed))},"+ f" missing {sorted(set(listed) - set(files))},"+ f" twice {sorted({n for n in listed if listed.count(n) > 1})}"+ )+ first = intro.partition("\n")[2].strip().split("\n\n")[0]+ return " ".join(first.split()), groups+++def front(**fields: str | list[str]) -> str:+ """A page's front matter (JSON's strings are YAML's)."""+ lines = []+ for key, value in fields.items():+ if isinstance(value, list):+ lines += [f"{key}:", *(f" - {item}" for item in value)]+ else:+ lines.append(f"{key}: {json.dumps(value, ensure_ascii=False)}")+ return "---\n" + "\n".join(lines) + "\n---\n\n"+++def card(film: Film) -> str:+ """A film's card: its still, its title, and its first sentence, the card a link to it."""+ return (+ f"- \n\n"+ f" [**{film.title}**]({film.page})\n\n"+ f" {film.lead}\n"+ )+++def index(intro: str, groups: list[tuple[str, list[Film]]]) -> str:+ """The Gallery's first page: the README's introduction, and each group's cards."""+ sections = [+ f"## {title}\n\n"+ '<div class="grid cards mx-cards" markdown>\n\n'+ + "\n".join(card(film) for film in films)+ + "\n</div>\n"+ for title, films in groups+ ]+ return (+ front(title="Gallery", description=intro, hide=["navigation", "toc"])+ + f"# Gallery\n\n{intro}\n\n"+ + "\n".join(sections)+ )+++def page(film: Film) -> str:+ """A film's page: its title, what it shows, then the film, its code folded under it."""+ return (+ front(title=film.title, description=film.words, hide=["toc"])+ + f"# {film.title}\n\n{film.words}\n\n"+ + f'```python title="examples/{film.name}.py" fold\n{film.code}\n```\n'+ )+++def nav(groups: list[tuple[str, list[Film]]]) -> str:+ """The Gallery's navigation: its first page, then each group's films."""+ lines = ["nav:", " - All films: index.md"]+ for title, films in groups:+ lines.append(f" - {json.dumps(title)}:")+ lines += [f" - {film.page}" for film in films]+ return "\n".join(lines) + "\n"+++def main() -> None:+ intro, groups = readme()+ shutil.rmtree(GALLERY, ignore_errors=True)+ GALLERY.mkdir(parents=True)+ (GALLERY / "index.md").write_text(index(intro, groups), encoding="utf-8")+ (GALLERY / ".nav.yml").write_text(nav(groups), encoding="utf-8")+ for _, films in groups:+ for film in films:+ (GALLERY / film.page).write_text(page(film), encoding="utf-8")+ print(f"{sum(len(films) for _, films in groups)} films in {len(groups)} groups")+++if __name__ == "__main__":+ main()diff --git a/scripts/docs/rates.py b/scripts/docs/rates.pynew file mode 100644index 00000000..1282ae04--- /dev/null+++ b/scripts/docs/rates.py@@ -0,0 +1,56 @@+"""The rate functions' curves, which the docs' rate function explorer draws (`.mx-rates`, in+`docs/content/javascripts/manimgx.js`).++`python -m scripts.docs.rates` writes `docs/content/javascripts/rate-functions.json`, which is+committed, so that the site needs no step to build it: every rate function of+`manimgx.animation.easing`, by name, as its progress at `SAMPLES` times evenly spread from 0+to 1, one function a line.+"""++import inspect+import json+from pathlib import Path++from manimgx.animation import easing+from manimgx.typing import RateFunc++ROOT = Path(__file__).parents[2]+DATA = ROOT / "docs" / "content" / "javascripts" / "rate-functions.json"+# enough that a curve keeps its swings (elastic, bounce, wiggle) when drawn as straight lines+SAMPLES = 121+++def functions() -> dict[str, RateFunc]:+ """Every rate function of the module, by name: each function of the time that gives+ the progress, not those that make one from another (`squish_rate_func`)."""+ return {+ name: function+ for name in easing.__all__+ if inspect.isfunction(function := getattr(easing, name))+ and inspect.signature(function).return_annotation is float+ }+++def sampled(function: RateFunc) -> list[float]:+ """A rate function's progress at each sample's time, to 4 decimals (0 and 1 as+ written: `0`, not `0.0`)."""+ values = [round(function(i / (SAMPLES - 1)), 4) + 0.0 for i in range(SAMPLES)]+ return [int(value) if value.is_integer() else value for value in values]+++def text() -> str:+ """The data file's text."""+ lines = (+ f" {json.dumps(name)}: {json.dumps(sampled(function), separators=(',', ':'))}"+ for name, function in functions().items()+ )+ return "{\n" + ",\n".join(lines) + "\n}\n"+++def main() -> None:+ DATA.write_text(text(), encoding="utf-8")+ print(f"{len(functions())} rate functions, {SAMPLES} samples each")+++if __name__ == "__main__":+ main()diff --git a/scripts/docs/reference.py b/scripts/docs/reference.pynew file mode 100644index 00000000..555e51c2--- /dev/null+++ b/scripts/docs/reference.py@@ -0,0 +1,35 @@+"""The command line's reference, from its Typer app: the one page of the API reference that is+generated.++`python -m scripts.docs.reference` writes `docs/content/reference/rendering/command-line.md`+(not committed), so the page always says what the app does. The rest of the reference is+written by hand, in `docs/content/reference/`: its story in prose, and the API in it as+mkdocstrings' `:::` blocks, which render each object from its docstring.+`tests/docs/test_reference.py` keeps the two together: every name the package documents is+on a page, once, and every name a page shows is still in the package.+"""++import subprocess+import sys+from pathlib import Path++REPOSITORY = Path(__file__).parents[2]+PAGE = REPOSITORY / "docs" / "content" / "reference" / "rendering" / "command-line.md"+++def main() -> None:+ PAGE.parent.mkdir(parents=True, exist_ok=True)+ subprocess.run(+ [+ *(sys.executable, "-m", "typer", "manimgx.cli", "utils", "docs"),+ *("--name", "manimgx", "--title", "Command line"),+ *("--output", str(PAGE)),+ ],+ check=True,+ capture_output=True,+ )+ print(f"wrote {PAGE.relative_to(REPOSITORY)}")+++if __name__ == "__main__":+ main()diff --git a/src/manimgx/__init__.py b/src/manimgx/__init__.pyindex 148f5587..56d45703 100644--- a/src/manimgx/__init__.py+++ b/src/manimgx/__init__.py@@ -69,7 +69,7 @@ from manimgx.drawing.geometry import (z_to_vector,)from manimgx.drawing.paint import *-from manimgx.drawing.paint import stretch_array as stretch_array_to_length+from manimgx.drawing.paint import stretch_array_to_lengthfrom manimgx.mobject import (ComplexValueTracker,Group,diff --git a/tests/docs/test_deprecated.py b/tests/docs/test_deprecated.pynew file mode 100644index 00000000..8f976cf0--- /dev/null+++ b/tests/docs/test_deprecated.py@@ -0,0 +1,117 @@+"""What is deprecated is left out of the API reference (`docs/deprecated.py`): each class,+function or property decorated with `@deprecated`, in every form ty flags, and nothing else."""++from pathlib import Path++import pytest++GROUP = """+from typing import TYPE_CHECKING+from warnings import deprecated++from typing_extensions import deprecated as backported++__all__ = ["Group", "VGroup", "Moving", "Zoomed", "stretch", "stretch_to", "squash"]+++class Group:+ def arrange(self) -> "Group":+ return self++ @deprecated("Use arrange.", category=None)+ def arrange_submobjects(self) -> "Group":+ return self.arrange()++ @property+ def width(self) -> float:+ return 1.0++ @width.setter+ def width(self, value: float) -> None: ...++ @property+ @deprecated("Use width.", category=None)+ def old_width(self) -> float:+ return self.width+++if TYPE_CHECKING:++ @deprecated("Use Group.", category=None)+ class VGroup(Group): ...++else:+ VGroup = Group+++@backported("Use Group.", category=None)+class Moving(Group): ...+++class Zoomed(Moving): ...+++def stretch() -> None: ...+++@deprecated("Use stretch.", category=None)+def stretch_to() -> None:+ stretch()+++squash = deprecated("Use stretch.", category=None)(stretch)+"""+++def kept(tmp_path: Path) -> dict[str, set[str]]:+ """The names griffe keeps of a package, with the extension: its module's, its class's,+ and its own that still resolve (as the reference's exports do)."""+ pytest.importorskip("griffe") # the docs group's+ import griffe+ from docs.deprecated import Deprecated++ folder = tmp_path / "shapes"+ folder.mkdir()+ (folder / "__init__.py").write_text(+ "from shapes.group import *\nfrom shapes.group import stretch_to as stretched\n",+ encoding="utf-8",+ )+ (folder / "group.py").write_text(GROUP, encoding="utf-8")+ package = griffe.load(+ "shapes",+ search_paths=[tmp_path],+ extensions=griffe.load_extensions(Deprecated),+ resolve_aliases=True,+ )+ assert isinstance(package, griffe.Module)+ group = package["group"]+ return {+ "group": set(group.members),+ "Group": set(group["Group"].members),+ "shapes": {+ name+ for name, member in package.members.items()+ if not isinstance(member, griffe.Alias) or member.resolved+ },+ }+++def test_each_form_ty_flags_is_left_out(tmp_path: Path) -> None:+ names = kept(tmp_path)+ assert "arrange_submobjects" not in names["Group"] # a method's second name+ assert "old_width" not in names["Group"] # a property's, decorated on its getter+ assert "stretch_to" not in names["group"] # a function's+ # a deprecated class stays where it is defined, for the classes made from it (Zoomed),+ # but the package names none of them, by `import *` or by name+ assert {"VGroup", "Moving"} <= names["group"]+ assert {"VGroup", "Moving", "stretch_to", "stretched"}.isdisjoint(names["shapes"])+++def test_what_to_use_instead_stays(tmp_path: Path) -> None:+ names = kept(tmp_path)+ assert {"arrange", "width"} <= names["Group"]+ assert {"Group", "stretch"} <= names["group"] & names["shapes"]+ # a subclass isn't deprecated with its base, as `__deprecated__` would have it+ assert "Zoomed" in names["group"] & names["shapes"]+ # an assignment isn't deprecated, to ty or here: the decorator marks a definition+ assert "squash" in names["group"]diff --git a/tests/docs/test_examples.py b/tests/docs/test_examples.pynew file mode 100644index 00000000..10ebabe1--- /dev/null+++ b/tests/docs/test_examples.py@@ -0,0 +1,15 @@+"""The docs' examples, as the site's build renders them (`docs/examples.py`): the build has+no voice's key (its workflow has none), so a narrated example says what `docs/voice/` keeps."""++import pytest+from docs import examples+++def test_a_narrated_example_says_what_docs_voice_keeps(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.delenv("FAL_KEY", raising=False)+ narrated = [e for e in examples.examples() if ".say(" in e.code]+ assert narrated+ for example in narrated:+ examples.load(example)().render() # its frames counted, not drawndiff --git a/tests/docs/test_gallery.py b/tests/docs/test_gallery.pynew file mode 100644index 00000000..4d48e2a1--- /dev/null+++ b/tests/docs/test_gallery.py@@ -0,0 +1,43 @@+"""The Gallery (`scripts/docs/gallery.py`) is `examples/` as its README tells it: a card for+each film on its first page, in the README's groups, and a page for each film, with what it+shows and its code, folded under the film."""++import re++from scripts.docs import gallery+++def test_every_example_has_a_page_with_its_code() -> None:+ _, groups = gallery.readme()+ films = [film for _, found in groups for film in found]+ assert sorted(film.name for film in films) == sorted(+ path.stem for path in gallery.EXAMPLES.glob("*.py")+ )+ for film in films:+ page = gallery.page(film)+ assert f"\n# {film.title}\n\n{film.words}\n" in page, film.name+ assert page.count(f'```python title="examples/{film.name}.py" fold\n') == 1+++def test_every_film_has_a_card_that_links_its_page() -> None:+ intro, groups = gallery.readme()+ index = gallery.index(intro, groups)+ for title, films in groups:+ assert index.count(f"\n## {title}\n") == 1+ for film in films:+ card = (+ f"- \n\n [**{film.title}**]({film.page})\n\n"+ )+ assert index.count(card) == 1, film.name+ nav = gallery.nav(groups)+ assert all(nav.count(f" - {film.page}\n") == 1 for _, f in groups for film in f)+++def test_a_card_says_one_sentence() -> None:+ """A card's sentence is the first of what the film shows: short, and whole."""+ _, groups = gallery.readme()+ for _, films in groups:+ for film in films:+ assert re.fullmatch(r"[A-Z0-9√].*[.?!]", film.lead), film.name+ assert len(film.lead.split()) <= 24, film.name+ assert film.words.startswith(film.lead), film.namediff --git a/tests/docs/test_hidden.py b/tests/docs/test_hidden.pynew file mode 100644index 00000000..017a2b45--- /dev/null+++ b/tests/docs/test_hidden.py@@ -0,0 +1,77 @@+"""No example teaches a name manimgx hides (`@deprecated`): not the pages', the README's, the+docstrings' nor the example films' (`examples/`, which the Gallery shows). ty checks each with+`deprecated` an error. The example of a hidden object's own docstring is not shown, and is+not checked."""++import ast+import subprocess+import sys+from functools import cache+from pathlib import Path++import pytest++ROOT = Path(__file__).parents[2]+++@cache+def hidden_spans(path: Path) -> list[tuple[int, int]]:+ """The lines of each definition a module decorates with `@deprecated`."""+ tree = ast.parse(path.read_text(encoding="utf-8"))+ return [+ (node.lineno, node.end_lineno or node.lineno)+ for node in ast.walk(tree)+ if isinstance(node, ast.FunctionDef | ast.ClassDef)+ and any("deprecated" in ast.unparse(d) for d in node.decorator_list)+ ]+++def shown(where: str) -> bool:+ """Whether an example is shown: one on a page, or in the docstring of what isn't hidden."""+ file, _, line = where.rpartition(":")+ path = ROOT / file+ if not file.startswith("src/"):+ return True+ return not any(a <= int(line) <= b for a, b in hidden_spans(path))+++def test_no_example_uses_a_hidden_name(tmp_path: Path) -> None:+ pytest.importorskip("markdown") # the docs group's, which docs.examples imports+ from docs import examples++ for n, example in enumerate(examples.examples()):+ if shown(example.where):+ (tmp_path / f"example_{n}.py").write_text(+ f"# {example.where}\n{example.code}", encoding="utf-8"+ )+ for film in sorted((ROOT / "examples").glob("*.py")):+ (tmp_path / f"film_{film.name}").write_text(+ f"# examples/{film.name}\n{film.read_text(encoding='utf-8')}",+ encoding="utf-8",+ )+ ty = Path(sys.executable).parent / "ty"+ done = subprocess.run(+ [+ str(ty),+ "check",+ "--python",+ sys.prefix,+ "--output-format",+ "concise",+ "--error",+ "deprecated",+ str(tmp_path),+ ],+ capture_output=True,+ text=True,+ check=False,+ )+ uses = []+ for line in done.stdout.splitlines():+ if "[deprecated]" in line:+ file, number = line.split(":")[:2]+ source = (tmp_path / Path(file).name).read_text(encoding="utf-8")+ uses.append(+ f"{source.splitlines()[0][2:]} (+{number}): {line.split('] ', 1)[1]}"+ )+ assert not uses, "examples that use a hidden name:\n" + "\n".join(uses)diff --git a/tests/docs/test_links.py b/tests/docs/test_links.pynew file mode 100644index 00000000..2b54497e--- /dev/null+++ b/tests/docs/test_links.py@@ -0,0 +1,50 @@+"""The README, included as the Welcome page, reaches the site's own images and pages on the+site it is on (`docs/links.py`), so `just serve-docs` shows the images it built."""++from pathlib import Path++import pytest++README = Path(__file__).parents[2] / "README.md"+++def test_the_readme_reaches_the_site_it_is_on() -> None:+ markdown = pytest.importorskip("markdown") # the docs group's+ from docs import links++ html = markdown.markdown(+ README.read_text(encoding="utf-8"),+ extensions=["md_in_html", "pymdownx.superfences", links.makeExtension()],+ )+ site = f"https://{links.HOST}"+ for attribute in ("src", "srcset", "href", "poster"):+ assert f'{attribute}="{site}' not in html+ # the banner, the logo on each ground+ assert 'srcset="/showcase/logo-dark.svg"' in html+ assert 'src="/showcase/logo-light.svg"' in html+ # the wall's films, and the scene's film on each ground+ assert 'srcset="/showcase/hopf_fibration.avif"' in html # on a low-density screen+ assert 'src="/showcase/[email protected]"' in html+ assert 'srcset="/films/readme-Hopf.svg"' in html+ assert 'src="/films/readme-Hopf-light.svg#readme"' in html+ # a URL written as text, which an agent is told to follow, stays as it is+ assert f"Follow {site}/llms.txt" in html+++def test_only_the_site_s_own_urls_become_paths() -> None:+ pytest.importorskip("markdown")+ from docs import links++ site = f"https://{links.HOST}"+ tags = (+ f'<a href="{site}">'+ f"<img src='{site}/a.svg#readme' srcset=\"{site}/a.svg 1x, {site}/b.svg 2x\">"+ f'<img src="https://img.shields.io/badge/docs-{links.HOST}-blue">'+ f'<code><img src="{site}/c.svg"></code>'+ )+ assert links.paths(tags) == (+ '<a href="/">'+ "<img src='/a.svg#readme' srcset=\"/a.svg 1x, /b.svg 2x\">"+ f'<img src="https://img.shields.io/badge/docs-{links.HOST}-blue">'+ f'<code><img src="{site}/c.svg"></code>'+ )diff --git a/tests/docs/test_llms.py b/tests/docs/test_llms.pynew file mode 100644index 00000000..ec558b3f--- /dev/null+++ b/tests/docs/test_llms.py@@ -0,0 +1,55 @@+"""The site for agents (Zensical's llmstxt plugin, set in docs/zensical.toml). Its primer,+which opens llms.txt, is written by hand, so these check it against the API: its scene runs,+and every name it teaches exists. And every page is the plugin's: it writes a page's Markdown,+which the page's Copy as Markdown button copies, for the pages its sections name only."""++import re+import tomllib+from fnmatch import fnmatchcase+from pathlib import Path++import manimgx as m++CONFIG = Path(__file__).parents[2] / "docs" / "zensical.toml"+LLMSTXT = tomllib.loads(CONFIG.read_text(encoding="utf-8"))["project"]["plugins"][+ "llmstxt"+]+PRIMER: str = LLMSTXT["markdown_description"]+++def test_its_scenes_run() -> None:+ blocks = re.findall(r"^```python\n(.*?)^```", PRIMER, re.MULTILINE | re.DOTALL)+ assert blocks+ for code in blocks:+ namespace: dict[str, object] = {}+ exec(compile(code, str(CONFIG), "exec"), namespace)+ scenes = [+ scene+ for scene in namespace.values()+ if isinstance(scene, type) and issubclass(scene, m.Scene)+ ]+ assert scenes, code+ for scene in scenes:+ if scene is not m.Scene:+ scene().render() # its frames counted, not drawn+++def test_its_names_exist() -> None:+ # `m.Circle`, `m.UP`; `Square`, `Brace(mob, m.DOWN)`; `.next_to(other, m.RIGHT)`+ for name in re.findall(r"\bm\.([A-Za-z_]\w*)", PRIMER):+ assert hasattr(m, name), f"m.{name}"+ for name in re.findall(r"`([A-Z]\w*)[(`]", PRIMER):+ assert hasattr(m, name), name+ for name in re.findall(r"`\.(\w+)\(", PRIMER):+ assert hasattr(m.VMobject, name), f".{name}"+++def test_every_page_has_its_markdown() -> None:+ content = CONFIG.parent / "content"+ patterns: list[str] = [+ pattern for patterns in LLMSTXT["sections"].values() for pattern in patterns+ ]+ pages = [page.relative_to(content).as_posix() for page in content.rglob("*.md")]+ assert "index.md" in pages+ for page in pages:+ assert any(fnmatchcase(page, pattern) for pattern in patterns), pagediff --git a/tests/docs/test_overrides.py b/tests/docs/test_overrides.pynew file mode 100644index 00000000..be0d12f7--- /dev/null+++ b/tests/docs/test_overrides.py@@ -0,0 +1,96 @@+"""The theme's overrides, copied from Zensical, and what they add: the header's lockup (the logo+and "by Academa" below it, each its own link) and the footer's band, Academa's. Each copy is+checked against what it copies: Zensical's templates, and the numbers of the byline's SVG+(`scripts/showcase/logo.py`) that the stylesheet repeats. And the band offers the newsletter+only with the door its field posts to."""++import re+import tomllib+from pathlib import Path++import pytest++DOCS = Path(__file__).parents[2] / "docs"+CONFIG = tomllib.loads((DOCS / "zensical.toml").read_text(encoding="utf-8"))["project"]+PARTIALS = DOCS / "overrides" / "partials"+IMAGES = DOCS / "content" / "images"+STYLESHEET = DOCS / "content" / "stylesheets" / "manimgx.css"+++def lines(path: Path) -> list[str]:+ """A template's lines, without its first comment and indentation."""+ text = re.sub(r"\A\{#-.*?-#\}\n", "", path.read_text(encoding="utf-8"), flags=re.S)+ return [line.strip() for line in text.splitlines()]+++def zensicals(name: str) -> list[str]:+ """One of Zensical's partials, as `lines` reads it."""+ zensical = pytest.importorskip("zensical") # the docs group's+ return lines(Path(zensical.__file__).parent / "templates" / "partials" / name)+++def view(name: str) -> list[float]:+ """An SVG's viewBox: x, y, width, height."""+ box = re.search(r'viewBox="([^"]+)"', (IMAGES / name).read_text(encoding="utf-8"))+ assert box, name+ return [float(v) for v in box.group(1).split()]+++def test_the_header_is_zensicals_but_for_the_lockup() -> None:+ theirs, ours = zensicals("header.html"), lines(PARTIALS / "header.html")+ # the lockup: a box around Zensical's link to the home page, and the byline after it+ start = ours.index('<div class="mx-lockup">')+ byline = next(i for i, line in enumerate(ours) if "mx-byline" in line)+ end = ours.index("</div>", byline)+ assert ours[:start] + ours[start + 1 : byline] + ours[end + 1 :] == theirs+++def test_the_footer_is_zensicals_but_for_the_band() -> None:+ theirs, ours = zensicals("footer.html"), lines(PARTIALS / "footer.html")+ # the band, where Zensical's copyright and social links were, before the footer ends+ meta = theirs.index('<div class="md-footer-meta md-typeset">')+ end = theirs.index("</footer>")+ assert ours == [+ *theirs[:meta],+ '{% include "partials/academa.html" %}',+ *theirs[end:],+ ]+++def test_the_stylesheet_places_the_byline_where_its_svg_says() -> None:+ _, _, _, logo = view("logo-light.svg")+ x, y, _, height = view("byline-light.svg")+ assert view("byline-dark.svg") == view("byline-light.svg")+ assert x == 0 # from the logo's left edge+ css = STYLESHEET.read_text(encoding="utf-8")+ assert f"calc(var(--mx-logo) / {logo:g})" in css+ assert f"calc(({y:g} - {logo:g}) * var(--mx-unit))" in css+ assert f"calc({height:g} * var(--mx-unit))" in css+++def band(extra: dict[str, object]) -> str:+ """The footer's band, rendered with the site's settings and this `extra`."""+ jinja2 = pytest.importorskip("jinja2") # the docs group's+ zensical = pytest.importorskip("zensical")+ templates = [DOCS / "overrides", Path(zensical.__file__).parent / "templates"]+ environment = jinja2.Environment(loader=jinja2.FileSystemLoader(templates))+ environment.filters["url"] = lambda path: path+ config = {**CONFIG, "extra": extra}+ return environment.get_template("partials/academa.html").render(config=config)+++def test_the_newsletter_field_posts_to_its_door() -> None:+ door = CONFIG["extra"]["newsletter"]+ assert door.startswith("https://")+ html = band(CONFIG["extra"])+ assert f'<form class="mx-footer__subscribe" method="post" action="{door}">' in html+ assert 'class="mx-footer__answer" role="status"' in html+ # the privacy policy that covers what the field collects+ assert 'href="https://academa.ai/privacy"' in html+++def test_without_a_door_the_band_offers_no_newsletter() -> None:+ html = band({key: v for key, v in CONFIG["extra"].items() if key != "newsletter"})+ assert "<form" not in html+ assert "academa.ai/privacy" not in html+ assert "Join the Discord" in htmldiff --git a/tests/docs/test_previews.py b/tests/docs/test_previews.pynew file mode 100644index 00000000..8b78e4d9--- /dev/null+++ b/tests/docs/test_previews.py@@ -0,0 +1,44 @@+"""A reference to the API previews its target on hover, as a link does (`docs/previews.py`):+each `<autoref>` tag of a rendered page is marked, once, and the text is left as it is. A+card's link previews nothing: the card shows what the preview would."""++import pytest+++def test_each_reference_is_marked_once() -> None:+ pytest.importorskip("markdown") # the docs group's+ from docs import previews++ page = (+ '<p><autoref identifier="manimgx.Scene">Scene</autoref> and '+ '<code><autoref identifier="manimgx.Mobject" optional hover>Mobject</autoref></code>'+ "</p>"+ )+ once = previews.marked(page)+ assert once.count("<autoref data-preview ") == 2+ # a docstring's references pass twice: as the docstring is converted, then in its page+ assert previews.marked(once) == once+++def test_text_is_left_as_it_is() -> None:+ pytest.importorskip("markdown")+ from docs import previews++ # a code block's tag is text: its `<` is escaped+ code = "<pre><code><autoref identifier="x">y</autoref></code></pre>"+ assert previews.marked(code) == code+ # a tag whose name only starts like it+ other = '<autorefs identifier="x"></autorefs>'+ assert previews.marked(other) == other+++def test_a_cards_link_previews_nothing() -> None:+ pytest.importorskip("markdown")+ from docs import previews++ card = (+ '<div class="grid cards mx-cards">\n<ul>\n<li>\n<p><img src="/films/A.webp" /></p>\n'+ '<p><a data-preview="" href="a/"><strong>A</strong></a></p>\n</li>\n</ul>\n</div>'+ )+ link = '<p><a data-preview="" href="b/">B</a></p>'+ assert previews.marked(card + link) == card.replace(' data-preview=""', "") + linkdiff --git a/tests/docs/test_rates.py b/tests/docs/test_rates.pynew file mode 100644index 00000000..c1010505--- /dev/null+++ b/tests/docs/test_rates.py@@ -0,0 +1,31 @@+"""The rate function explorer's curves (`docs/content/javascripts/rate-functions.json`, which+`scripts/docs/rates.py` writes) are manimgx's rate functions: the committed file is what the+script writes now, and every function a page names in an explorer (`data-rates`) is in it."""++import json+import re+from pathlib import Path++from scripts.docs import rates++PAGES = Path(__file__).parents[2] / "docs" / "content"+++def test_the_curves_are_the_rate_functions_now() -> None:+ written = rates.DATA.read_text(encoding="utf-8")+ assert written == rates.text(), "run `python -m scripts.docs.rates`"+++def test_every_function_an_explorer_names_has_a_curve() -> None:+ curves = json.loads(rates.DATA.read_text(encoding="utf-8"))+ named = [+ name+ for page in PAGES.rglob("*.md")+ for names in re.findall(+ r'data-rates="([^"]*)"', page.read_text(encoding="utf-8")+ )+ for name in names.split()+ ]+ assert named+ for name in named:+ assert name in curves, namediff --git a/tests/docs/test_reference.py b/tests/docs/test_reference.pynew file mode 100644index 00000000..5248408e--- /dev/null+++ b/tests/docs/test_reference.py@@ -0,0 +1,311 @@+"""The API reference shows what the package documents, once, and no more+(`docs/content/reference/`).++Its pages are written by hand: their story in prose, and the API as mkdocstrings' `:::`+blocks, which render each object from its docstring. So nothing generates the list of what+they show, and these tests keep it whole. What must be shown: every name `import manimgx as+m` exports, and every documented member of an exported class: its own, and those it inherits+from bases the package doesn't export (a private `_Grid`'s), down to its first exported base.+Not what is `@deprecated` (`docs/deprecated.py` takes it out as griffe loads the package): a+deprecated class stays in its module, for the classes made from it, but leaves the reference+with its members, what those classes inherit from it among them. Nor what is listed in+`UNDOCUMENTED`: what can't carry the decorator (an attribute, a constant, a type alias) and no+scene needs.+"""++import re+from pathlib import Path++import pytest++griffe = pytest.importorskip("griffe") # the docs group's++ROOT = Path(__file__).parents[2]+PAGES = ROOT / "docs" / "content" / "reference"+DIRECTIVE = re.compile(r"^:::\s+(\S+)\s*\n((?:[ \t]+.*\n|\n)*)", re.MULTILINE)+CARDS = re.compile(+ r'<div class="grid cards mx-cards" markdown>\n(.*?)\n</div>', re.DOTALL+)++# What the package documents for its own developers, and the reference leaves out+UNDOCUMENTED = {+ # a mobject's state, which its methods and the style keywords read and set+ *(+ f"Mobject.{name}"+ for name in [+ "background_stroke_rgbas",+ "background_stroke_width",+ "cap_style",+ "defaults",+ "dim",+ "fill_rgbas",+ "joint_type",+ "material",+ "paint",+ "shade_in_3d",+ "shared",+ "sheen_direction",+ "sheen_factor",+ "stroke_rgbas",+ "style",+ "updaters",+ "updating_suspended",+ "z_index_group",+ ]+ ),+ *(+ f"VMobject.{name}"+ for name in [+ "gradient_frame",+ "make_smooth_after_applying_functions",+ "n_points_per_curve",+ "pre_function_handle_to_anchor_scale_factor",+ "tolerance_for_point_equality",+ ]+ ),+ "Axes.num_sampled_graph_points_per_tick",+ "Animation.defaults",+ "Scene.clock",+ "Scene.updaters",+ # Manim CE's defaults and units, as constants+ *(+ f"manimgx.{name}"+ for name in [+ "DEFAULT_ARROW_TIP_LENGTH",+ "DEFAULT_DASH_LENGTH",+ "DEFAULT_DOT_RADIUS",+ "DEFAULT_FONT_SIZE",+ "DEFAULT_POINTWISE_FUNCTION_RUN_TIME",+ "DEFAULT_POINT_DENSITY_1D",+ "DEFAULT_POINT_DENSITY_2D",+ "DEFAULT_SMALL_DOT_RADIUS",+ "DEFAULT_STROKE_WIDTH",+ "DEFAULT_WAIT_TIME",+ "SCALE_FACTOR_PER_FONT_POINT",+ "START_X",+ "START_Y",+ "Pixels",+ "Degrees",+ "Munits",+ ]+ ),+ # the types of annotations+ *(+ f"manimgx.{name}"+ for name in [+ "Coefficients",+ "Colorscale",+ "Floats",+ "ParsableManimColor",+ "RateFunction",+ "Step",+ ]+ ),+}++[email protected](scope="module")+def package() -> "griffe.Module":+ from docs.deprecated import Deprecated++ loaded = griffe.load(+ "manimgx",+ search_paths=[ROOT / "src"],+ extensions=griffe.load_extensions(Deprecated),+ resolve_aliases=True,+ resolve_external=False,+ )+ assert isinstance(loaded, griffe.Module)+ return loaded+++def real(obj: "griffe.Object | griffe.Alias") -> "griffe.Object | None":+ try:+ return obj.final_target if isinstance(obj, griffe.Alias) else obj+ except (griffe.AliasResolutionError, griffe.CyclicAliasError):+ return None+++def resolve(package: "griffe.Module", identifier: str) -> "griffe.Object | None":+ try:+ return real(package[identifier.removeprefix("manimgx.")])+ except KeyError:+ return None+++def documented(obj: "griffe.Object") -> bool:+ return bool(obj.docstring and obj.docstring.value.strip())+++def members(cls: "griffe.Class", stop: set[str]) -> dict[str, "griffe.Object"]:+ """A class's documented public members, by name: its own, then its bases' down to the+ first in `stop`, or the first deprecated."""+ from docs.deprecated import deprecated++ found: dict[str, griffe.Object] = {}+ for owner in [cls, *cls.mro()]:+ if owner is not cls and (owner.path in stop or deprecated(owner)):+ break+ for name, member in owner.members.items():+ target = real(member)+ if name.startswith("_") or name in found or target is None:+ continue+ if target.path.startswith("manimgx") and documented(target):+ found[name] = target+ return found+++def required(package: "griffe.Module") -> tuple[dict[str, str], set[str]]:+ """What must be shown, by path, each with a label (`manimgx.Circle`,+ `Circle.surround`); and the exported classes' paths."""+ need: dict[str, str] = {}+ classes = []+ for name, member in package.members.items():+ target = real(member)+ if name.startswith("_") or target is None or target.is_module:+ continue+ if target.path.startswith("manimgx."):+ need.setdefault(target.path, f"manimgx.{name}")+ if isinstance(target, griffe.Class):+ classes.append(target)+ exported = {cls.path for cls in classes}+ for cls in classes:+ for name, member in members(cls, exported).items():+ need.setdefault(member.path, f"{cls.name}.{name}")+ return need, exported+++def shown(package: "griffe.Module") -> dict[str, list[str]]:+ """What the pages render, by path: each with the pages that render it."""+ seen: dict[str, list[str]] = {}+ for page in sorted(PAGES.rglob("*.md")):+ where = str(page.relative_to(PAGES))+ for match in DIRECTIVE.finditer(page.read_text(encoding="utf-8")):+ obj = resolve(package, match[1])+ assert obj is not None, f"{where}: {match[1]} is not in the package"+ seen.setdefault(obj.path, []).append(where)+ if not isinstance(obj, griffe.Class):+ continue+ options = match[2]+ listed = re.search(r"(?<!inherited_)members:\s*(false|\[.*?\])", options)+ own = {+ name: target+ for name, member in obj.members.items()+ if not name.startswith("_")+ and (target := real(member)) is not None+ and documented(target)+ }+ if listed is None:+ chosen = own+ elif listed[1] == "false":+ chosen = {}+ else:+ chosen = {n: own[n] for n in re.findall(r"\w+", listed[1]) if n in own}+ inherited = re.search(r"inherited_members:\s*(\[.*?\])", options)+ if inherited:+ every = members(obj, set())+ chosen |= {n: every[n] for n in re.findall(r"\w+", inherited[1])}+ for member in chosen.values():+ seen.setdefault(member.path, []).append(where)+ return seen+++def palette_shows(package: "griffe.Module", path: str) -> bool:+ """Whether a name is a named color, which the colors' page shows as its palette."""+ obj = resolve(package, path)+ return isinstance(obj, griffe.Attribute) and str(obj.value).startswith(+ "ManimColor("+ )+++def test_every_documented_name_is_shown(package: "griffe.Module") -> None:+ need, _ = required(package)+ seen = shown(package)+ names: dict[str, set[str]] = {}+ for path in seen:+ owner, _, name = path.rpartition(".")+ names.setdefault(name, set()).add(owner)++ def related(path: str) -> bool:+ """Whether an override's base, or a base's override, is shown under its name."""+ owner, _, name = path.rpartition(".")+ cls = resolve(package, owner)+ if not isinstance(cls, griffe.Class):+ return False+ lineage = {cls.path, *(base.path for base in cls.mro())}+ for other in names.get(name, ()):+ other_cls = resolve(package, other)+ if other in lineage or (+ isinstance(other_cls, griffe.Class)+ and cls.path in {base.path for base in other_cls.mro()}+ ):+ return True+ return False++ def another_name(label: str) -> bool:+ """Whether an export is another name of a class shown (`VGroup = Group`)."""+ obj = resolve(package, label)+ if not isinstance(obj, griffe.Attribute) or obj.value is None:+ return False+ other = resolve(package, f"manimgx.{obj.value}")+ return isinstance(other, griffe.Class) and other.path in seen++ missing = sorted(+ label+ for path, label in need.items()+ if path not in seen+ and label not in UNDOCUMENTED+ and not palette_shows(package, label)+ and not another_name(label)+ and not related(path)+ )+ assert not missing, f"not on a page of docs/content/reference/: {missing}"+++def test_nothing_is_shown_twice(package: "griffe.Module") -> None:+ """A class, a function or a constant is shown once; a member a private base gives two+ classes (`_Grid.get_rows`, Matrix's and Table's) is shown with each."""+ twice = {}+ for path, where in shown(package).items():+ obj = resolve(package, path)+ if len(where) > 1 and obj is not None and isinstance(obj.parent, griffe.Module):+ twice[path] = where+ assert not twice, f"shown on more than one page, or twice on one: {twice}"+++def test_undocumented_names_exist(package: "griffe.Module") -> None:+ need, _ = required(package)+ labels = set(need.values())+ assert labels >= UNDOCUMENTED, sorted(UNDOCUMENTED - labels)+++def test_every_card_has_its_film() -> None:+ """A card shows the still of a scene the docs define (``, which+ `docs/films.py` resolves), and nothing else above its name: no count of pages."""+ from docs import examples++ scenes = {str(example.scene) for example in examples.examples()}+ for page in PAGES.rglob("*.md"):+ for block in CARDS.findall(page.read_text(encoding="utf-8")):+ for card in re.split(r"^- ", block, flags=re.MULTILINE)[1:]:+ picture = re.match(r"!\[\]\(film:(\w+)\)\n\n \[\*\*", card)+ where = page.relative_to(PAGES)+ assert picture, (+ f"{where}: a card is a film, then its name: {card[:60]!r}"+ )+ assert picture[1] in scenes, (+ f"{where}: no scene {picture[1]} in the docs"+ )+++def test_nothing_deprecated_is_shown(package: "griffe.Module") -> None:+ """A deprecated class stays in its module for the classes made from it, but no page+ shows it, nor what is deprecated in a class shown."""+ from docs.deprecated import deprecated++ hidden = sorted(+ path+ for path in shown(package)+ if (obj := resolve(package, path)) is not None and deprecated(obj)+ )+ assert not hidden, f"deprecated, and shown: {hidden}"diff --git a/tests/docs/test_skill.py b/tests/docs/test_skill.pynew file mode 100644index 00000000..cdd7f6bb--- /dev/null+++ b/tests/docs/test_skill.py@@ -0,0 +1,22 @@+"""The agent skill (`skills/manimgx/SKILL.md`) is what `npx skills add academa-labs/manimgx`+and `gh skill install academa-labs/manimgx` install: they find it by its path,+`skills/<name>/SKILL.md`, and read its front matter, which the Agent Skills specification+(https://agentskills.io/specification) constrains. This checks it against the specification:+the name is its folder's, and the description is 1 to 1,024 characters."""++import re+from pathlib import Path++import yaml++SKILL = Path(__file__).parents[2] / "skills" / "manimgx" / "SKILL.md"+++def test_its_front_matter_follows_the_specification() -> None:+ text = SKILL.read_text(encoding="utf-8")+ match = re.fullmatch(r"---\n(.*?)\n---\n.*", text, re.DOTALL)+ assert match, "SKILL.md opens with its front matter, between two `---` lines"+ fields = yaml.safe_load(match[1])+ assert fields["name"] == SKILL.parent.name+ assert isinstance(fields["description"], str)+ assert 1 <= len(fields["description"]) <= 1024diff --git a/tests/docs/test_svg.py b/tests/docs/test_svg.pynew file mode 100644index 00000000..269079d3--- /dev/null+++ b/tests/docs/test_svg.py@@ -0,0 +1,31 @@+"""The README's films as SVGs (`docs/svg.py`) have no background, so the page's shows+through, and a light page's variant draws the scene's white ink in the page's, leaving its+colors as they are."""++from pathlib import Path++from docs import svg++import manimgx as m+++class Ink(m.Scene):+ def construct(self) -> None:+ title = m.Square(2, color=m.WHITE, fill_opacity=1) # white ink, as a title is+ ring = m.Circle(1.5, color="#ffc94a").shift(3 * m.RIGHT) # a color+ self.play(m.Create(ring), m.FadeIn(title), run_time=0.5)+++def test_no_background_and_white_ink_dark_on_a_light_page(tmp_path: Path) -> None:+ recording = svg.record(Ink)+ dark, light = tmp_path / "dark.svg", tmp_path / "light.svg"+ svg.write(recording, dark)+ svg.write(recording, light, light=True)+ on_dark, on_light = dark.read_text(), light.read_text()+ for text in (on_dark, on_light):+ assert "<rect" not in text # nothing under the scene+ assert "#FFC94A" in text # the color stays+ assert "#FFFFFF" in on_dark+ assert svg.INK not in on_dark+ assert svg.INK in on_light+ assert "#FFFFFF" not in on_lightdiff --git a/tests/docs/test_wall.py b/tests/docs/test_wall.pynew file mode 100644index 00000000..d15beb9c--- /dev/null+++ b/tests/docs/test_wall.py@@ -0,0 +1,39 @@+"""The README's wall (`scripts/showcase/wall.py`): every clip's box lies in its film, its+frames last the loop exactly, so that it loops in time, and the README shows every film's+tiles, linked to its file."""++from pathlib import Path++import pytest+from scripts.showcase import wall++README = Path(__file__).parents[2] / "README.md"+++def test_every_clip_s_box_lies_in_its_film() -> None:+ for clip in wall.CLIPS:+ left, top, right, bottom = clip.box+ assert 0 <= left < right <= wall.FILM[0], clip.name+ assert 0 <= top < bottom <= wall.FILM[1], clip.name+ assert abs((right - left) * 9 / 16 - (bottom - top)) < 1, clip.name # 16:9+++def test_a_box_that_leaves_its_film_is_refused() -> None:+ with pytest.raises(ValueError, match="leaves the film"):+ _ = wall.Clip("too-wide", 0, 1000, 0, 1000).box+++def test_the_frames_last_the_loop_exactly() -> None:+ durations = wall.durations()+ assert len(durations) == wall.FPS * wall.SECONDS+ assert sum(durations) == 1000 * wall.SECONDS+ assert max(durations) - min(durations) <= 1 # whole milliseconds, evenly spread+++def test_the_readme_shows_every_film_linked_to_its_file() -> None:+ readme = README.read_text(encoding="utf-8")+ for clip in wall.CLIPS:+ for scale in wall.SCALES:+ tile = f"https://manimgx.academa.ai/showcase/{wall.name(clip, scale)}"+ assert tile in readme+ assert f"/blob/main/examples/{clip.name}.py" in readme