Coverage for src/manimgx/cli/scenes.py: 78%

153 statements  

« prev     ^ index     » next       coverage.py v7.16.1, created at 2026-10-26 05:52 +0000

1"""A command-line scene run: its arguments, source file, format, film and author-facing errors.""" 

2 

3import dataclasses 

4import difflib 

5import importlib.util 

6import linecache 

7import os 

8import re 

9import sys 

10import traceback 

11from collections.abc import Callable 

12from dataclasses import dataclass 

13from importlib.machinery import SourceFileLoader 

14from pathlib import Path 

15from types import CodeType, ModuleType 

16from typing import Annotated, Self 

17 

18import typer 

19from rich.console import Console 

20 

21import manimgx 

22from manimgx.animation.timeline import Animation 

23from manimgx.rendering.film import ( 

24 DEFAULT_ENCODER_CRF, 

25 DEFAULT_ENCODER_PRESET, 

26 Film, 

27 FrameSink, 

28 Play, 

29 X264Preset, 

30) 

31from manimgx.scene import Scene 

32from manimgx.settings import Config, config 

33 

34 

35@dataclass(frozen=True, slots=True) 

36class Size: 

37 """A picture's size in pixels.""" 

38 

39 width: int 

40 height: int 

41 

42 def __str__(self) -> str: 

43 return f"{self.width}x{self.height}" 

44 

45 

46def size(text: str) -> Size: 

47 """`WIDTHxHEIGHT` as a size.""" 

48 width, _, height = text.lower().partition("x") 

49 try: 

50 parsed = Size(int(width), int(height)) 

51 except ValueError: 

52 raise typer.BadParameter( 

53 f"{text!r} is not WIDTHxHEIGHT, e.g. 1280x720" 

54 ) from None 

55 if parsed.width <= 0 or parsed.height <= 0 or parsed.width % 2 or parsed.height % 2: 

56 raise typer.BadParameter( 

57 f"{text!r}: width and height must be even and positive" 

58 ) 

59 return parsed 

60 

61 

62File = Annotated[ 

63 Path, 

64 typer.Argument( 

65 metavar="FILE", 

66 help="The scene file: a Python file defining ManimGX scenes.", 

67 show_default=False, 

68 ), 

69] 

70SceneName = Annotated[ 

71 str | None, 

72 typer.Argument( 

73 metavar="SCENE", 

74 help=( 

75 "The scene (a class in the file); needed only if the file defines several." 

76 ), 

77 show_default=False, 

78 ), 

79] 

80# a scene's format is its own — what its file sets in `config`, else 1920x1080 at 60 fps — unless 

81# an option says otherwise 

82Resolution = Annotated[ 

83 Size | None, 

84 typer.Option( 

85 "--resolution", 

86 "-r", 

87 parser=size, 

88 metavar="WxH", 

89 help=( 

90 "Pixels, e.g. 1280x720. [default: the scene's config, 1920x1080 unless set]" 

91 ), 

92 show_default=False, 

93 ), 

94] 

95Fps = Annotated[ 

96 int | None, 

97 typer.Option( 

98 min=1, 

99 help="Frames per second. [default: the scene's config, 60 unless set]", 

100 show_default=False, 

101 ), 

102] 

103 

104 

105PACKAGE = str(Path(manimgx.__file__).parent) 

106 

107# names from older Manim (CE before 0.x renames, manimgl) and what ManimGX has instead 

108RENAMED = { 

109 "ShowCreation": "Create", 

110 "ShowCreationThenDestruction": "ShowPassingFlash", 

111 "ShowCreationThenFadeOut": "ShowPassingFlash", 

112 "CircleIndicate": "Circumscribe", 

113 "WiggleOutThenIn": "Wiggle", 

114 "TextMobject": "Text (plain text) or Tex (text with LaTeX)", 

115 "TexText": "Tex", 

116 "OldTexText": "Tex", 

117 "TexMobject": "MathTex", 

118 "OldTex": "MathTex", 

119 "FadeInFrom": "FadeIn(mobject, shift=direction)", 

120 "FadeInFromDown": "FadeIn(mobject, shift=UP)", 

121 "FadeOutAndShift": "FadeOut(mobject, shift=direction)", 

122 "FadeInFromLarge": "FadeIn(mobject, scale=factor)", 

123 "GraphScene": "a Scene with Axes (axes.plot(f))", 

124 "ParametricSurface": "Surface", 

125 "ContinualAnimation": "mobject.add_updater(function)", 

126} 

127 

128 

129def _names() -> list[str]: 

130 return [name for name in dir(manimgx) if not name.startswith("_")] 

131 

132 

133def hints(error: BaseException) -> list[str]: 

134 """What to write instead, for the mistakes a scene's author makes in names.""" 

135 text = str(error) 

136 if isinstance(error, AttributeError) and ( 

137 match := re.search(r"module 'manimgx' has no attribute '(\w+)'", text) 

138 ): 

139 return [_instead(match.group(1))] 

140 if isinstance(error, AttributeError) and error.obj is not None and error.name: 

141 close = difflib.get_close_matches(error.name, dir(error.obj), n=3, cutoff=0.6) 

142 if close: 

143 return [f"did you mean {' or '.join(close)}?"] 

144 if isinstance(error, NameError) and error.name: 

145 if error.name in _names(): 

146 return [ 

147 f"{error.name} is manimgx.{error.name}: `import manimgx as m`, then " 

148 f"m.{error.name}" 

149 ] 

150 if error.name in RENAMED: 

151 return [_instead(error.name)] 

152 if isinstance(error, ModuleNotFoundError) and error.name in ("manim", "manimlib"): 

153 return ["manimgx is the module: `import manimgx as m` (its API is Manim CE's)"] 

154 return [] 

155 

156 

157def _instead(name: str) -> str: 

158 if name in RENAMED: 

159 return f"{name} is {RENAMED[name]} in ManimGX" 

160 close = difflib.get_close_matches(name, _names(), n=3, cutoff=0.6) 

161 if close: 

162 return f"ManimGX has no {name}; did you mean {' or '.join(close)}?" 

163 return f"ManimGX has no {name}" 

164 

165 

166def report_error(error: BaseException) -> str: 

167 """The error as it went through the scene's code: its last frames there (and where ManimGX 

168 raised it), the error, and hints.""" 

169 frames = traceback.extract_tb(error.__traceback__) 

170 own = [ 

171 f 

172 for f in frames 

173 if not f.filename.startswith(PACKAGE) 

174 and "/typer/" not in f.filename 

175 and not f.filename.startswith("<") 

176 ] 

177 lines: list[str] = [] 

178 for f in own[-3:]: 

179 lines.append(f"{Path(f.filename).name}:{f.lineno}: in {f.name}") 

180 if f.line: 

181 lines.append(f" {f.line}") 

182 inside = [f for f in frames if f.filename.startswith(PACKAGE)] 

183 if inside and frames[-1].filename.startswith(PACKAGE): 

184 last = inside[-1] 

185 where = Path(last.filename).relative_to(PACKAGE) 

186 lines.append(f" (raised in manimgx/{where}:{last.lineno}, in {last.name})") 

187 lines.append(f"{type(error).__name__}: {error}") 

188 lines += [f"hint: {h}" for h in hints(error)] 

189 return "\n".join(lines) 

190 

191 

192class Mistake(Exception): 

193 """The command was given wrong; the message says how to give it.""" 

194 

195 

196class Source(SourceFileLoader): 

197 """Current authoring source, with no timestamp-bytecode reuse or cache writes.""" 

198 

199 def get_code(self, fullname: str) -> CodeType: 

200 linecache.cache.pop(self.path, None) 

201 return self.source_to_code(self.get_data(self.path), self.path) 

202 

203 

204def load(path: Path) -> ModuleType: 

205 """Run the file as a module named by its stem, with its directory first on the path (so it 

206 imports its neighbours) — not as `__main__`, so its own `if __name__ == "__main__":` block 

207 stays put.""" 

208 defaults = Config() 

209 for field in dataclasses.fields(Config): 

210 setattr(config, field.name, getattr(defaults, field.name)) 

211 if not path.is_file(): 

212 raise Mistake(f"{path}: no such file") 

213 spec = importlib.util.spec_from_file_location(path.stem, path) 

214 if spec is None or spec.loader is None: 

215 raise Mistake(f"{path}: not a Python file") 

216 spec.loader = Source(path.stem, str(path.resolve())) 

217 module = importlib.util.module_from_spec(spec) 

218 sys.modules[path.stem] = module # dataclasses and pickles resolve names through it 

219 sys.path.insert(0, str(path.resolve().parent)) 

220 spec.loader.exec_module(module) 

221 return module 

222 

223 

224def scenes(module: ModuleType) -> list[type[Scene]]: 

225 """The scenes the module defines, in the order it defines them.""" 

226 return [ 

227 value 

228 for value in vars(module).values() 

229 if isinstance(value, type) 

230 and issubclass(value, Scene) 

231 and value.__module__ == module.__name__ 

232 ] 

233 

234 

235def pick(path: Path, module: ModuleType, name: str | None) -> type[Scene]: 

236 """The scene `name` names — or, unnamed, the file's only scene.""" 

237 found = scenes(module) 

238 names = [scene.__name__ for scene in found] 

239 if name is not None: 

240 for scene in found: 

241 if scene.__name__ == name: 

242 return scene 

243 close = difflib.get_close_matches(name, names, n=3) 

244 hint = f" Did you mean {' or '.join(close)}?" if close else "" 

245 raise Mistake( 

246 f"{path} has no scene {name!r}.{hint} Its scenes: {', '.join(names)}" 

247 ) 

248 if len(found) == 1: 

249 return found[0] 

250 if not found: 

251 raise Mistake(f"{path} defines no scene (a subclass of manimgx.Scene)") 

252 raise Mistake( 

253 f"{path} defines {len(found)} scenes ({', '.join(names)}): name one after the" 

254 " file" 

255 ) 

256 

257 

258@dataclass(frozen=True, slots=True) 

259class Format: 

260 """The picture a take makes: its size in pixels and frames per second.""" 

261 

262 width: int 

263 height: int 

264 fps: float 

265 

266 @classmethod 

267 def own(cls, size: Size | None = None, fps: float | None = None) -> Self: 

268 """The scene's own format — as its file leaves `config` — unless `size` or `fps` say 

269 otherwise.""" 

270 shape = size or Size(config.pixel_width, config.pixel_height) 

271 return cls(shape.width, shape.height, fps or config.frame_rate) 

272 

273 def __str__(self) -> str: 

274 return f"{self.width}x{self.height} at {self.fps:g} fps" 

275 

276 

277def fail(message: str, code: int = 2) -> typer.Exit: 

278 """Say what went wrong (on stderr) and end with `code`: 2 the command was wrong, 1 the scene 

279 failed.""" 

280 typer.echo(message, err=True) 

281 return typer.Exit(code) 

282 

283 

284def scene(file: Path, name: str | None) -> type[Scene]: 

285 """The scene the command names: its file run on ManimGX's own config (whatever the file 

286 sets there is the scene's, not a take's before it), and it picked.""" 

287 try: 

288 return pick(file, load(file), name) 

289 except Mistake as mistake: 

290 raise fail(f"error: {mistake}") from None 

291 except Exception as error: 

292 raise fail(report_error(error), 1) from None 

293 

294 

295type Watch = Callable[[Scene, Play, tuple[Animation, ...]], object] 

296"""What a command does when a play ends: the scene (as the play left it), the play, and what it 

297played.""" 

298 

299 

300def take( 

301 kind: type[Scene], 

302 look: Format, 

303 *, 

304 video: str | os.PathLike[str] | None = None, 

305 frames: FrameSink | None = None, 

306 plays: Watch | None = None, 

307 preset: X264Preset = DEFAULT_ENCODER_PRESET, 

308 crf: float = DEFAULT_ENCODER_CRF, 

309) -> tuple[Scene, Film]: 

310 """Run the scene at `look`, making its film (and video, frames and plays, as asked). On a 

311 terminal, a status line on stderr follows the plays as they end.""" 

312 config.pixel_width, config.pixel_height = look.width, look.height 

313 config.frame_rate = look.fps 

314 shown = Console(stderr=True) 

315 try: 

316 with shown.status(f"{kind.__name__}…", spinner="dots") as status: 

317 # after the config: its camera frame follows the picture's shape 

318 made = kind() 

319 

320 def hook(play: Play, did: tuple[Animation, ...]) -> None: 

321 if shown.is_terminal: 

322 status.update( 

323 f"{kind.__name__} t = {float(play.end):.1f} s, play" 

324 f" #{play.index}" 

325 ) 

326 if plays is not None: 

327 plays(made, play, did) 

328 

329 return made, made.render( 

330 video, frames=frames, plays=hook, preset=preset, crf=crf 

331 ) 

332 except Exception as error: 

333 raise fail(report_error(error), 1) from None