Coverage for src/manimgx/cli/export.py: 95%

134 statements  

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

1"""Offline scene exports: video, inspections and presentations.""" 

2 

3import json 

4import os 

5import re 

6import time 

7import webbrowser 

8from fractions import Fraction 

9from html import escape 

10from importlib.resources import files 

11from pathlib import Path 

12from typing import TYPE_CHECKING, Annotated 

13from urllib.parse import quote 

14 

15import typer 

16from PIL import Image 

17 

18from manimgx.animation import clock 

19from manimgx.animation.timeline import Animation 

20from manimgx.cli.diagnostics import Names, names, written_frame 

21from manimgx.cli.scenes import ( 

22 File, 

23 Format, 

24 Fps, 

25 Resolution, 

26 SceneName, 

27 fail, 

28 scene, 

29 take, 

30) 

31from manimgx.cli.storyboard import Sheets, Watch, line 

32from manimgx.rendering.film import ( 

33 DEFAULT_ENCODER_CRF, 

34 DEFAULT_ENCODER_PRESET, 

35 Cut, 

36 Film, 

37 Frame, 

38 Play, 

39 X264Preset, 

40) 

41from manimgx.scene import Scene 

42from manimgx.settings import config 

43 

44if TYPE_CHECKING: 

45 from manimgx.animation.transform import Transform 

46 from manimgx.drawing.geometry import Path as MotionPath 

47 

48 

49def render( 

50 file: File, 

51 name: SceneName = None, 

52 output: Annotated[ 

53 Path | None, 

54 typer.Option( 

55 "--output", 

56 "-o", 

57 help="The video (.mp4). [default: <Scene>.mp4 beside the file]", 

58 ), 

59 ] = None, 

60 resolution: Resolution = None, 

61 fps: Fps = None, 

62 preset: Annotated[ 

63 X264Preset, 

64 typer.Option( 

65 help="Encoding speed: faster presets encode sooner but produce larger files." 

66 ), 

67 ] = DEFAULT_ENCODER_PRESET, 

68 crf: Annotated[ 

69 float, 

70 typer.Option( 

71 min=0, 

72 max=51, 

73 help="Video quality: lower values give higher quality and larger files.", 

74 ), 

75 ] = DEFAULT_ENCODER_CRF, 

76) -> None: 

77 """Render a scene to an MP4 video, with its sound. 

78 

79 Also writes a storyboard beside the video (the frame at each play's end, layout problems 

80 outlined and numbered) and lists those problems — see `manimgx inspect` — and, if the 

81 scene speaks or has subcaptions, its subtitles (.srt).""" 

82 kind = scene(file, name) 

83 video = output or file.with_name(f"{kind.__name__}.mp4") 

84 if video.suffix.lower() != ".mp4": 

85 raise fail(f"error: {video}: ManimGX writes MP4 video; name the output *.mp4") 

86 look = Format.own(resolution, fps) 

87 watch = Watch(Sheets(video.with_name(f"{video.stem}.storyboard.png"))) 

88 started = time.perf_counter() 

89 try: 

90 made, _ = take(kind, look, video=video, plays=watch, preset=preset, crf=crf) 

91 finally: 

92 sheets = watch.storyboard.close() 

93 took = time.perf_counter() - started 

94 megabytes = video.stat().st_size / 1e6 

95 typer.echo( 

96 f"{video} {float(made.clock):.2f} s, {look}, {megabytes:.1f} MB " 

97 f"(rendered in {took:.1f} s)" 

98 ) 

99 typer.echo(f"storyboard: {', '.join(str(s) for s in sheets)}") 

100 subtitles = made.film.subtitles() 

101 if subtitles: 

102 srt = video.with_suffix(".srt") 

103 srt.write_text(subtitles, encoding="utf-8") 

104 typer.echo(f"subtitles: {srt}") 

105 typer.echo(watch.report(timeline=False, film=made.film)) 

106 

107 

108def moments(given: list[str]) -> set[Fraction | None]: 

109 """Distinct times in seconds; None means `end`. `-t 1,2` is `-t 1 -t 2`.""" 

110 out: set[Fraction | None] = set() 

111 for part in (p.strip() for text in given for p in text.split(",")): 

112 if not part: 

113 continue 

114 try: 

115 moment = None if part == "end" else Fraction(part) 

116 if moment is not None and moment < 0: 

117 raise ValueError 

118 except (ValueError, ZeroDivisionError): 

119 raise fail( 

120 f"error: {part!r} is not a time: non-negative seconds or 'end'" 

121 ) from None 

122 out.add(moment) 

123 if given and not out: 

124 raise fail("error: --time needs seconds from the start, or 'end'") 

125 return out 

126 

127 

128def inspect( 

129 file: File, 

130 name: SceneName = None, 

131 time: Annotated[ 

132 list[str] | None, 

133 typer.Option( 

134 "--time", 

135 "-t", 

136 metavar="TIME", 

137 help=( 

138 "Seconds from the start, or 'end'; several: repeat -t or separate with" 

139 " commas." 

140 ), 

141 show_default=False, 

142 ), 

143 ] = None, 

144 output: Annotated[ 

145 Path | None, 

146 typer.Option( 

147 "--output", 

148 "-o", 

149 help="The storyboard (.png). [default: <Scene>.storyboard.png beside the file]", 

150 ), 

151 ] = None, 

152) -> None: 

153 """Inspect a scene: annotated PNGs, timeline and 2D layout checks, without video. 

154 

155 Samples play and wait endings by default. With -t, inspects the frames a video player 

156 shows at those times; 'end' is the last frame. Checks for clipped content, overlapping 

157 text, lines or fills over text, and small labels. 3D scenes get pictures and a timeline; 

158 layout checks are skipped. Only sampled moments are checked. 

159 

160 Pictures are chronological, captioned #play t=… file:line, with problems outlined and 

161 numbered. Six fit on each sheet (more go on `<name>-2.png`, …). Default sampling omits 

162 consecutive identical pictures. With -t, only the requested frames are drawn, and the 

163 scene stops after the last requested frame's play unless 'end' is included. 

164 

165 Exits 1 for layout problems; notes, such as a graph leaving the frame, do not count. 

166 """ 

167 kind = scene(file, name) 

168 wanted = moments(time or []) 

169 target = output or file.with_name(f"{kind.__name__}.storyboard.png") 

170 if target.suffix.lower() != ".png": 

171 raise fail( 

172 f"error: {target}: a storyboard is a PNG image; name the output *.png" 

173 ) 

174 look = Format.own() 

175 fps = clock.rational(look.fps) 

176 # The last sample no later than the requested observed instant. 

177 pending = sorted( 

178 ((clock.frame_at(t, fps, after=True) - 1, t) for t in wanted if t is not None), 

179 reverse=True, 

180 ) 

181 known: Names | None = None 

182 watch = Watch(Sheets(target)) 

183 

184 class Sampling(Scene): 

185 """Observe selected frames through the scene's existing evaluation methods.""" 

186 

187 def _emit(self, repeat: int = 1) -> None: 

188 while pending and pending[-1][0] < self.frame + repeat: 

189 when = Fraction(pending.pop()[0]) / fps 

190 watch.see(self, when, known=known) 

191 super()._emit(repeat) 

192 

193 def _pure_tweens( 

194 self, anim: Animation, alpha: list[float] 

195 ) -> "tuple[list[tuple[Transform, MotionPath]], set[int]] | None": 

196 if pending and pending[-1][0] < self.frame + len(alpha): 

197 return None # this play needs its mutable world at the selected frames 

198 return super()._pure_tweens(anim, alpha) 

199 

200 def ended(made: Scene, play: Play, animations: tuple[Animation, ...]) -> None: 

201 nonlocal known 

202 if not made.three_d: 

203 known = names(made, written_frame()) 

204 watch.lines.append(line(play, animations)) 

205 if None not in wanted and not pending: 

206 raise Cut # the play showing the last frame asked for is over 

207 

208 try: 

209 # Only an inspection with selected frames uses the adapter. Scene and render 

210 # keep their ordinary evaluation path, including subclasses' overrides. 

211 observed = ( 

212 type(kind.__name__, (kind, Sampling), {"__module__": kind.__module__}) 

213 if pending 

214 else kind 

215 ) 

216 made, film = take(observed, look, plays=ended if wanted else watch) 

217 if pending: 

218 raise fail( 

219 f"error: the scene ends at {float(made.clock):.2f} s; there is no frame at" 

220 f" {pending[-1][1]} s", 

221 1, 

222 ) 

223 if None in wanted or (not wanted and not film.plays): 

224 watch.see(made, Fraction(film.frame_count - 1) / fps, known=known) 

225 finally: 

226 sheets = watch.storyboard.close() 

227 typer.echo( 

228 f"{file}: {kind.__name__}, {float(made.clock):.2f} s, {len(film.plays)} plays" 

229 ) 

230 typer.echo(f"storyboard: {', '.join(str(s) for s in sheets)}") 

231 typer.echo(watch.report(film=film if not wanted or None in wanted else None)) 

232 if watch.layout.numbers: 

233 raise typer.Exit(1) 

234 

235 

236def present( 

237 file: File, 

238 name: SceneName = None, 

239 output: Annotated[ 

240 Path | None, 

241 typer.Option( 

242 "--output", 

243 "-o", 

244 help="The video (.mp4); the page is written beside it (.html). [default:" 

245 " <Scene>.mp4 beside the file]", 

246 ), 

247 ] = None, 

248 resolution: Resolution = None, 

249 fps: Fps = None, 

250 pdf: Annotated[ 

251 bool, 

252 typer.Option( 

253 help="Also write a PDF: the picture each slide ends on, a page each." 

254 ), 

255 ] = False, 

256 show: Annotated[ 

257 bool, typer.Option("--open/--no-open", help="Open the page in the browser.") 

258 ] = True, 

259) -> None: 

260 """Present a scene: its sections are the slides. 

261 

262 Renders the video, writes a page that plays it (it stops at the end of each section, 

263 until you go on), and opens it. Keys: → or Space next, ← back, F full screen, B black, 

264 Shift+P presenter view (notes, the next slide, a timer), C captions, ? help. A clicker 

265 works: it sends the same keys. Begin a section with `self.next_section(...)` in the scene. 

266 """ 

267 kind = scene(file, name) 

268 video = output or file.with_name(f"{kind.__name__}.mp4") 

269 if video.suffix.lower() != ".mp4": 

270 raise fail(f"error: {video}: ManimGX writes MP4 video; name the output *.mp4") 

271 look = Format.own(resolution, fps) 

272 pictures: list[bytes] = [] # the pictures slides end on, for the PDF 

273 last: list[Frame] = [] 

274 

275 def keep(frame: Frame) -> None: 

276 if frame.key and frame.index > 0: 

277 pictures.append(frame.pixels()) 

278 last[:] = [frame] 

279 

280 started = time.perf_counter() 

281 made, film = take(kind, look, video=video, frames=keep if pdf else None) 

282 if pdf and last: 

283 pictures.append(last[0].pixels()) # the film's last picture ends the last slide 

284 html = video.with_suffix(".html") 

285 html.write_text(page(film, Path(video.name), kind.__name__), encoding="utf-8") 

286 slides = len(film.sections) 

287 typer.echo( 

288 f"{video} {float(made.clock):.2f} s, {look}, {slides} slides (rendered in" 

289 f" {time.perf_counter() - started:.1f} s)" 

290 ) 

291 typer.echo(f"{html}") 

292 if pdf: 

293 size = (config.pixel_width, config.pixel_height) 

294 images = [Image.frombytes("RGBA", size, p).convert("RGB") for p in pictures] 

295 handout = video.with_suffix(".pdf") 

296 images[0].save(handout, save_all=True, append_images=images[1:]) 

297 typer.echo(f"{handout}") 

298 if show: 

299 webbrowser.open(html.resolve().as_uri()) 

300 

301 

302def page(film: Film, video: str | os.PathLike[str], title: str = "ManimGX") -> str: 

303 """The page that presents `film`, whose video is `video` (a path or URL, as the page 

304 will find it: relative to the page, typically). 

305 

306 Args: 

307 film: The film, rendered. 

308 video: Where the page finds its video: a URL string, or a filesystem path 

309 (relative to the page, unless absolute). 

310 title: The page's title. 

311 

312 Returns: 

313 The page's HTML. 

314 """ 

315 deck = { 

316 "fps": float(film.fps), 

317 "frames": film.frame_count, 

318 "sections": [ 

319 {"name": s.name, "frame": s.frame, "type": s.type, "notes": s.notes} 

320 for s in film.sections 

321 ], 

322 "captions": [[c.start, c.end, c.text] for c in film.captions()], 

323 } 

324 html = (files("manimgx") / "cli" / "present.html").read_text(encoding="utf-8") 

325 if not isinstance(video, str): 

326 path = Path(video) 

327 video = path.as_uri() if path.is_absolute() else quote(path.as_posix()) 

328 values = { 

329 "DECK_TITLE": escape(title), 

330 "DECK_VIDEO": escape(video), 

331 "DECK_JSON": json.dumps(deck).replace("</", "<\\/"), 

332 } 

333 return re.sub(r"DECK_(?:TITLE|VIDEO|JSON)", lambda match: values[match[0]], html)