datacut 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. datacut/__init__.py +121 -0
  2. datacut/__main__.py +122 -0
  3. datacut/animation/__init__.py +0 -0
  4. datacut/animation/animation.py +336 -0
  5. datacut/animation/composition.py +258 -0
  6. datacut/animation/creation.py +315 -0
  7. datacut/animation/fading.py +328 -0
  8. datacut/animation/growing.py +90 -0
  9. datacut/animation/indication.py +608 -0
  10. datacut/animation/movement.py +165 -0
  11. datacut/animation/numbers.py +92 -0
  12. datacut/animation/physics.py +453 -0
  13. datacut/animation/rotation.py +95 -0
  14. datacut/animation/specialized.py +956 -0
  15. datacut/animation/transform.py +505 -0
  16. datacut/animation/transform_matching_parts.py +343 -0
  17. datacut/animation/update.py +95 -0
  18. datacut/camera/__init__.py +0 -0
  19. datacut/camera/camera.py +795 -0
  20. datacut/camera/camera_frame.py +320 -0
  21. datacut/camera/cinematography.py +1166 -0
  22. datacut/config.py +479 -0
  23. datacut/constants.py +160 -0
  24. datacut/css/__init__.py +189 -0
  25. datacut/css/easing.py +328 -0
  26. datacut/css/engine.py +1727 -0
  27. datacut/css/gradients.py +678 -0
  28. datacut/css/motion.py +1615 -0
  29. datacut/css/parser.py +741 -0
  30. datacut/css/presets.py +143 -0
  31. datacut/css/shader_fill.py +703 -0
  32. datacut/css/values.py +650 -0
  33. datacut/default_config.yml +224 -0
  34. datacut/event_handler/__init__.py +6 -0
  35. datacut/event_handler/event_dispatcher.py +161 -0
  36. datacut/event_handler/event_listner.py +31 -0
  37. datacut/event_handler/event_type.py +11 -0
  38. datacut/event_handler/picking.py +111 -0
  39. datacut/event_keys.py +53 -0
  40. datacut/extract_scene.py +200 -0
  41. datacut/layout/__init__.py +39 -0
  42. datacut/layout/components.py +425 -0
  43. datacut/layout/containers.py +1520 -0
  44. datacut/logger.py +13 -0
  45. datacut/mobject/__init__.py +0 -0
  46. datacut/mobject/boolean_ops.py +168 -0
  47. datacut/mobject/changing.py +209 -0
  48. datacut/mobject/coordinate_systems.py +1056 -0
  49. datacut/mobject/fractals.py +348 -0
  50. datacut/mobject/frame.py +80 -0
  51. datacut/mobject/functions.py +147 -0
  52. datacut/mobject/geometry.py +1834 -0
  53. datacut/mobject/gltf.py +243 -0
  54. datacut/mobject/interactive.py +906 -0
  55. datacut/mobject/lights.py +366 -0
  56. datacut/mobject/materials.py +207 -0
  57. datacut/mobject/matrix.py +570 -0
  58. datacut/mobject/mesh3d.py +2288 -0
  59. datacut/mobject/mobject.py +2885 -0
  60. datacut/mobject/mobject_update_utils.py +123 -0
  61. datacut/mobject/model.py +543 -0
  62. datacut/mobject/number_line.py +517 -0
  63. datacut/mobject/numbers.py +441 -0
  64. datacut/mobject/probability.py +536 -0
  65. datacut/mobject/shape_matchers.py +161 -0
  66. datacut/mobject/subtitles.py +260 -0
  67. datacut/mobject/svg/__init__.py +0 -0
  68. datacut/mobject/svg/brace.py +356 -0
  69. datacut/mobject/svg/drawings.py +1041 -0
  70. datacut/mobject/svg/old_tex_mobject.py +335 -0
  71. datacut/mobject/svg/path_cache.py +155 -0
  72. datacut/mobject/svg/special_tex.py +216 -0
  73. datacut/mobject/svg/string_mobject.py +622 -0
  74. datacut/mobject/svg/svg_mobject.py +657 -0
  75. datacut/mobject/svg/svg_parse.py +437 -0
  76. datacut/mobject/svg/tex_mobject.py +499 -0
  77. datacut/mobject/svg/text_mobject.py +702 -0
  78. datacut/mobject/svg/typst_mobject.py +864 -0
  79. datacut/mobject/three_dimensions.py +686 -0
  80. datacut/mobject/types/__init__.py +0 -0
  81. datacut/mobject/types/dot_cloud.py +220 -0
  82. datacut/mobject/types/image_mobject.py +130 -0
  83. datacut/mobject/types/point_cloud_mobject.py +138 -0
  84. datacut/mobject/types/shader_mobject.py +268 -0
  85. datacut/mobject/types/surface.py +848 -0
  86. datacut/mobject/types/vectorized_mobject.py +1749 -0
  87. datacut/mobject/types/video_mobject.py +3902 -0
  88. datacut/mobject/value_tracker.py +110 -0
  89. datacut/mobject/vector_field.py +585 -0
  90. datacut/module_loader.py +176 -0
  91. datacut/reactive/__init__.py +25 -0
  92. datacut/reactive/signals.py +610 -0
  93. datacut/renderer/__init__.py +4 -0
  94. datacut/renderer/drawing.py +1066 -0
  95. datacut/renderer/gpu.py +800 -0
  96. datacut/renderer/material.py +88 -0
  97. datacut/renderer/pipeline.py +179 -0
  98. datacut/renderer/post_process.py +577 -0
  99. datacut/renderer/renderer.py +1285 -0
  100. datacut/renderer/shader_source.py +146 -0
  101. datacut/renderer/shared_buffer.py +185 -0
  102. datacut/renderer/texture.py +217 -0
  103. datacut/renderer/uniform_block.py +118 -0
  104. datacut/scene/__init__.py +0 -0
  105. datacut/scene/incremental.py +233 -0
  106. datacut/scene/interactive_scene.py +758 -0
  107. datacut/scene/performance.py +226 -0
  108. datacut/scene/presentation_scene.py +783 -0
  109. datacut/scene/recording.py +541 -0
  110. datacut/scene/safe_zones.py +323 -0
  111. datacut/scene/scene.py +2849 -0
  112. datacut/scene/scene_embed.py +277 -0
  113. datacut/scene/scene_file_writer.py +1014 -0
  114. datacut/scene/scene_task.py +183 -0
  115. datacut/scene/sfx.py +164 -0
  116. datacut/scene/sound.py +702 -0
  117. datacut/scene/sound_clip.py +580 -0
  118. datacut/scene/timeline.py +1689 -0
  119. datacut/scene/transcript.py +503 -0
  120. datacut/shaders/fill.wgsl +107 -0
  121. datacut/shaders/fill_depth.wgsl +198 -0
  122. datacut/shaders/image.wgsl +25 -0
  123. datacut/shaders/inserts/NOTE.md +16 -0
  124. datacut/shaders/inserts/clip_test.wgsl +14 -0
  125. datacut/shaders/inserts/complex_functions.wgsl +20 -0
  126. datacut/shaders/inserts/fill_color.wgsl +10 -0
  127. datacut/shaders/inserts/finalize_color.wgsl +44 -0
  128. datacut/shaders/inserts/frame_uniforms.wgsl +37 -0
  129. datacut/shaders/inserts/frame_units.wgsl +18 -0
  130. datacut/shaders/inserts/image_quad.wgsl +28 -0
  131. datacut/shaders/inserts/mobject_uniforms.wgsl +11 -0
  132. datacut/shaders/inserts/project_point.wgsl +44 -0
  133. datacut/shaders/inserts/quad_corners.wgsl +12 -0
  134. datacut/shaders/inserts/read_data.wgsl +33 -0
  135. datacut/shaders/inserts/surface_mesh.wgsl +106 -0
  136. datacut/shaders/mandelbrot_fractal.wgsl +100 -0
  137. datacut/shaders/mesh.wgsl +474 -0
  138. datacut/shaders/newton_fractal.wgsl +200 -0
  139. datacut/shaders/present.wgsl +62 -0
  140. datacut/shaders/stroke.wgsl +1141 -0
  141. datacut/shaders/stroke_depth.wgsl +1136 -0
  142. datacut/shaders/surface.wgsl +40 -0
  143. datacut/shaders/textured_surface.wgsl +59 -0
  144. datacut/shaders/true_dot.wgsl +78 -0
  145. datacut/shaders/video.wgsl +42 -0
  146. datacut/tex_templates.yml +736 -0
  147. datacut/transcribe.py +32 -0
  148. datacut/typing.py +412 -0
  149. datacut/utils/__init__.py +0 -0
  150. datacut/utils/bezier.py +467 -0
  151. datacut/utils/browser_audio.py +423 -0
  152. datacut/utils/browser_code_transform.py +1293 -0
  153. datacut/utils/browser_completions.py +2255 -0
  154. datacut/utils/browser_fonts.py +143 -0
  155. datacut/utils/browser_pathops.py +47 -0
  156. datacut/utils/browser_scheduler.py +18 -0
  157. datacut/utils/browser_typst.py +82 -0
  158. datacut/utils/cache.py +34 -0
  159. datacut/utils/cinematic_vfx.py +779 -0
  160. datacut/utils/color.py +203 -0
  161. datacut/utils/debug.py +46 -0
  162. datacut/utils/dict_ops.py +22 -0
  163. datacut/utils/directories.py +55 -0
  164. datacut/utils/editor_signatures.py +1806 -0
  165. datacut/utils/editor_thumbnails.py +769 -0
  166. datacut/utils/family_ops.py +48 -0
  167. datacut/utils/file_ops.py +65 -0
  168. datacut/utils/images.py +52 -0
  169. datacut/utils/iterables.py +216 -0
  170. datacut/utils/native.py +280 -0
  171. datacut/utils/paths.py +83 -0
  172. datacut/utils/rate_functions.py +154 -0
  173. datacut/utils/render_geometry.py +186 -0
  174. datacut/utils/simple_functions.py +99 -0
  175. datacut/utils/sounds.py +43 -0
  176. datacut/utils/space_ops.py +460 -0
  177. datacut/utils/structured_array.py +256 -0
  178. datacut/utils/svg_export.py +102 -0
  179. datacut/utils/tex.py +139 -0
  180. datacut/utils/tex_file_writing.py +164 -0
  181. datacut/utils/tex_to_symbol_count.py +186 -0
  182. datacut/utils/typst_file_writing.py +205 -0
  183. datacut/utils/vfx_presets.py +4543 -0
  184. datacut/utils/visual_css.py +737 -0
  185. datacut/utils/visual_editor.py +4292 -0
  186. datacut/utils/window_audio.py +760 -0
  187. datacut/window.py +910 -0
  188. datacut-0.1.0.dist-info/METADATA +226 -0
  189. datacut-0.1.0.dist-info/RECORD +193 -0
  190. datacut-0.1.0.dist-info/WHEEL +5 -0
  191. datacut-0.1.0.dist-info/entry_points.txt +2 -0
  192. datacut-0.1.0.dist-info/licenses/LICENSE.md +21 -0
  193. datacut-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1293 @@
1
+ from __future__ import annotations
2
+
3
+ import ast
4
+ import copy
5
+
6
+ SYNC_CREATE_MOBJECTS = {'Text', 'MarkupText', 'Code'}
7
+ ASYNC_CREATE_MOBJECTS = {
8
+ 'Typst', 'TypstText', 'Tex', 'TexText', 'DecimalNumber', 'Integer',
9
+ 'VideoMobject', 'Sprite',
10
+ 'Brace', 'LineBrace', 'BraceLabel', 'BraceText',
11
+ 'Matrix', 'DecimalMatrix', 'IntegerMatrix', 'TexMatrix', 'MobjectMatrix',
12
+ 'BulletedList', 'TexTextFromPresetString', 'Checkmark', 'Exmark', 'Title',
13
+ 'BarChart', 'Speedometer', 'Bubble', 'SpeechBubble', 'ThoughtBubble',
14
+ 'Slider', 'Textbox', 'ControlPanel',
15
+ 'Button', 'Badge', 'Toast', 'Avatar',
16
+ }
17
+
18
+ DIRECT_ASYNC_METHODS = {
19
+ 'add_numbers', 'add_coordinates', 'add_coordinate_labels',
20
+ 'add_axis_labels', 'get_axis_labels',
21
+ 'get_axis_label', 'get_x_axis_label', 'get_y_axis_label',
22
+ 'get_graph_label', 'get_number_mobject',
23
+ 'make_number_changeable', 'swap_entries_for_ellipses',
24
+ 'shift_brace', 'change_label', 'change_brace_label',
25
+ 'add_title',
26
+ 'get_subdivision_braces_and_labels',
27
+ 'get_side_braces_and_labels',
28
+ 'get_top_braces_and_labels',
29
+ 'get_bottom_braces_and_labels',
30
+ 'from_scene',
31
+ }
32
+
33
+ MAYBE_ASYNC_METHODS = {
34
+ 'get_text', 'get_tex', 'write',
35
+ }
36
+
37
+ ASYNC_HELPER_FUNCTIONS = {
38
+ 'index_labels': 'index_labels_async',
39
+ }
40
+
41
+ SYNCHRONOUS_MOBJECT_METHODS = {
42
+ 'move_to', 'next_to', 'shift', 'scale', 'rotate', 'align_to', 'to_edge', 'to_corner',
43
+ 'set_color', 'set_stroke', 'set_fill', 'add', 'remove', 'become', 'match_x', 'match_y',
44
+ 'match_z', 'match_width', 'match_height', 'match_depth', 'set_width', 'set_height',
45
+ 'fix_in_frame', 'center', 'arrange', 'add_updater', 'remove_updater', 'update',
46
+ 'get_center', 'get_width', 'get_height', 'get_start', 'get_end', 'point_from_proportion'
47
+ }
48
+
49
+
50
+ def _is_true_constant(node: ast.AST) -> bool:
51
+ return isinstance(node, ast.Constant) and node.value is True
52
+
53
+
54
+ def _browser_schedule_task(coro_or_val):
55
+ import asyncio
56
+ import inspect
57
+ if inspect.isawaitable(coro_or_val):
58
+ return asyncio.create_task(coro_or_val)
59
+ return coro_or_val
60
+
61
+
62
+ async def _browser_call_async(obj, method_name: str, *args, **kwargs):
63
+ async_method = getattr(obj, f'{method_name}_async', None)
64
+ if async_method is not None:
65
+ return await async_method(*args, **kwargs)
66
+ return getattr(obj, method_name)(*args, **kwargs)
67
+
68
+
69
+ class _BrowserTransformer(ast.NodeTransformer):
70
+ def __init__(self, _visited_files: set[str] | None = None):
71
+ super().__init__()
72
+ self.changed = False
73
+ self.in_await = False
74
+ self.in_lambda = False
75
+ self.in_init = False
76
+ self.used_schedule_helper = False
77
+ self.used_call_async_helper = False
78
+ self.used_inspect = False
79
+ self.async_create_mobjects = set(ASYNC_CREATE_MOBJECTS)
80
+ self.sync_create_mobjects = set(SYNC_CREATE_MOBJECTS)
81
+ self.async_helper_functions = dict(ASYNC_HELPER_FUNCTIONS)
82
+ self.number_line_names = {'NumberLine', 'UnitInterval'}
83
+ self.manim_module_aliases = {'datacut'}
84
+ self.scene_base_aliases = {'Scene'}
85
+ self._visited_files = set(_visited_files) if _visited_files else set()
86
+
87
+ def _collect_manim_imports(self, tree: ast.AST) -> None:
88
+ for node in ast.walk(tree):
89
+ if isinstance(node, ast.Import):
90
+ for alias in node.names:
91
+ if alias.name == 'datacut' or alias.name.startswith('datacut.'):
92
+ if alias.asname:
93
+ self.manim_module_aliases.add(alias.asname)
94
+ else:
95
+ self.manim_module_aliases.add(alias.name.split('.')[0])
96
+ elif isinstance(node, ast.ImportFrom):
97
+ if node.module and (node.module == 'datacut' or node.module.startswith('datacut.')):
98
+ for alias in node.names:
99
+ if alias.name == '*':
100
+ continue
101
+ local_name = alias.asname or alias.name
102
+ if alias.name in ASYNC_CREATE_MOBJECTS:
103
+ self.async_create_mobjects.add(local_name)
104
+ elif alias.name in SYNC_CREATE_MOBJECTS:
105
+ self.sync_create_mobjects.add(local_name)
106
+ elif alias.name in ASYNC_HELPER_FUNCTIONS:
107
+ self.async_helper_functions[local_name] = ASYNC_HELPER_FUNCTIONS[alias.name]
108
+ elif alias.name in ('NumberLine', 'UnitInterval'):
109
+ self.number_line_names.add(local_name)
110
+ elif alias.name == 'Scene' or alias.name.endswith('Scene'):
111
+ self.scene_base_aliases.add(local_name)
112
+ elif alias.name[:1].islower():
113
+ self.manim_module_aliases.add(local_name)
114
+
115
+ # Propagate simple module aliases like `ml = datacut`
116
+ changed = True
117
+ while changed:
118
+ changed = False
119
+ for node in ast.walk(tree):
120
+ if isinstance(node, ast.Assign) and self._is_manim_module_expr(node.value):
121
+ for target in node.targets:
122
+ if isinstance(target, ast.Name) and target.id not in self.manim_module_aliases:
123
+ self.manim_module_aliases.add(target.id)
124
+ changed = True
125
+
126
+ def _resolve_local_module_file(self, mod_name: str) -> str | None:
127
+ import os
128
+ if not mod_name or mod_name == 'datacut' or mod_name.startswith('datacut.'):
129
+ return None
130
+ parts = mod_name.split('.')
131
+ search_roots = []
132
+ if os.path.isdir('/assets'):
133
+ search_roots.append('/assets')
134
+ cwd = os.getcwd()
135
+ if cwd and cwd not in search_roots and os.path.isdir(cwd):
136
+ search_roots.append(cwd)
137
+ for root in search_roots:
138
+ candidate = os.path.join(root, *parts) + '.py'
139
+ if os.path.isfile(candidate):
140
+ return os.path.abspath(candidate)
141
+ pkg_init = os.path.join(root, *parts, '__init__.py')
142
+ if os.path.isfile(pkg_init):
143
+ return os.path.abspath(pkg_init)
144
+ return None
145
+
146
+ def _discover_local_async_exports(self, tree: ast.AST) -> tuple[set[str], dict[str, set[str]]]:
147
+ """Inspect local project `.py` modules imported by `tree` to find functions
148
+ that become `async def` after browser transformation.
149
+ """
150
+ imported_async_names: set[str] = set()
151
+ imported_module_async_funcs: dict[str, set[str]] = {}
152
+ file_async_cache: dict[str, set[str]] = {}
153
+
154
+ def _async_funcs_in_file(filepath: str) -> set[str]:
155
+ if filepath in file_async_cache:
156
+ return file_async_cache[filepath]
157
+ if filepath in self._visited_files:
158
+ return set()
159
+ next_visited = set(self._visited_files)
160
+ next_visited.add(filepath)
161
+ try:
162
+ with open(filepath, 'r', encoding='utf-8') as f:
163
+ mod_source = f.read()
164
+ mod_tree = ast.parse(mod_source, filepath)
165
+ mod_tree = _BrowserTransformer(_visited_files=next_visited).transform(mod_tree)
166
+ names = {
167
+ n.name for n in getattr(mod_tree, 'body', [])
168
+ if isinstance(n, ast.AsyncFunctionDef)
169
+ }
170
+ except Exception:
171
+ names = set()
172
+ file_async_cache[filepath] = names
173
+ return names
174
+
175
+ for node in ast.walk(tree):
176
+ if isinstance(node, ast.ImportFrom) and node.module and node.level == 0:
177
+ filepath = self._resolve_local_module_file(node.module)
178
+ if not filepath:
179
+ continue
180
+ mod_async = _async_funcs_in_file(filepath)
181
+ if not mod_async:
182
+ continue
183
+ for alias in node.names:
184
+ if alias.name == '*':
185
+ imported_async_names.update(mod_async)
186
+ elif alias.name in mod_async:
187
+ imported_async_names.add(alias.asname or alias.name)
188
+ elif isinstance(node, ast.Import):
189
+ for alias in node.names:
190
+ filepath = self._resolve_local_module_file(alias.name)
191
+ if not filepath:
192
+ continue
193
+ mod_async = _async_funcs_in_file(filepath)
194
+ if not mod_async:
195
+ continue
196
+ local_alias = alias.asname or alias.name.split('.')[0]
197
+ imported_module_async_funcs.setdefault(local_alias, set()).update(mod_async)
198
+
199
+ return imported_async_names, imported_module_async_funcs
200
+
201
+ def _is_manim_module_expr(self, node: ast.AST) -> bool:
202
+ if isinstance(node, ast.Name):
203
+ return node.id in self.manim_module_aliases
204
+ if isinstance(node, ast.Attribute):
205
+ return self._is_manim_module_expr(node.value)
206
+ return False
207
+
208
+ def _is_create_mobject_expr(self, node: ast.AST) -> bool:
209
+ create_names = self.async_create_mobjects | self.sync_create_mobjects
210
+ if isinstance(node, ast.Name):
211
+ return node.id in create_names
212
+ if isinstance(node, ast.Attribute):
213
+ return node.attr in create_names and self._is_manim_module_expr(node.value)
214
+ return False
215
+
216
+ def _is_number_line_expr(self, node: ast.AST) -> bool:
217
+ if isinstance(node, ast.Name):
218
+ return node.id in self.number_line_names
219
+ if isinstance(node, ast.Attribute):
220
+ return node.attr in self.number_line_names and self._is_manim_module_expr(node.value)
221
+ return False
222
+
223
+ def transform(self, tree: ast.AST) -> ast.AST:
224
+ self._collect_manim_imports(tree)
225
+
226
+ # Phase 0: Transform custom DecimalNumber/Integer subclasses (e.g. LiveNumber(DecimalNumber))
227
+ # into browser-safe classes with def __init__(self, **kwargs): pass and async def create(cls, ...)
228
+ for node in ast.walk(tree):
229
+ if isinstance(node, ast.ClassDef):
230
+ is_async_subclass = any(
231
+ (isinstance(b, ast.Name) and b.id in ('DecimalNumber', 'Integer')) or
232
+ (isinstance(b, ast.Attribute) and b.attr in ('DecimalNumber', 'Integer'))
233
+ for b in node.bases
234
+ )
235
+ if is_async_subclass:
236
+ self.async_create_mobjects.add(node.name)
237
+ init_node = next((m for m in node.body if isinstance(m, ast.FunctionDef) and m.name == '__init__'), None)
238
+ if init_node:
239
+ create_args = copy.deepcopy(init_node.args)
240
+ if create_args.args:
241
+ create_args.args[0].arg = 'cls'
242
+
243
+ create_body = []
244
+ if create_args.kwarg:
245
+ create_body.append(ast.parse(f'self = cls(**{create_args.kwarg.arg})').body[0])
246
+ else:
247
+ create_body.append(ast.parse('self = cls()').body[0])
248
+
249
+ for stmt in init_node.body:
250
+ is_super_init = False
251
+ if isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Call):
252
+ call = stmt.value
253
+ if isinstance(call.func, ast.Attribute) and call.func.attr == '__init__':
254
+ if (
255
+ (isinstance(call.func.value, ast.Call) and isinstance(call.func.value.func, ast.Name) and call.func.value.func.id == 'super') or
256
+ (isinstance(call.func.value, ast.Name) and call.func.value.id in ('super', 'DecimalNumber', 'Integer')) or
257
+ (isinstance(call.func.value, ast.Attribute) and call.func.value.attr in ('DecimalNumber', 'Integer') and self._is_manim_module_expr(call.func.value.value))
258
+ ):
259
+ is_super_init = True
260
+ call.func.value = ast.Call(
261
+ func=ast.Name(id='super', ctx=ast.Load()),
262
+ args=[ast.Name(id='cls', ctx=ast.Load()), ast.Name(id='self', ctx=ast.Load())],
263
+ keywords=[]
264
+ )
265
+ call.keywords = [kw for kw in call.keywords if kw.arg != '_skip_text_render']
266
+ call.keywords.append(ast.keyword(arg='_skip_text_render', value=ast.Constant(value=True)))
267
+ create_body.append(stmt)
268
+
269
+ first_arg = call.args[0] if call.args else ast.Constant(value=0)
270
+ cache_logic = ast.parse('''
271
+ try:
272
+ font_key = (self.get_font_size(), tuple(sorted(((k, str(v)) for k, v in self.text_config.items()))))
273
+ except Exception:
274
+ font_key = self.get_font_size()
275
+ if not hasattr(cls, '_glyph_cache_by_font'):
276
+ cls._glyph_cache_by_font = {}
277
+ if font_key not in cls._glyph_cache_by_font:
278
+ from datacut.mobject.svg.typst_mobject import Typst
279
+ from datacut.mobject.types.vectorized_mobject import VGroup, VMobject
280
+ chars = '0123456789.-+–, i'
281
+ t = await Typst.create(chars, isolate=tuple(chars), font_size=self.get_font_size(), **self.text_config)
282
+ cache = {}
283
+ for idx, ch in enumerate(chars):
284
+ indices = t.find_submobject_indices_by_span((idx, idx + 1))
285
+ if indices:
286
+ mob = VGroup(*(t.submobjects[i].copy() for i in indices))
287
+ mob.font_size = self.get_font_size()
288
+ cache[ch] = mob
289
+ blank = VMobject()
290
+ blank.font_size = self.get_font_size()
291
+ cache[' '] = blank
292
+ cls._glyph_cache_by_font[font_key] = cache
293
+ self._glyph_cache = cls._glyph_cache_by_font[font_key]
294
+ ''').body
295
+ create_body.extend(cache_logic)
296
+ render = ast.Expr(value=ast.Call(
297
+ func=ast.Attribute(value=ast.Name(id='self', ctx=ast.Load()), attr='set_submobjects_from_number', ctx=ast.Load()),
298
+ args=[first_arg],
299
+ keywords=[]
300
+ ))
301
+ init_colors = ast.Expr(value=ast.Call(
302
+ func=ast.Attribute(value=ast.Name(id='self', ctx=ast.Load()), attr='init_colors', ctx=ast.Load()),
303
+ args=[],
304
+ keywords=[]
305
+ ))
306
+ draw_fills = ast.Expr(value=ast.Call(
307
+ func=ast.Attribute(value=ast.Name(id='self', ctx=ast.Load()), attr='draw_fills_together_if_disjoint', ctx=ast.Load()),
308
+ args=[],
309
+ keywords=[]
310
+ ))
311
+ create_body.append(render)
312
+ create_body.append(init_colors)
313
+ create_body.append(draw_fills)
314
+ if not is_super_init:
315
+ create_body.append(stmt)
316
+
317
+ create_body.append(ast.Return(value=ast.Name(id='self', ctx=ast.Load())))
318
+
319
+ create_def = ast.AsyncFunctionDef(
320
+ name='create',
321
+ args=create_args,
322
+ body=create_body,
323
+ decorator_list=[ast.Name(id='classmethod', ctx=ast.Load())],
324
+ returns=None
325
+ )
326
+
327
+ init_node.args = ast.arguments(
328
+ posonlyargs=[],
329
+ args=[ast.arg(arg='self')],
330
+ vararg=None,
331
+ kwonlyargs=[],
332
+ kw_defaults=[],
333
+ kwarg=ast.arg(arg='kwargs'),
334
+ defaults=[]
335
+ )
336
+ init_node.body = [ast.Pass()]
337
+ node.body.append(create_def)
338
+
339
+ char_to_mob_node = ast.parse('''
340
+ def char_to_mob(self, char: str):
341
+ cache = getattr(self, '_glyph_cache', None)
342
+ if cache and char in cache:
343
+ return cache[char].copy()
344
+ return super().char_to_mob(char)
345
+ ''').body[0]
346
+ if not any(isinstance(m, (ast.FunctionDef, ast.AsyncFunctionDef)) and m.name == 'char_to_mob' for m in node.body):
347
+ node.body.append(char_to_mob_node)
348
+
349
+ # Phase 0.5: Transform functions registered via add_key_press_listner (and listener methods) into async
350
+ key_listener_methods = {
351
+ 'add_key_press_listner', 'add_key_press_listener',
352
+ 'add_key_release_listner', 'add_key_release_listener',
353
+ }
354
+
355
+ for cls_node in (n for n in ast.walk(tree) if isinstance(n, ast.ClassDef)):
356
+ for method in cls_node.body:
357
+ if isinstance(method, (ast.FunctionDef, ast.AsyncFunctionDef)):
358
+ for sub in ast.walk(method):
359
+ if isinstance(sub, ast.Call):
360
+ attr = None
361
+ if isinstance(sub.func, ast.Attribute):
362
+ attr = sub.func.attr
363
+ elif isinstance(sub.func, ast.Name):
364
+ attr = sub.func.id
365
+ if attr in key_listener_methods:
366
+ callback_arg = sub.args[0] if sub.args else next((k.value for k in sub.keywords if k.arg in ('callback', 'fn', 'func')), None)
367
+ if callback_arg is not None:
368
+ if isinstance(callback_arg, ast.Attribute) and isinstance(callback_arg.value, ast.Name) and callback_arg.value.id == 'self':
369
+ target = next((m for m in cls_node.body if isinstance(m, ast.FunctionDef) and m.name == callback_arg.attr), None)
370
+ if target:
371
+ target.__class__ = ast.AsyncFunctionDef
372
+ elif isinstance(callback_arg, ast.Name):
373
+ target = next((m for m in cls_node.body if isinstance(m, ast.FunctionDef) and m.name == callback_arg.id), None)
374
+ if target:
375
+ target.__class__ = ast.AsyncFunctionDef
376
+
377
+ for sub in ast.walk(tree):
378
+ if isinstance(sub, ast.Call):
379
+ attr = None
380
+ if isinstance(sub.func, ast.Attribute):
381
+ attr = sub.func.attr
382
+ elif isinstance(sub.func, ast.Name):
383
+ attr = sub.func.id
384
+ if attr in key_listener_methods:
385
+ callback_arg = sub.args[0] if sub.args else next((k.value for k in sub.keywords if k.arg in ('callback', 'fn', 'func')), None)
386
+ if callback_arg is not None:
387
+ target_name = None
388
+ if isinstance(callback_arg, ast.Attribute):
389
+ target_name = callback_arg.attr
390
+ elif isinstance(callback_arg, ast.Name):
391
+ target_name = callback_arg.id
392
+ if target_name:
393
+ for fn_node in ast.walk(tree):
394
+ if isinstance(fn_node, ast.FunctionDef) and fn_node.name == target_name:
395
+ fn_node.__class__ = ast.AsyncFunctionDef
396
+
397
+ # Phase 0.6: Transform construct and setup methods in Scene classes into async
398
+ scene_class_names = set(self.scene_base_aliases)
399
+ changed_scene = True
400
+ while changed_scene:
401
+ changed_scene = False
402
+ for node in ast.walk(tree):
403
+ if isinstance(node, ast.ClassDef) and node.name not in scene_class_names:
404
+ if any(
405
+ (isinstance(b, ast.Name) and (b.id == 'Scene' or b.id.endswith('Scene') or b.id in scene_class_names)) or
406
+ (isinstance(b, ast.Attribute) and (b.attr == 'Scene' or b.attr.endswith('Scene') or b.attr in scene_class_names))
407
+ for b in node.bases
408
+ ):
409
+ scene_class_names.add(node.name)
410
+ changed_scene = True
411
+
412
+ for node in ast.walk(tree):
413
+ if isinstance(node, ast.ClassDef) and (
414
+ node.name in scene_class_names or any(
415
+ (isinstance(b, ast.Name) and (b.id == 'Scene' or b.id.endswith('Scene') or b.id in scene_class_names)) or
416
+ (isinstance(b, ast.Attribute) and (b.attr == 'Scene' or b.attr.endswith('Scene') or b.attr in scene_class_names))
417
+ for b in node.bases
418
+ )
419
+ ):
420
+ for child in node.body:
421
+ if isinstance(child, ast.FunctionDef) and child.name in ('construct', 'setup'):
422
+ child.__class__ = ast.AsyncFunctionDef
423
+
424
+ # Phase 1: Transform built-in async primitives (Text.create, play_async, wait_async, etc.)
425
+ tree = self.visit(tree)
426
+
427
+ # Discover async functions exported by imported local project modules (e.g. `utils/tarjetas.py`)
428
+ imported_async_names, imported_module_async_funcs = self._discover_local_async_exports(tree)
429
+
430
+ # Phase 2: Iteratively find all functions that contain `await` and propagate to their callers
431
+ # until a fixed point is reached.
432
+ while True:
433
+ all_funcs = []
434
+ for node in ast.walk(tree):
435
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
436
+ all_funcs.append(node)
437
+
438
+ async_func_names = set(imported_async_names)
439
+ newly_marked_async = False
440
+
441
+ for func in all_funcs:
442
+ if func.name == '__init__':
443
+ continue
444
+
445
+ has_direct_await = False
446
+ for stmt in func.body:
447
+ for child in ast.walk(stmt):
448
+ if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)):
449
+ continue
450
+ if isinstance(child, ast.Await):
451
+ has_direct_await = True
452
+ break
453
+ if has_direct_await:
454
+ break
455
+
456
+ if has_direct_await or isinstance(func, ast.AsyncFunctionDef):
457
+ if isinstance(func, ast.FunctionDef):
458
+ func.__class__ = ast.AsyncFunctionDef
459
+ newly_marked_async = True
460
+ async_func_names.add(func.name)
461
+
462
+ # Propagate to variable aliases (e.g. _goldenlib_mathtex = mathtex)
463
+ for node in ast.walk(tree):
464
+ if isinstance(node, ast.Assign):
465
+ if isinstance(node.value, ast.Name) and node.value.id in async_func_names:
466
+ for target in node.targets:
467
+ if isinstance(target, ast.Name):
468
+ async_func_names.add(target.id)
469
+
470
+ # Build map from function node to its enclosing ClassDef (if any)
471
+ func_to_class = {}
472
+ for node in ast.walk(tree):
473
+ if isinstance(node, ast.ClassDef):
474
+ for item in node.body:
475
+ if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
476
+ func_to_class[item] = node
477
+
478
+ # Classify methods by class type
479
+ scene_class_names = set(self.scene_base_aliases)
480
+ changed_scene = True
481
+ while changed_scene:
482
+ changed_scene = False
483
+ for node in ast.walk(tree):
484
+ if isinstance(node, ast.ClassDef) and node.name not in scene_class_names:
485
+ if any(
486
+ (isinstance(b, ast.Name) and (b.id == 'Scene' or b.id.endswith('Scene') or b.id in scene_class_names)) or
487
+ (isinstance(b, ast.Attribute) and (b.attr == 'Scene' or b.attr.endswith('Scene') or b.attr in scene_class_names))
488
+ for b in node.bases
489
+ ):
490
+ scene_class_names.add(node.name)
491
+ changed_scene = True
492
+
493
+ scene_async_methods = set()
494
+ non_scene_async_methods = set()
495
+ non_scene_sync_methods = set()
496
+
497
+ for node in ast.walk(tree):
498
+ if isinstance(node, ast.ClassDef):
499
+ is_sc = node.name in scene_class_names or any(
500
+ (isinstance(b, ast.Name) and (b.id == 'Scene' or b.id.endswith('Scene') or b.id in scene_class_names)) or
501
+ (isinstance(b, ast.Attribute) and (b.attr == 'Scene' or b.attr.endswith('Scene') or b.attr in scene_class_names))
502
+ for b in node.bases
503
+ )
504
+ for item in node.body:
505
+ if isinstance(item, ast.AsyncFunctionDef):
506
+ if is_sc:
507
+ scene_async_methods.add(item.name)
508
+ else:
509
+ non_scene_async_methods.add(item.name)
510
+ elif isinstance(item, ast.FunctionDef):
511
+ if not is_sc:
512
+ non_scene_sync_methods.add(item.name)
513
+
514
+ non_scene_sync_methods -= non_scene_async_methods
515
+
516
+ await_added = False
517
+ transformer = self
518
+
519
+ class AwaitCallTransformer(ast.NodeTransformer):
520
+ def __init__(self, async_names, scene_async_methods, non_scene_async_methods, non_scene_sync_methods, scene_class_names):
521
+ super().__init__()
522
+ self.async_names = async_names
523
+ self.scene_async_methods = scene_async_methods
524
+ self.non_scene_async_methods = non_scene_async_methods
525
+ self.non_scene_sync_methods = non_scene_sync_methods
526
+ self.scene_class_names = scene_class_names
527
+ self.current_class = None
528
+ self.await_added = False
529
+ self.in_await = False
530
+ self.in_lambda = False
531
+ self.in_init = False
532
+
533
+ def visit_ClassDef(self, node):
534
+ prev_class = self.current_class
535
+ self.current_class = node
536
+ node = self.generic_visit(node)
537
+ self.current_class = prev_class
538
+ return node
539
+
540
+ def visit_FunctionDef(self, node):
541
+ prev_init = self.in_init
542
+ if node.name == '__init__':
543
+ self.in_init = True
544
+ node = self.generic_visit(node)
545
+ self.in_init = prev_init
546
+ return node
547
+
548
+ def visit_AsyncFunctionDef(self, node):
549
+ prev_init = self.in_init
550
+ if node.name == '__init__':
551
+ self.in_init = True
552
+ node = self.generic_visit(node)
553
+ self.in_init = prev_init
554
+ return node
555
+
556
+ def visit_Lambda(self, node):
557
+ prev_lambda = self.in_lambda
558
+ self.in_lambda = True
559
+ node = self.generic_visit(node)
560
+ self.in_lambda = prev_lambda
561
+ return node
562
+
563
+ def visit_Await(self, node):
564
+ prev = self.in_await
565
+ self.in_await = True
566
+ node.value = self.visit(node.value)
567
+ self.in_await = prev
568
+ return node
569
+
570
+ def visit_Call(self, node):
571
+ prev = self.in_await
572
+ self.in_await = False
573
+ node = self.generic_visit(node)
574
+ self.in_await = prev
575
+
576
+ if self.in_await:
577
+ return node
578
+
579
+ func_name = None
580
+ is_attr = False
581
+ if isinstance(node.func, ast.Name):
582
+ func_name = node.func.id
583
+ elif isinstance(node.func, ast.Attribute):
584
+ func_name = node.func.attr
585
+ is_attr = True
586
+
587
+ if func_name == '__init__':
588
+ return node
589
+
590
+ if is_attr and func_name in SYNCHRONOUS_MOBJECT_METHODS:
591
+ return node
592
+
593
+ should_await = False
594
+ if not is_attr:
595
+ if func_name in self.async_names and func_name != 'construct':
596
+ should_await = True
597
+ else:
598
+ val = node.func.value
599
+ is_self_or_super = False
600
+ if isinstance(val, ast.Name) and val.id in ('self', 'cls', 'scene'):
601
+ is_self_or_super = True
602
+ elif isinstance(val, ast.Call):
603
+ if (isinstance(val.func, ast.Name) and val.func.id == 'super') or \
604
+ (isinstance(val.func, ast.Attribute) and val.func.attr == 'super'):
605
+ is_self_or_super = True
606
+ elif isinstance(val, ast.Attribute) and isinstance(val.value, ast.Name) and val.value.id == 'self' and val.attr == 'scene':
607
+ is_self_or_super = True
608
+
609
+ if is_self_or_super:
610
+ if isinstance(val, ast.Name) and val.id in ('self', 'cls') and self.current_class is not None:
611
+ current_is_scene = (
612
+ self.current_class.name in self.scene_class_names or
613
+ any(
614
+ (isinstance(b, ast.Name) and (b.id == 'Scene' or b.id.endswith('Scene') or b.id in self.scene_class_names)) or
615
+ (isinstance(b, ast.Attribute) and (b.attr == 'Scene' or b.attr.endswith('Scene') or b.attr in self.scene_class_names))
616
+ for b in self.current_class.bases
617
+ )
618
+ )
619
+ current_class_async = {
620
+ m.name for m in self.current_class.body if isinstance(m, ast.AsyncFunctionDef)
621
+ }
622
+ current_class_sync = {
623
+ m.name for m in self.current_class.body if isinstance(m, ast.FunctionDef)
624
+ }
625
+ if func_name in current_class_sync:
626
+ should_await = False
627
+ elif func_name in current_class_async and func_name != 'construct':
628
+ should_await = True
629
+ elif current_is_scene and (func_name in self.scene_async_methods or func_name in self.async_names) and func_name != 'construct':
630
+ should_await = True
631
+ elif not current_is_scene and func_name in self.non_scene_async_methods and func_name != 'construct':
632
+ should_await = True
633
+ else:
634
+ if func_name in self.async_names and func_name != 'construct':
635
+ should_await = True
636
+ else:
637
+ if func_name == 'create' and transformer._is_create_mobject_expr(val):
638
+ should_await = True
639
+ elif isinstance(val, ast.Name) and func_name in imported_module_async_funcs.get(val.id, ()):
640
+ should_await = True
641
+ elif func_name in self.non_scene_async_methods:
642
+ should_await = True
643
+ elif func_name in self.non_scene_sync_methods:
644
+ should_await = False
645
+ elif func_name in self.scene_async_methods:
646
+ should_await = False
647
+ else:
648
+ should_await = False
649
+
650
+ if should_await:
651
+ if self.in_init:
652
+ return node
653
+ if self.in_lambda:
654
+ transformer.used_schedule_helper = True
655
+ return ast.copy_location(
656
+ ast.Call(
657
+ func=ast.Name(id='_browser_schedule_task', ctx=ast.Load()),
658
+ args=[node],
659
+ keywords=[]
660
+ ),
661
+ node
662
+ )
663
+ else:
664
+ self.await_added = True
665
+ return ast.copy_location(ast.Await(value=node), node)
666
+
667
+ return node
668
+
669
+ def visit_Starred(self, node):
670
+ node = self.generic_visit(node)
671
+ if isinstance(node.value, ast.GeneratorExp):
672
+ if any(isinstance(c, ast.Await) for c in ast.walk(node.value)):
673
+ node.value = ast.ListComp(
674
+ elt=node.value.elt,
675
+ generators=node.value.generators
676
+ )
677
+ return node
678
+
679
+ caller_transformer = AwaitCallTransformer(
680
+ async_func_names,
681
+ scene_async_methods=scene_async_methods,
682
+ non_scene_async_methods=non_scene_async_methods,
683
+ non_scene_sync_methods=non_scene_sync_methods,
684
+ scene_class_names=scene_class_names,
685
+ )
686
+ for func in all_funcs:
687
+ prev_init = caller_transformer.in_init
688
+ if func.name == '__init__':
689
+ caller_transformer.in_init = True
690
+ caller_transformer.current_class = func_to_class.get(func)
691
+ new_body = []
692
+ for stmt in func.body:
693
+ res = caller_transformer.visit(stmt)
694
+ if isinstance(res, list):
695
+ new_body.extend(res)
696
+ else:
697
+ new_body.append(res)
698
+ func.body = new_body
699
+ caller_transformer.in_init = prev_init
700
+
701
+ if caller_transformer.await_added:
702
+ await_added = True
703
+
704
+ if not newly_marked_async and not await_added:
705
+ break
706
+
707
+ # Ensure any Scene construct or setup method is AsyncFunctionDef
708
+ for node in ast.walk(tree):
709
+ if isinstance(node, ast.ClassDef):
710
+ is_scene = (
711
+ node.name in scene_class_names or
712
+ any(
713
+ (isinstance(b, ast.Name) and (b.id == 'Scene' or b.id.endswith('Scene') or b.id in scene_class_names)) or
714
+ (isinstance(b, ast.Attribute) and (b.attr == 'Scene' or b.attr.endswith('Scene') or b.attr in scene_class_names))
715
+ for b in node.bases
716
+ )
717
+ )
718
+ if is_scene:
719
+ for child in node.body:
720
+ if isinstance(child, ast.FunctionDef) and child.name in ('construct', 'setup'):
721
+ child.__class__ = ast.AsyncFunctionDef
722
+
723
+ existing_methods = {
724
+ m.name for m in node.body if isinstance(m, (ast.FunctionDef, ast.AsyncFunctionDef))
725
+ }
726
+ for base_name in ('play', 'wait', 'hold_loop'):
727
+ async_name = f'{base_name}_async'
728
+ if base_name in existing_methods and async_name not in existing_methods:
729
+ assign_node = ast.Assign(
730
+ targets=[ast.Name(id=async_name, ctx=ast.Store())],
731
+ value=ast.Name(id=base_name, ctx=ast.Load())
732
+ )
733
+ ast.copy_location(assign_node, node)
734
+ node.body.append(assign_node)
735
+
736
+ # Phase 2.5: Transform calls to variable functions in async functions
737
+ import builtins
738
+ import importlib
739
+ try:
740
+ import datacut
741
+ _manim_symbols = set(dir(datacut))
742
+ except Exception:
743
+ _manim_symbols = set()
744
+
745
+ _builtin_names = set(dir(builtins))
746
+ top_level_names = {
747
+ n.name for n in getattr(tree, 'body', [])
748
+ if isinstance(n, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef))
749
+ }
750
+ imported_names = set()
751
+ for n in ast.walk(tree):
752
+ if isinstance(n, ast.Import):
753
+ for alias in n.names:
754
+ imported_names.add(alias.asname or alias.name.split('.')[0])
755
+ elif isinstance(n, ast.ImportFrom):
756
+ if n.module and any(alias.name == '*' for alias in n.names):
757
+ try:
758
+ _star_mod = importlib.import_module(n.module)
759
+ _star_all = getattr(_star_mod, '__all__', None)
760
+ if isinstance(_star_all, (list, tuple, set)) and len(_star_all) > 0:
761
+ imported_names.update(x for x in _star_all if isinstance(x, str))
762
+ else:
763
+ imported_names.update(x for x in dir(_star_mod) if not x.startswith('_'))
764
+ except Exception:
765
+ pass
766
+ for alias in n.names:
767
+ if alias.name != '*':
768
+ imported_names.add(alias.asname or alias.name)
769
+
770
+ known_globals = (
771
+ _builtin_names
772
+ | _manim_symbols
773
+ | top_level_names
774
+ | imported_names
775
+ | {'self', 'super', 'cls'}
776
+ | self.async_create_mobjects
777
+ | self.sync_create_mobjects
778
+ | self.number_line_names
779
+ | self.manim_module_aliases
780
+ )
781
+
782
+ def is_variable_call(call_node: ast.Call) -> bool:
783
+ if not isinstance(call_node.func, ast.Name):
784
+ return False
785
+ if call_node.func.id in known_globals:
786
+ return False
787
+ return True
788
+
789
+ def transform_statement_list(stmts: list[ast.stmt]) -> list[ast.stmt]:
790
+ new_stmts = []
791
+ for stmt in stmts:
792
+ if isinstance(stmt, ast.If):
793
+ stmt.body = transform_statement_list(stmt.body)
794
+ stmt.orelse = transform_statement_list(stmt.orelse)
795
+ new_stmts.append(stmt)
796
+ elif isinstance(stmt, (ast.For, ast.While)):
797
+ stmt.body = transform_statement_list(stmt.body)
798
+ stmt.orelse = transform_statement_list(stmt.orelse)
799
+ new_stmts.append(stmt)
800
+ elif isinstance(stmt, ast.Try):
801
+ stmt.body = transform_statement_list(stmt.body)
802
+ for h in stmt.handlers:
803
+ h.body = transform_statement_list(h.body)
804
+ stmt.orelse = transform_statement_list(stmt.orelse)
805
+ stmt.finalbody = transform_statement_list(stmt.finalbody)
806
+ new_stmts.append(stmt)
807
+ elif isinstance(stmt, ast.With):
808
+ stmt.body = transform_statement_list(stmt.body)
809
+ new_stmts.append(stmt)
810
+ elif isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
811
+ new_stmts.append(stmt)
812
+ elif isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Call) and is_variable_call(stmt.value):
813
+ self.used_inspect = True
814
+ temp_var = '_res'
815
+ assign_node = ast.Assign(
816
+ targets=[ast.Name(id=temp_var, ctx=ast.Store())],
817
+ value=stmt.value
818
+ )
819
+ ast.copy_location(assign_node, stmt)
820
+ check_node = ast.If(
821
+ test=ast.Call(
822
+ func=ast.Attribute(
823
+ value=ast.Name(id='inspect', ctx=ast.Load()),
824
+ attr='iscoroutine',
825
+ ctx=ast.Load()
826
+ ),
827
+ args=[ast.Name(id=temp_var, ctx=ast.Load())],
828
+ keywords=[]
829
+ ),
830
+ body=[
831
+ ast.Assign(
832
+ targets=[ast.Name(id=temp_var, ctx=ast.Store())],
833
+ value=ast.Await(value=ast.Name(id=temp_var, ctx=ast.Load()))
834
+ )
835
+ ],
836
+ orelse=[]
837
+ )
838
+ ast.copy_location(check_node, stmt)
839
+ ast.copy_location(check_node.body[0], stmt)
840
+ new_stmts.extend([assign_node, check_node])
841
+ elif isinstance(stmt, ast.Assign) and isinstance(stmt.value, ast.Call) and is_variable_call(stmt.value):
842
+ self.used_inspect = True
843
+ if len(stmt.targets) == 1 and isinstance(stmt.targets[0], ast.Name):
844
+ var_name = stmt.targets[0].id
845
+ new_stmts.append(stmt)
846
+ check_node = ast.If(
847
+ test=ast.Call(
848
+ func=ast.Attribute(
849
+ value=ast.Name(id='inspect', ctx=ast.Load()),
850
+ attr='iscoroutine',
851
+ ctx=ast.Load()
852
+ ),
853
+ args=[ast.Name(id=var_name, ctx=ast.Load())],
854
+ keywords=[]
855
+ ),
856
+ body=[
857
+ ast.Assign(
858
+ targets=[ast.Name(id=var_name, ctx=ast.Store())],
859
+ value=ast.Await(value=ast.Name(id=var_name, ctx=ast.Load()))
860
+ )
861
+ ],
862
+ orelse=[]
863
+ )
864
+ ast.copy_location(check_node, stmt)
865
+ ast.copy_location(check_node.body[0], stmt)
866
+ new_stmts.append(check_node)
867
+ else:
868
+ temp_var = '_res'
869
+ assign_node = ast.Assign(
870
+ targets=[ast.Name(id=temp_var, ctx=ast.Store())],
871
+ value=stmt.value
872
+ )
873
+ ast.copy_location(assign_node, stmt)
874
+ check_node = ast.If(
875
+ test=ast.Call(
876
+ func=ast.Attribute(
877
+ value=ast.Name(id='inspect', ctx=ast.Load()),
878
+ attr='iscoroutine',
879
+ ctx=ast.Load()
880
+ ),
881
+ args=[ast.Name(id=temp_var, ctx=ast.Load())],
882
+ keywords=[]
883
+ ),
884
+ body=[
885
+ ast.Assign(
886
+ targets=[ast.Name(id=temp_var, ctx=ast.Store())],
887
+ value=ast.Await(value=ast.Name(id=temp_var, ctx=ast.Load()))
888
+ )
889
+ ],
890
+ orelse=[]
891
+ )
892
+ ast.copy_location(check_node, stmt)
893
+ ast.copy_location(check_node.body[0], stmt)
894
+ final_assign = ast.Assign(
895
+ targets=stmt.targets,
896
+ value=ast.Name(id=temp_var, ctx=ast.Load())
897
+ )
898
+ ast.copy_location(final_assign, stmt)
899
+ new_stmts.extend([assign_node, check_node, final_assign])
900
+ elif isinstance(stmt, ast.Return) and isinstance(stmt.value, ast.Call) and is_variable_call(stmt.value):
901
+ self.used_inspect = True
902
+ temp_var = '_res'
903
+ assign_node = ast.Assign(
904
+ targets=[ast.Name(id=temp_var, ctx=ast.Store())],
905
+ value=stmt.value
906
+ )
907
+ ast.copy_location(assign_node, stmt)
908
+ check_node = ast.If(
909
+ test=ast.Call(
910
+ func=ast.Attribute(
911
+ value=ast.Name(id='inspect', ctx=ast.Load()),
912
+ attr='iscoroutine',
913
+ ctx=ast.Load()
914
+ ),
915
+ args=[ast.Name(id=temp_var, ctx=ast.Load())],
916
+ keywords=[]
917
+ ),
918
+ body=[
919
+ ast.Assign(
920
+ targets=[ast.Name(id=temp_var, ctx=ast.Store())],
921
+ value=ast.Await(value=ast.Name(id=temp_var, ctx=ast.Load()))
922
+ )
923
+ ],
924
+ orelse=[]
925
+ )
926
+ ast.copy_location(check_node, stmt)
927
+ ast.copy_location(check_node.body[0], stmt)
928
+ ret_node = ast.Return(value=ast.Name(id=temp_var, ctx=ast.Load()))
929
+ ast.copy_location(ret_node, stmt)
930
+ new_stmts.extend([assign_node, check_node, ret_node])
931
+ else:
932
+ new_stmts.append(stmt)
933
+ return new_stmts
934
+
935
+ for node in ast.walk(tree):
936
+ if isinstance(node, ast.AsyncFunctionDef):
937
+ node.body = transform_statement_list(node.body)
938
+
939
+ if self.used_inspect:
940
+ has_inspect = any(
941
+ isinstance(n, ast.Import) and any(alias.name == 'inspect' for alias in n.names)
942
+ for n in getattr(tree, 'body', [])
943
+ )
944
+ if not has_inspect:
945
+ idx = 0
946
+ while idx < len(tree.body):
947
+ item = tree.body[idx]
948
+ if isinstance(item, ast.Expr) and isinstance(item.value, ast.Constant) and isinstance(item.value.value, str):
949
+ idx += 1
950
+ elif isinstance(item, ast.ImportFrom) and item.module == '__future__':
951
+ idx += 1
952
+ else:
953
+ break
954
+ tree.body.insert(idx, ast.Import(names=[ast.alias(name='inspect', asname=None)]))
955
+
956
+ if self.used_call_async_helper:
957
+ has_call_helper = any(
958
+ isinstance(n, ast.AsyncFunctionDef) and n.name == '_browser_call_async'
959
+ for n in getattr(tree, 'body', [])
960
+ )
961
+ if not has_call_helper:
962
+ call_helper_code = (
963
+ "async def _browser_call_async(obj, method_name, *args, **kwargs):\n"
964
+ " async_method = getattr(obj, f'{method_name}_async', None)\n"
965
+ " if async_method is not None:\n"
966
+ " return await async_method(*args, **kwargs)\n"
967
+ " return getattr(obj, method_name)(*args, **kwargs)\n"
968
+ )
969
+ tree.body = ast.parse(call_helper_code).body + tree.body
970
+
971
+ if self.used_schedule_helper:
972
+ has_helper = any(
973
+ isinstance(n, ast.FunctionDef) and n.name == '_browser_schedule_task'
974
+ for n in getattr(tree, 'body', [])
975
+ )
976
+ if not has_helper:
977
+ helper_code = (
978
+ "def _browser_schedule_task(coro_or_val):\n"
979
+ " import asyncio\n"
980
+ " import inspect\n"
981
+ " if inspect.isawaitable(coro_or_val):\n"
982
+ " return asyncio.create_task(coro_or_val)\n"
983
+ " return coro_or_val\n"
984
+ )
985
+ tree.body = ast.parse(helper_code).body + tree.body
986
+
987
+ return tree
988
+
989
+ def visit_FunctionDef(self, node):
990
+ prev_init = self.in_init
991
+ if node.name == '__init__':
992
+ self.in_init = True
993
+ node = self.generic_visit(node)
994
+ self.in_init = prev_init
995
+ return node
996
+
997
+ def visit_AsyncFunctionDef(self, node):
998
+ prev_init = self.in_init
999
+ if node.name == '__init__':
1000
+ self.in_init = True
1001
+ node = self.generic_visit(node)
1002
+ self.in_init = prev_init
1003
+ return node
1004
+
1005
+ def visit_Lambda(self, node):
1006
+ prev = self.in_lambda
1007
+ self.in_lambda = True
1008
+ node = self.generic_visit(node)
1009
+ self.in_lambda = prev
1010
+ return node
1011
+
1012
+ def visit_Await(self, node):
1013
+ previous = self.in_await
1014
+ self.in_await = True
1015
+ node.value = self.visit(node.value)
1016
+ self.in_await = previous
1017
+ return node
1018
+
1019
+ def visit_ClassDef(self, node):
1020
+ node = self.generic_visit(node)
1021
+ is_scene_class = any(
1022
+ (
1023
+ isinstance(base, ast.Name)
1024
+ and (base.id == 'Scene' or base.id.endswith('Scene') or base.id in self.scene_base_aliases)
1025
+ )
1026
+ or (
1027
+ isinstance(base, ast.Attribute)
1028
+ and (base.attr == 'Scene' or base.attr.endswith('Scene'))
1029
+ )
1030
+ for base in node.bases
1031
+ )
1032
+
1033
+ if is_scene_class:
1034
+ for child in node.body:
1035
+ if isinstance(child, ast.FunctionDef) and child.name in ('construct', 'setup'):
1036
+ child.__class__ = ast.AsyncFunctionDef
1037
+
1038
+ return node
1039
+
1040
+ def visit_Call(self, node):
1041
+ node = self.generic_visit(node)
1042
+
1043
+ if self.in_init:
1044
+ return node
1045
+
1046
+ if (
1047
+ not self.in_await
1048
+ and isinstance(node.func, ast.Attribute)
1049
+ and node.func.attr == 'create'
1050
+ and self._is_create_mobject_expr(node.func.value)
1051
+ ):
1052
+ self.changed = True
1053
+ if self.in_lambda:
1054
+ self.used_schedule_helper = True
1055
+ return ast.copy_location(
1056
+ ast.Call(func=ast.Name(id='_browser_schedule_task', ctx=ast.Load()), args=[node], keywords=[]),
1057
+ node
1058
+ )
1059
+ return ast.copy_location(ast.Await(node), node)
1060
+
1061
+ if not self.in_await and self._is_create_mobject_expr(node.func):
1062
+ node.func = ast.Attribute(node.func, 'create', ast.Load())
1063
+ self.changed = True
1064
+ if self.in_lambda:
1065
+ self.used_schedule_helper = True
1066
+ return ast.copy_location(
1067
+ ast.Call(func=ast.Name(id='_browser_schedule_task', ctx=ast.Load()), args=[node], keywords=[]),
1068
+ node
1069
+ )
1070
+ return ast.copy_location(ast.Await(node), node)
1071
+
1072
+ if not self.in_await and isinstance(node.func, ast.Attribute):
1073
+ attr = node.func.attr
1074
+ if attr in ('play', 'wait', 'wait_until', 'wait_for_word'):
1075
+ node.func.attr = f'{attr}_async'
1076
+ self.changed = True
1077
+ if self.in_lambda:
1078
+ self.used_schedule_helper = True
1079
+ return ast.copy_location(
1080
+ ast.Call(func=ast.Name(id='_browser_schedule_task', ctx=ast.Load()), args=[node], keywords=[]),
1081
+ node
1082
+ )
1083
+ return ast.copy_location(ast.Await(node), node)
1084
+
1085
+ if attr == 'hold_loop':
1086
+ node.func.attr = 'hold_loop_async'
1087
+ self.changed = True
1088
+ if self.in_lambda:
1089
+ self.used_schedule_helper = True
1090
+ return ast.copy_location(
1091
+ ast.Call(func=ast.Name(id='_browser_schedule_task', ctx=ast.Load()), args=[node], keywords=[]),
1092
+ node
1093
+ )
1094
+ return ast.copy_location(ast.Await(node), node)
1095
+
1096
+ if attr in DIRECT_ASYNC_METHODS:
1097
+ node.func.attr = f'{attr}_async'
1098
+ self.changed = True
1099
+ if self.in_lambda:
1100
+ self.used_schedule_helper = True
1101
+ return ast.copy_location(
1102
+ ast.Call(func=ast.Name(id='_browser_schedule_task', ctx=ast.Load()), args=[node], keywords=[]),
1103
+ node
1104
+ )
1105
+ return ast.copy_location(ast.Await(node), node)
1106
+
1107
+ if attr in MAYBE_ASYNC_METHODS:
1108
+ self.changed = True
1109
+ self.used_call_async_helper = True
1110
+ helper_call = ast.copy_location(
1111
+ ast.Call(
1112
+ func=ast.Name(id='_browser_call_async', ctx=ast.Load()),
1113
+ args=[node.func.value, ast.Constant(value=attr), *node.args],
1114
+ keywords=node.keywords,
1115
+ ),
1116
+ node,
1117
+ )
1118
+ if self.in_lambda:
1119
+ self.used_schedule_helper = True
1120
+ return ast.copy_location(
1121
+ ast.Call(func=ast.Name(id='_browser_schedule_task', ctx=ast.Load()), args=[helper_call], keywords=[]),
1122
+ node
1123
+ )
1124
+ return ast.copy_location(ast.Await(helper_call), node)
1125
+
1126
+ if not self.in_await:
1127
+ if isinstance(node.func, ast.Name) and node.func.id in self.async_helper_functions:
1128
+ node.func.id = self.async_helper_functions[node.func.id]
1129
+ self.changed = True
1130
+ if self.in_lambda:
1131
+ self.used_schedule_helper = True
1132
+ return ast.copy_location(
1133
+ ast.Call(func=ast.Name(id='_browser_schedule_task', ctx=ast.Load()), args=[node], keywords=[]),
1134
+ node
1135
+ )
1136
+ return ast.copy_location(ast.Await(node), node)
1137
+ if (
1138
+ isinstance(node.func, ast.Attribute)
1139
+ and node.func.attr in ASYNC_HELPER_FUNCTIONS
1140
+ and self._is_manim_module_expr(node.func.value)
1141
+ ):
1142
+ node.func.attr = ASYNC_HELPER_FUNCTIONS[node.func.attr]
1143
+ self.changed = True
1144
+ if self.in_lambda:
1145
+ self.used_schedule_helper = True
1146
+ return ast.copy_location(
1147
+ ast.Call(func=ast.Name(id='_browser_schedule_task', ctx=ast.Load()), args=[node], keywords=[]),
1148
+ node
1149
+ )
1150
+ return ast.copy_location(ast.Await(node), node)
1151
+
1152
+ if not self.in_await and self._is_number_line_expr(node.func):
1153
+ for keyword in node.keywords:
1154
+ if keyword.arg == 'include_numbers' and _is_true_constant(keyword.value):
1155
+ keyword.value = ast.Constant(value=False)
1156
+ helper = ast.Call(ast.Name(id='_browser_add_number_line_numbers', ctx=ast.Load()), [node], [])
1157
+ self.changed = True
1158
+ if self.in_lambda:
1159
+ self.used_schedule_helper = True
1160
+ return ast.copy_location(
1161
+ ast.Call(func=ast.Name(id='_browser_schedule_task', ctx=ast.Load()), args=[helper], keywords=[]),
1162
+ node
1163
+ )
1164
+ return ast.copy_location(ast.Await(helper), node)
1165
+
1166
+ return node
1167
+
1168
+ def visit_Starred(self, node):
1169
+ node = self.generic_visit(node)
1170
+ if isinstance(node.value, ast.GeneratorExp):
1171
+ if any(isinstance(c, ast.Await) for c in ast.walk(node.value)):
1172
+ node.value = ast.ListComp(
1173
+ elt=node.value.elt,
1174
+ generators=node.value.generators
1175
+ )
1176
+ return node
1177
+
1178
+
1179
+ def transform_browser_source(source: str) -> str:
1180
+ tree = ast.parse(source)
1181
+ tree = _BrowserTransformer().transform(tree)
1182
+ ast.fix_missing_locations(tree)
1183
+ return ast.unparse(tree)
1184
+
1185
+
1186
+ def compile_browser_source(source: str, filename: str = "<editor>", top_level_await: bool = False):
1187
+ """
1188
+ The same transform, compiled straight from the tree rather than from the code written back
1189
+ out of it, so that every line keeps its number in `source`: an error says where it is in
1190
+ what was written, and the scene's timeline knows which line each play was called from, see
1191
+ datacut.scene.timeline. The source is kept where tracebacks look for lines.
1192
+
1193
+ With `top_level_await`, module-level code may await (the transform makes `Text(...)` and
1194
+ the like awaited wherever they are, so a plain script outside any Scene needs it). Running
1195
+ such code with `eval(code, namespace)` then gives a coroutine to await.
1196
+ """
1197
+ import linecache
1198
+ tree = ast.parse(source, filename)
1199
+ tree = _BrowserTransformer().transform(tree)
1200
+ ast.fix_missing_locations(tree)
1201
+ flags = ast.PyCF_ALLOW_TOP_LEVEL_AWAIT if top_level_await else 0
1202
+ try:
1203
+ code = compile(tree, filename, "exec", flags=flags)
1204
+ except (SyntaxError, TypeError, ValueError):
1205
+ # A tree the transform left unfit to compile as it stands: through its text, the
1206
+ # lines' numbers being lost
1207
+ code = compile(ast.unparse(tree), filename, "exec", flags=flags)
1208
+ linecache.cache[filename] = (len(source), None, source.splitlines(True), filename)
1209
+ return code
1210
+
1211
+
1212
+ async def _browser_add_number_line_numbers(line):
1213
+ await line.add_numbers_async(excluding=line.numbers_to_exclude)
1214
+ return line
1215
+
1216
+
1217
+ class _BrowserAssetsLoader:
1218
+ """Loads local `.py` modules under `/assets` through `compile_browser_source`."""
1219
+
1220
+ def __init__(self, fullname: str, origin: str):
1221
+ self.fullname = fullname
1222
+ self.origin = origin
1223
+
1224
+ def create_module(self, spec):
1225
+ return None
1226
+
1227
+ def exec_module(self, module):
1228
+ with open(self.origin, "r", encoding="utf-8") as f:
1229
+ source = f.read()
1230
+ module.__dict__.setdefault("_browser_schedule_task", _browser_schedule_task)
1231
+ module.__dict__.setdefault("_browser_call_async", _browser_call_async)
1232
+ module.__dict__.setdefault("_browser_add_number_line_numbers", _browser_add_number_line_numbers)
1233
+ code = compile_browser_source(source, self.origin)
1234
+ exec(code, module.__dict__, module.__dict__)
1235
+
1236
+
1237
+ class _BrowserAssetsFinder:
1238
+ """MetaPathFinder that transforms local project `.py` files on import in Pyodide."""
1239
+
1240
+ def __init__(self, root_dir: str = "/assets"):
1241
+ import os
1242
+ self.root_dir = os.path.abspath(root_dir)
1243
+
1244
+ def find_spec(self, fullname: str, path=None, target=None):
1245
+ import importlib.machinery
1246
+ import os
1247
+
1248
+ if not fullname or fullname == "datacut" or fullname.startswith("datacut."):
1249
+ return None
1250
+ if not os.path.isdir(self.root_dir):
1251
+ return None
1252
+
1253
+ parts = fullname.split(".")
1254
+ py_file = os.path.join(self.root_dir, *parts) + ".py"
1255
+ if os.path.isfile(py_file):
1256
+ loader = _BrowserAssetsLoader(fullname, py_file)
1257
+ return importlib.machinery.ModuleSpec(fullname, loader, origin=py_file)
1258
+
1259
+ pkg_dir = os.path.join(self.root_dir, *parts)
1260
+ if os.path.isdir(pkg_dir):
1261
+ pkg_init = os.path.join(pkg_dir, "__init__.py")
1262
+ if os.path.isfile(pkg_init):
1263
+ loader = _BrowserAssetsLoader(fullname, pkg_init)
1264
+ spec = importlib.machinery.ModuleSpec(fullname, loader, origin=pkg_init, is_package=True)
1265
+ spec.submodule_search_locations = [pkg_dir]
1266
+ return spec
1267
+ # Namespace package (directory without __init__.py, e.g. `utils/tarjetas.py`)
1268
+ spec = importlib.machinery.ModuleSpec(fullname, None, is_package=True)
1269
+ spec.submodule_search_locations = [pkg_dir]
1270
+ return spec
1271
+
1272
+ return None
1273
+
1274
+
1275
+ def install_browser_import_hook(root_dir: str = "/assets") -> None:
1276
+ """Ensure local project modules under `root_dir` are browser-transformed when imported."""
1277
+ import os
1278
+ import sys
1279
+
1280
+ abs_root = os.path.abspath(root_dir)
1281
+ for finder in sys.meta_path:
1282
+ if isinstance(finder, _BrowserAssetsFinder) and finder.root_dir == abs_root:
1283
+ return
1284
+ sys.meta_path.insert(0, _BrowserAssetsFinder(abs_root))
1285
+
1286
+
1287
+ __all__ = [
1288
+ 'SYNC_CREATE_MOBJECTS', 'ASYNC_CREATE_MOBJECTS', 'DIRECT_ASYNC_METHODS',
1289
+ 'MAYBE_ASYNC_METHODS', 'ASYNC_HELPER_FUNCTIONS', '_browser_schedule_task',
1290
+ '_browser_call_async', '_browser_add_number_line_numbers',
1291
+ 'install_browser_import_hook', 'transform_browser_source',
1292
+ 'compile_browser_source',
1293
+ ]