/
__init__.py
155 lines (120 loc) · 4.57 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
from IPython.core.magic import Magics, magics_class, cell_magic
from unittest.mock import patch
from tempfile import NamedTemporaryFile
import manimlib
from IPython.display import HTML
import sys
from io import StringIO
from contextlib import ExitStack, suppress, redirect_stdout, redirect_stderr
from warnings import warn
from IPython import get_ipython
from pathlib import Path
std_out = sys.stdout
def video(path, width=854, height=480, controls=True, autoplay=True):
return HTML(f"""
<video
width="{width}"
height="{height}"
autoplay="{'autoplay' if autoplay else ''}"
{'controls' if controls else ''}
>
<source src="{path}" type="video/mp4">
</video>
""")
class StringIOWithCallback(StringIO):
def __init__(self, callback, **kwargs):
super().__init__(**kwargs)
self.callback = callback
def write(self, s):
super().write(s)
self.callback(s)
@magics_class
class ManimMagics(Magics):
path_line_start = 'File ready at '
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.defaults = {
'autoplay': True,
'controls': True,
'silent': True,
'width': 854,
'height': 480
}
video_settings = {'width', 'height', 'controls', 'autoplay'}
magic_off_switches = {
'verbose': 'silent',
'no-controls': 'controls',
'no-autoplay': 'autoplay'
}
@cell_magic
def manim(self, line, cell):
# execute the code - won't generate any video, however it will introduce
# the variables into the notebook's namespace (enabling autocompletion etc);
# this also allows users to get feedback on some code errors early on
get_ipython().ex(cell)
user_args = line.split(' ')
# path of the output video
path = None
settings = self.defaults.copy()
# disable the switches as indicated by the user
for key, arg in self.magic_off_switches.items():
if '--' + key in user_args:
user_args.remove('--' + key)
settings[arg] = False
resolution_index = (
user_args.index('-r') if '-r' in user_args else
user_args.index('--resolution') if '--resolution' in user_args else
None
)
if resolution_index is not None:
# the resolution is passed as "height,width"
try:
h, w = user_args[resolution_index + 1].split(',')
settings['height'] = h
settings['width'] = w
except (IndexError, KeyError):
warn('Unable to retrieve dimensions from your resolution setting, falling back to the defaults')
silent = settings['silent']
def catch_path_and_forward(lines):
nonlocal path
for line in lines.split('\n'):
if not silent:
print(line, file=std_out)
if line.startswith(self.path_line_start):
path = line[len(self.path_line_start):].strip()
with NamedTemporaryFile('w', suffix='.py') as f:
f.write(cell)
f.flush()
args = ['manim', f.name, *user_args]
stdout = StringIOWithCallback(catch_path_and_forward)
with ExitStack() as stack:
enter = stack.enter_context
enter(patch.object(sys, 'argv', args))
enter(suppress(SystemExit))
enter(redirect_stdout(stdout))
if silent:
stderr = StringIO()
enter(redirect_stderr(stderr))
manimlib.main()
if path:
path = Path(path)
assert path.exists()
# To display a video in Jupyter, we need to have access to it
# so it has to be within the working tree. The absolute paths
# are usually outside of the accessible range.
relative_path = path.relative_to(Path.cwd())
video_settings = {
k: v
for k, v in settings.items()
if k in self.video_settings
}
return video(relative_path, **video_settings)
else:
warn('Could not find path in the manim output')
# If we were silent, some errors could have been silenced too.
if silent:
# Let's break the silence:
print(stdout.getvalue())
print(stderr.getvalue(), file=sys.stderr)
ip = get_ipython()
ip.register_magics(ManimMagics)