Spaces:
Sleeping
Sleeping
raksa-the-wildcats
commited on
Commit
Β·
92d1d5d
1
Parent(s):
0a73588
Fifth commit
Browse files- app.py +280 -288
- requirements.txt +1 -2
app.py
CHANGED
|
@@ -1,355 +1,347 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
import tempfile
|
| 3 |
-
import os
|
| 4 |
import subprocess
|
| 5 |
-
import
|
| 6 |
-
import
|
| 7 |
import shutil
|
| 8 |
from pathlib import Path
|
| 9 |
import time
|
| 10 |
-
import threading
|
| 11 |
-
import queue
|
| 12 |
-
import matplotlib.pyplot as plt
|
| 13 |
-
import matplotlib.animation as animation
|
| 14 |
-
import numpy as np
|
| 15 |
-
from io import StringIO
|
| 16 |
-
import sys
|
| 17 |
|
| 18 |
-
class
|
| 19 |
def __init__(self):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
self.temp_dir = tempfile.mkdtemp()
|
| 21 |
-
self.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
dangerous_imports = [
|
| 26 |
-
'subprocess', 'os.system', 'eval', 'exec', 'open',
|
| 27 |
-
'compile', 'globals', 'locals', 'input', 'raw_input',
|
| 28 |
-
'file', '__import__'
|
| 29 |
-
]
|
| 30 |
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
return False, f"Dangerous operation detected: {dangerous}"
|
| 34 |
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
has_animation_logic = ('animate' in code or 'FuncAnimation' in code or 'save(' in code)
|
| 38 |
|
| 39 |
-
|
| 40 |
-
return False, "Code should use matplotlib for animations"
|
| 41 |
-
|
| 42 |
-
if not has_animation_logic:
|
| 43 |
-
return False, "Code should contain animation logic (animate function, FuncAnimation, or save call)"
|
| 44 |
-
|
| 45 |
-
return True, "Valid"
|
| 46 |
|
| 47 |
-
def
|
| 48 |
-
"""Execute
|
| 49 |
try:
|
| 50 |
# Validate code
|
| 51 |
-
is_valid, message = self.
|
| 52 |
if not is_valid:
|
| 53 |
-
return None, f"
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
-
# Create
|
| 56 |
-
|
|
|
|
|
|
|
| 57 |
|
| 58 |
-
#
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
|
| 64 |
-
#
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
'min': min, 'max': max, 'abs': abs, 'round': round, 'sum': sum,
|
| 70 |
-
'print': print, 'int': int, 'float': float, 'str': str,
|
| 71 |
-
'list': list, 'dict': dict, 'tuple': tuple, 'set': set,
|
| 72 |
-
'bool': bool, 'type': type,
|
| 73 |
-
},
|
| 74 |
-
# Pre-imported modules
|
| 75 |
-
'matplotlib': matplotlib,
|
| 76 |
-
'plt': plt,
|
| 77 |
-
'animation': animation,
|
| 78 |
-
'np': np,
|
| 79 |
-
'numpy': np,
|
| 80 |
-
'output_path': output_path,
|
| 81 |
}
|
|
|
|
| 82 |
|
| 83 |
-
#
|
| 84 |
-
|
| 85 |
|
| 86 |
-
#
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
except Exception as e:
|
| 93 |
-
|
|
|
|
| 94 |
|
| 95 |
-
def
|
| 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 |
-
# Create animation
|
| 128 |
-
anim = animation.FuncAnimation(fig, animate, frames=200, interval=50, blit=True)
|
| 129 |
-
anim.save(output_path, writer='ffmpeg', fps=20)
|
| 130 |
-
plt.close()''',
|
| 131 |
-
|
| 132 |
-
"Growing Circle": '''import matplotlib.pyplot as plt
|
| 133 |
-
import matplotlib.animation as animation
|
| 134 |
-
import numpy as np
|
| 135 |
-
|
| 136 |
-
fig, ax = plt.subplots(figsize=(8, 8))
|
| 137 |
-
ax.set_xlim(-2, 2)
|
| 138 |
-
ax.set_ylim(-2, 2)
|
| 139 |
-
ax.set_aspect('equal')
|
| 140 |
-
ax.set_title('Growing Circle')
|
| 141 |
-
|
| 142 |
-
circle = plt.Circle((0, 0), 0, fill=False, color='red', linewidth=3)
|
| 143 |
-
ax.add_patch(circle)
|
| 144 |
-
|
| 145 |
-
def animate(frame):
|
| 146 |
-
radius = (frame / 100) * 1.5
|
| 147 |
-
circle.set_radius(radius)
|
| 148 |
-
return circle,
|
| 149 |
-
|
| 150 |
-
anim = animation.FuncAnimation(fig, animate, frames=150, interval=100, blit=True)
|
| 151 |
-
anim.save(output_path, writer='ffmpeg', fps=10)
|
| 152 |
-
plt.close()''',
|
| 153 |
-
|
| 154 |
-
"Rotating Plot": '''import matplotlib.pyplot as plt
|
| 155 |
-
import matplotlib.animation as animation
|
| 156 |
-
import numpy as np
|
| 157 |
-
|
| 158 |
-
fig = plt.figure(figsize=(10, 8))
|
| 159 |
-
ax = fig.add_subplot(111, projection='3d')
|
| 160 |
-
|
| 161 |
-
# Generate data
|
| 162 |
-
t = np.linspace(0, 2*np.pi, 100)
|
| 163 |
-
x = np.cos(t)
|
| 164 |
-
y = np.sin(t)
|
| 165 |
-
z = t
|
| 166 |
-
|
| 167 |
-
line, = ax.plot(x, y, z, 'b-', linewidth=2)
|
| 168 |
-
ax.set_xlabel('X')
|
| 169 |
-
ax.set_ylabel('Y')
|
| 170 |
-
ax.set_zlabel('Z')
|
| 171 |
-
ax.set_title('Rotating 3D Helix')
|
| 172 |
-
|
| 173 |
-
def animate(frame):
|
| 174 |
-
ax.view_init(elev=30, azim=frame*2)
|
| 175 |
-
return line,
|
| 176 |
-
|
| 177 |
-
anim = animation.FuncAnimation(fig, animate, frames=180, interval=100, blit=False)
|
| 178 |
-
anim.save(output_path, writer='ffmpeg', fps=10)
|
| 179 |
-
plt.close()''',
|
| 180 |
-
|
| 181 |
-
"Bar Chart Race": '''import matplotlib.pyplot as plt
|
| 182 |
-
import matplotlib.animation as animation
|
| 183 |
-
import numpy as np
|
| 184 |
|
| 185 |
-
|
|
|
|
| 186 |
|
| 187 |
-
#
|
| 188 |
-
|
| 189 |
-
|
| 190 |
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
|
| 208 |
-
|
| 209 |
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
}
|
| 214 |
|
| 215 |
-
def
|
| 216 |
-
"""
|
|
|
|
|
|
|
| 217 |
if not code.strip():
|
| 218 |
-
return None, "Please
|
| 219 |
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
return None,
|
| 230 |
|
| 231 |
def load_example(example_name):
|
| 232 |
-
"""Load example
|
| 233 |
-
return
|
| 234 |
-
|
| 235 |
-
def clear_all():
|
| 236 |
-
"""Clear all fields"""
|
| 237 |
-
return "", None, ""
|
| 238 |
-
|
| 239 |
-
# Try to install manim if not available, fallback to matplotlib-only mode
|
| 240 |
-
try:
|
| 241 |
-
import manim
|
| 242 |
-
MANIM_AVAILABLE = True
|
| 243 |
-
except ImportError:
|
| 244 |
-
MANIM_AVAILABLE = False
|
| 245 |
|
| 246 |
# Create Gradio interface
|
| 247 |
-
with gr.Blocks(title="Animation
|
| 248 |
-
if not MANIM_AVAILABLE:
|
| 249 |
-
gr.Markdown("""
|
| 250 |
-
# π¬ Animation MCP Server (Lightweight Mode)
|
| 251 |
-
|
| 252 |
-
**Note**: Full Manim is not available in this environment. This is a lightweight version using Matplotlib animations.
|
| 253 |
-
|
| 254 |
-
Create animated plots, charts, and visualizations using matplotlib's animation capabilities!
|
| 255 |
-
""")
|
| 256 |
-
else:
|
| 257 |
-
gr.Markdown("""
|
| 258 |
-
# π¬ Animation MCP Server
|
| 259 |
-
|
| 260 |
-
Create animations using matplotlib or Manim Community Edition!
|
| 261 |
-
""")
|
| 262 |
-
|
| 263 |
gr.Markdown("""
|
| 264 |
-
|
| 265 |
-
1. Write or select an animation script
|
| 266 |
-
2. Make sure your code saves the animation to `output_path`
|
| 267 |
-
3. Click "Create Animation"
|
| 268 |
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 273 |
""")
|
| 274 |
|
| 275 |
with gr.Row():
|
| 276 |
with gr.Column(scale=2):
|
| 277 |
-
gr.Markdown("### π Animation Code")
|
| 278 |
-
|
| 279 |
-
with gr.Row():
|
| 280 |
-
example_dropdown = gr.Dropdown(
|
| 281 |
-
choices=list(EXAMPLE_SCRIPTS.keys()),
|
| 282 |
-
label="Load Example",
|
| 283 |
-
value=None
|
| 284 |
-
)
|
| 285 |
-
clear_btn = gr.Button("Clear All", size="sm")
|
| 286 |
-
|
| 287 |
code_input = gr.Code(
|
| 288 |
-
label="
|
| 289 |
language="python",
|
| 290 |
-
|
| 291 |
-
|
|
|
|
| 292 |
)
|
| 293 |
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 301 |
|
| 302 |
-
|
| 303 |
-
gr.Markdown("### π₯ Output")
|
| 304 |
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
|
|
|
| 309 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 310 |
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
)
|
| 315 |
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
- Call `plt.close()` at the end to free memory
|
| 323 |
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
""")
|
| 330 |
|
| 331 |
-
# Event handlers
|
| 332 |
example_dropdown.change(
|
| 333 |
fn=load_example,
|
| 334 |
inputs=[example_dropdown],
|
| 335 |
outputs=[code_input]
|
| 336 |
)
|
| 337 |
|
| 338 |
-
|
| 339 |
-
fn=
|
| 340 |
-
outputs=[
|
| 341 |
)
|
| 342 |
|
| 343 |
-
|
| 344 |
-
fn=
|
| 345 |
-
|
| 346 |
-
outputs=[video_output, status_output]
|
| 347 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 348 |
|
| 349 |
-
# Launch the app
|
| 350 |
if __name__ == "__main__":
|
| 351 |
-
|
| 352 |
-
server_name="0.0.0.0",
|
| 353 |
-
server_port=7860,
|
| 354 |
-
share=True
|
| 355 |
-
)
|
|
|
|
| 1 |
import gradio as gr
|
|
|
|
|
|
|
| 2 |
import subprocess
|
| 3 |
+
import os
|
| 4 |
+
import tempfile
|
| 5 |
import shutil
|
| 6 |
from pathlib import Path
|
| 7 |
import time
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
+
class ManimAnimationGenerator:
|
| 10 |
def __init__(self):
|
| 11 |
+
self.temp_dir = None
|
| 12 |
+
self.output_dir = None
|
| 13 |
+
|
| 14 |
+
def setup_directories(self):
|
| 15 |
+
"""Setup temporary directories for Manim execution"""
|
| 16 |
self.temp_dir = tempfile.mkdtemp()
|
| 17 |
+
self.output_dir = os.path.join(self.temp_dir, "media", "videos", "480p15")
|
| 18 |
+
os.makedirs(self.output_dir, exist_ok=True)
|
| 19 |
+
return self.temp_dir
|
| 20 |
+
|
| 21 |
+
def cleanup_directories(self):
|
| 22 |
+
"""Clean up temporary directories"""
|
| 23 |
+
if self.temp_dir and os.path.exists(self.temp_dir):
|
| 24 |
+
shutil.rmtree(self.temp_dir)
|
| 25 |
+
self.temp_dir = None
|
| 26 |
+
self.output_dir = None
|
| 27 |
+
|
| 28 |
+
def validate_manim_code(self, code):
|
| 29 |
+
"""Basic validation of Manim code"""
|
| 30 |
+
required_imports = ["from manim import *", "import manim"]
|
| 31 |
+
has_import = any(imp in code for imp in required_imports)
|
| 32 |
|
| 33 |
+
if not has_import:
|
| 34 |
+
return False, "Code must include 'from manim import *' or 'import manim'"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
+
if "class" not in code:
|
| 37 |
+
return False, "Code must contain at least one class definition"
|
|
|
|
| 38 |
|
| 39 |
+
if "Scene" not in code:
|
| 40 |
+
return False, "Class must inherit from Scene or a Scene subclass"
|
|
|
|
| 41 |
|
| 42 |
+
return True, "Code validation passed"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
+
def execute_manim_code(self, code, quality="low", format_type="gif"):
|
| 45 |
+
"""Execute Manim code and return the generated animation"""
|
| 46 |
try:
|
| 47 |
# Validate code
|
| 48 |
+
is_valid, message = self.validate_manim_code(code)
|
| 49 |
if not is_valid:
|
| 50 |
+
return None, f"β Validation Error: {message}", ""
|
| 51 |
+
|
| 52 |
+
# Setup directories
|
| 53 |
+
temp_dir = self.setup_directories()
|
| 54 |
|
| 55 |
+
# Create Python file
|
| 56 |
+
python_file = os.path.join(temp_dir, "animation.py")
|
| 57 |
+
with open(python_file, "w") as f:
|
| 58 |
+
f.write(code)
|
| 59 |
|
| 60 |
+
# Extract class name for Manim command
|
| 61 |
+
class_name = self.extract_class_name(code)
|
| 62 |
+
if not class_name:
|
| 63 |
+
self.cleanup_directories()
|
| 64 |
+
return None, "β Error: Could not find a valid Scene class in the code", ""
|
| 65 |
|
| 66 |
+
# Quality settings
|
| 67 |
+
quality_map = {
|
| 68 |
+
"low": "-ql",
|
| 69 |
+
"medium": "-qm",
|
| 70 |
+
"high": "-qh"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
}
|
| 72 |
+
quality_flag = quality_map.get(quality, "-ql")
|
| 73 |
|
| 74 |
+
# Format settings
|
| 75 |
+
format_flag = "--format=gif" if format_type == "gif" else ""
|
| 76 |
|
| 77 |
+
# Build Manim command
|
| 78 |
+
cmd = [
|
| 79 |
+
"manim",
|
| 80 |
+
quality_flag,
|
| 81 |
+
python_file,
|
| 82 |
+
class_name
|
| 83 |
+
]
|
| 84 |
+
|
| 85 |
+
if format_flag:
|
| 86 |
+
cmd.append(format_flag)
|
| 87 |
+
|
| 88 |
+
# Execute Manim
|
| 89 |
+
result = subprocess.run(
|
| 90 |
+
cmd,
|
| 91 |
+
cwd=temp_dir,
|
| 92 |
+
capture_output=True,
|
| 93 |
+
text=True,
|
| 94 |
+
timeout=120 # 2 minute timeout
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
if result.returncode != 0:
|
| 98 |
+
error_msg = f"β Manim execution failed:\n{result.stderr}"
|
| 99 |
+
self.cleanup_directories()
|
| 100 |
+
return None, error_msg, result.stdout
|
| 101 |
+
|
| 102 |
+
# Find generated file
|
| 103 |
+
output_file = self.find_output_file(temp_dir, class_name, format_type)
|
| 104 |
+
if not output_file:
|
| 105 |
+
self.cleanup_directories()
|
| 106 |
+
return None, "β Error: Could not find generated animation file", result.stdout
|
| 107 |
+
|
| 108 |
+
# Copy to a permanent location for Gradio
|
| 109 |
+
permanent_file = f"/tmp/{class_name}_{int(time.time())}.{format_type}"
|
| 110 |
+
shutil.copy2(output_file, permanent_file)
|
| 111 |
+
|
| 112 |
+
success_msg = f"β
Animation generated successfully!\nClass: {class_name}\nQuality: {quality}\nFormat: {format_type}"
|
| 113 |
+
|
| 114 |
+
self.cleanup_directories()
|
| 115 |
+
return permanent_file, success_msg, result.stdout
|
| 116 |
+
|
| 117 |
+
except subprocess.TimeoutExpired:
|
| 118 |
+
self.cleanup_directories()
|
| 119 |
+
return None, "β Error: Animation generation timed out (2 minutes)", ""
|
| 120 |
except Exception as e:
|
| 121 |
+
self.cleanup_directories()
|
| 122 |
+
return None, f"β Error: {str(e)}", ""
|
| 123 |
|
| 124 |
+
def extract_class_name(self, code):
|
| 125 |
+
"""Extract the first Scene class name from the code"""
|
| 126 |
+
lines = code.split('\n')
|
| 127 |
+
for line in lines:
|
| 128 |
+
if line.strip().startswith('class ') and 'Scene' in line:
|
| 129 |
+
# Extract class name
|
| 130 |
+
class_def = line.strip().split('class ')[1].split('(')[0].strip()
|
| 131 |
+
return class_def
|
| 132 |
+
return None
|
| 133 |
+
|
| 134 |
+
def find_output_file(self, temp_dir, class_name, format_type):
|
| 135 |
+
"""Find the generated output file"""
|
| 136 |
+
# Common Manim output paths
|
| 137 |
+
possible_paths = [
|
| 138 |
+
os.path.join(temp_dir, "media", "videos", "480p15", f"{class_name}.{format_type}"),
|
| 139 |
+
os.path.join(temp_dir, "media", "videos", "720p30", f"{class_name}.{format_type}"),
|
| 140 |
+
os.path.join(temp_dir, "media", "videos", "1080p60", f"{class_name}.{format_type}"),
|
| 141 |
+
os.path.join(temp_dir, "media", "images", f"{class_name}.png"),
|
| 142 |
+
]
|
| 143 |
+
|
| 144 |
+
# Also search recursively
|
| 145 |
+
for root, dirs, files in os.walk(temp_dir):
|
| 146 |
+
for file in files:
|
| 147 |
+
if file.startswith(class_name) and file.endswith(f".{format_type}"):
|
| 148 |
+
return os.path.join(root, file)
|
| 149 |
+
|
| 150 |
+
# Check specific paths
|
| 151 |
+
for path in possible_paths:
|
| 152 |
+
if os.path.exists(path):
|
| 153 |
+
return path
|
| 154 |
+
|
| 155 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
|
| 157 |
+
# Initialize the generator
|
| 158 |
+
generator = ManimAnimationGenerator()
|
| 159 |
|
| 160 |
+
# Example Manim codes for users
|
| 161 |
+
example_codes = {
|
| 162 |
+
"Simple Square": '''from manim import *
|
| 163 |
|
| 164 |
+
class CreateSquare(Scene):
|
| 165 |
+
def construct(self):
|
| 166 |
+
square = Square()
|
| 167 |
+
square.set_fill(BLUE, opacity=0.5)
|
| 168 |
+
square.set_stroke(WHITE, width=2)
|
| 169 |
+
|
| 170 |
+
self.play(Create(square))
|
| 171 |
+
self.play(square.animate.rotate(PI/4))
|
| 172 |
+
self.wait()''',
|
| 173 |
|
| 174 |
+
"Moving Circle": '''from manim import *
|
| 175 |
+
|
| 176 |
+
class MovingCircle(Scene):
|
| 177 |
+
def construct(self):
|
| 178 |
+
circle = Circle()
|
| 179 |
+
circle.set_fill(RED, opacity=0.5)
|
| 180 |
+
|
| 181 |
+
self.play(Create(circle))
|
| 182 |
+
self.play(circle.animate.shift(RIGHT * 2))
|
| 183 |
+
self.play(circle.animate.shift(UP * 2))
|
| 184 |
+
self.play(circle.animate.shift(LEFT * 2))
|
| 185 |
+
self.play(circle.animate.shift(DOWN * 2))
|
| 186 |
+
self.wait()''',
|
| 187 |
|
| 188 |
+
"Text Animation": '''from manim import *
|
| 189 |
+
|
| 190 |
+
class TextAnimation(Scene):
|
| 191 |
+
def construct(self):
|
| 192 |
+
text = Text("Hello Manim!", font_size=48)
|
| 193 |
+
text2 = Text("Animated Math!", font_size=48)
|
| 194 |
+
|
| 195 |
+
self.play(Write(text))
|
| 196 |
+
self.wait()
|
| 197 |
+
self.play(Transform(text, text2))
|
| 198 |
+
self.wait()''',
|
| 199 |
|
| 200 |
+
"Mathematical Formula": '''from manim import *
|
| 201 |
|
| 202 |
+
class MathFormula(Scene):
|
| 203 |
+
def construct(self):
|
| 204 |
+
formula = MathTex(r"\\frac{d}{dx}(x^2) = 2x")
|
| 205 |
+
formula.scale(2)
|
| 206 |
+
|
| 207 |
+
self.play(Write(formula))
|
| 208 |
+
self.wait()
|
| 209 |
+
|
| 210 |
+
formula2 = MathTex(r"\\int_0^1 x^2 dx = \\frac{1}{3}")
|
| 211 |
+
formula2.scale(2)
|
| 212 |
+
|
| 213 |
+
self.play(Transform(formula, formula2))
|
| 214 |
+
self.wait()'''
|
| 215 |
}
|
| 216 |
|
| 217 |
+
def generate_animation(code, quality, format_type, progress=gr.Progress()):
|
| 218 |
+
"""Main function to generate animation"""
|
| 219 |
+
progress(0, desc="Starting animation generation...")
|
| 220 |
+
|
| 221 |
if not code.strip():
|
| 222 |
+
return None, "β Please enter some Manim code", ""
|
| 223 |
|
| 224 |
+
progress(0.3, desc="Validating code...")
|
| 225 |
+
result = generator.execute_manim_code(code, quality, format_type)
|
| 226 |
+
|
| 227 |
+
progress(0.7, desc="Generating animation...")
|
| 228 |
+
|
| 229 |
+
if result[0]: # Success
|
| 230 |
+
progress(1.0, desc="Animation generated successfully!")
|
| 231 |
+
return result[0], result[1], result[2]
|
| 232 |
+
else: # Error
|
| 233 |
+
return None, result[1], result[2]
|
| 234 |
|
| 235 |
def load_example(example_name):
|
| 236 |
+
"""Load example code"""
|
| 237 |
+
return example_codes.get(example_name, "")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
|
| 239 |
# Create Gradio interface
|
| 240 |
+
with gr.Blocks(title="Manim Animation Generator", theme=gr.themes.Soft()) as app:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
gr.Markdown("""
|
| 242 |
+
# π¬ Manim Animation Generator
|
|
|
|
|
|
|
|
|
|
| 243 |
|
| 244 |
+
Create beautiful mathematical animations using [Manim](https://www.manim.community/)!
|
| 245 |
+
Enter your Python code below and watch it come to life.
|
| 246 |
+
|
| 247 |
+
## π How to use:
|
| 248 |
+
1. Write or select example Manim code
|
| 249 |
+
2. Choose quality and format settings
|
| 250 |
+
3. Click "Generate Animation"
|
| 251 |
+
4. Wait for your animation to render
|
| 252 |
+
|
| 253 |
+
## π‘ Tips:
|
| 254 |
+
- Your code must include `from manim import *`
|
| 255 |
+
- Create a class that inherits from `Scene`
|
| 256 |
+
- Use the `construct` method to define your animation
|
| 257 |
""")
|
| 258 |
|
| 259 |
with gr.Row():
|
| 260 |
with gr.Column(scale=2):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 261 |
code_input = gr.Code(
|
| 262 |
+
label="Manim Code",
|
| 263 |
language="python",
|
| 264 |
+
placeholder="Enter your Manim code here...",
|
| 265 |
+
lines=20,
|
| 266 |
+
value=example_codes["Simple Square"]
|
| 267 |
)
|
| 268 |
|
| 269 |
+
with gr.Row():
|
| 270 |
+
quality = gr.Dropdown(
|
| 271 |
+
choices=["low", "medium", "high"],
|
| 272 |
+
value="low",
|
| 273 |
+
label="Quality"
|
| 274 |
+
)
|
| 275 |
+
format_type = gr.Dropdown(
|
| 276 |
+
choices=["gif", "mp4"],
|
| 277 |
+
value="gif",
|
| 278 |
+
label="Format"
|
| 279 |
+
)
|
| 280 |
|
| 281 |
+
generate_btn = gr.Button("π¬ Generate Animation", variant="primary", size="lg")
|
|
|
|
| 282 |
|
| 283 |
+
gr.Markdown("### π Example Codes:")
|
| 284 |
+
example_dropdown = gr.Dropdown(
|
| 285 |
+
choices=list(example_codes.keys()),
|
| 286 |
+
label="Load Example",
|
| 287 |
+
value="Simple Square"
|
| 288 |
)
|
| 289 |
+
load_example_btn = gr.Button("π Load Example")
|
| 290 |
+
|
| 291 |
+
with gr.Column(scale=2):
|
| 292 |
+
output_video = gr.File(label="Generated Animation", file_types=[".gif", ".mp4"])
|
| 293 |
+
status_output = gr.Textbox(label="Status", lines=5, max_lines=10)
|
| 294 |
+
logs_output = gr.Textbox(label="Manim Logs", lines=8, max_lines=15, visible=False)
|
| 295 |
|
| 296 |
+
with gr.Row():
|
| 297 |
+
show_logs_btn = gr.Button("Show Logs", size="sm")
|
| 298 |
+
hide_logs_btn = gr.Button("Hide Logs", size="sm")
|
|
|
|
| 299 |
|
| 300 |
+
# Event handlers
|
| 301 |
+
generate_btn.click(
|
| 302 |
+
fn=generate_animation,
|
| 303 |
+
inputs=[code_input, quality, format_type],
|
| 304 |
+
outputs=[output_video, status_output, logs_output]
|
| 305 |
+
)
|
|
|
|
| 306 |
|
| 307 |
+
load_example_btn.click(
|
| 308 |
+
fn=load_example,
|
| 309 |
+
inputs=[example_dropdown],
|
| 310 |
+
outputs=[code_input]
|
| 311 |
+
)
|
|
|
|
| 312 |
|
|
|
|
| 313 |
example_dropdown.change(
|
| 314 |
fn=load_example,
|
| 315 |
inputs=[example_dropdown],
|
| 316 |
outputs=[code_input]
|
| 317 |
)
|
| 318 |
|
| 319 |
+
show_logs_btn.click(
|
| 320 |
+
fn=lambda: gr.update(visible=True),
|
| 321 |
+
outputs=[logs_output]
|
| 322 |
)
|
| 323 |
|
| 324 |
+
hide_logs_btn.click(
|
| 325 |
+
fn=lambda: gr.update(visible=False),
|
| 326 |
+
outputs=[logs_output]
|
|
|
|
| 327 |
)
|
| 328 |
+
|
| 329 |
+
gr.Markdown("""
|
| 330 |
+
## π§ Troubleshooting:
|
| 331 |
+
- **Timeout errors**: Try simpler animations or lower quality
|
| 332 |
+
- **Import errors**: Make sure to include `from manim import *`
|
| 333 |
+
- **Class errors**: Your class must inherit from `Scene`
|
| 334 |
+
- **No output**: Check that your `construct` method has animation commands
|
| 335 |
+
|
| 336 |
+
## π― Common Manim Objects:
|
| 337 |
+
- **Shapes**: `Circle()`, `Square()`, `Triangle()`, `Rectangle()`
|
| 338 |
+
- **Text**: `Text("Hello")`, `MathTex(r"x^2")`
|
| 339 |
+
- **Animations**: `Create()`, `Write()`, `Transform()`, `FadeIn()`, `FadeOut()`
|
| 340 |
+
- **Colors**: `RED`, `BLUE`, `GREEN`, `YELLOW`, `WHITE`, `BLACK`
|
| 341 |
+
|
| 342 |
+
---
|
| 343 |
+
Made with β€οΈ using [Manim](https://www.manim.community/) and [Gradio](https://gradio.app/)
|
| 344 |
+
""")
|
| 345 |
|
|
|
|
| 346 |
if __name__ == "__main__":
|
| 347 |
+
app.launch(debug=True, share=True)
|
|
|
|
|
|
|
|
|
|
|
|
requirements.txt
CHANGED
|
@@ -1,6 +1,5 @@
|
|
| 1 |
gradio>=4.0.0
|
| 2 |
-
|
| 3 |
numpy
|
| 4 |
-
scipy
|
| 5 |
pillow
|
| 6 |
ffmpeg-python
|
|
|
|
| 1 |
gradio>=4.0.0
|
| 2 |
+
manim>=0.18.0
|
| 3 |
numpy
|
|
|
|
| 4 |
pillow
|
| 5 |
ffmpeg-python
|