raksa-the-wildcats commited on
Commit
b8b1a1f
Β·
1 Parent(s): 92d1d5d

Sixth commit

Browse files
Files changed (2) hide show
  1. app.py +61 -16
  2. requirements.txt +14 -5
app.py CHANGED
@@ -5,6 +5,14 @@ import tempfile
5
  import shutil
6
  from pathlib import Path
7
  import time
 
 
 
 
 
 
 
 
8
 
9
  class ManimAnimationGenerator:
10
  def __init__(self):
@@ -41,8 +49,28 @@ class ManimAnimationGenerator:
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)
@@ -76,7 +104,7 @@ class ManimAnimationGenerator:
76
 
77
  # Build Manim command
78
  cmd = [
79
- "manim",
80
  quality_flag,
81
  python_file,
82
  class_name
@@ -85,13 +113,18 @@ class ManimAnimationGenerator:
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:
@@ -133,25 +166,12 @@ class ManimAnimationGenerator:
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
@@ -214,6 +234,20 @@ class MathFormula(Scene):
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...")
@@ -221,6 +255,9 @@ def generate_animation(code, quality, format_type, progress=gr.Progress()):
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
 
@@ -250,12 +287,19 @@ with gr.Blocks(title="Manim Animation Generator", theme=gr.themes.Soft()) as app
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(
@@ -328,6 +372,7 @@ with gr.Blocks(title="Manim Animation Generator", theme=gr.themes.Soft()) as app
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`
 
5
  import shutil
6
  from pathlib import Path
7
  import time
8
+ import sys
9
+
10
+ # Check if Manim is available
11
+ try:
12
+ import manim
13
+ MANIM_AVAILABLE = True
14
+ except ImportError:
15
+ MANIM_AVAILABLE = False
16
 
17
  class ManimAnimationGenerator:
18
  def __init__(self):
 
49
 
50
  return True, "Code validation passed"
51
 
52
+ def install_manim(self):
53
+ """Try to install Manim if not available"""
54
+ try:
55
+ subprocess.check_call([
56
+ sys.executable, "-m", "pip", "install",
57
+ "manim", "manimpango", "--quiet"
58
+ ])
59
+ return True, "Manim installed successfully"
60
+ except subprocess.CalledProcessError as e:
61
+ return False, f"Failed to install Manim: {str(e)}"
62
+
63
  def execute_manim_code(self, code, quality="low", format_type="gif"):
64
  """Execute Manim code and return the generated animation"""
65
+ global MANIM_AVAILABLE
66
+
67
+ # Check if Manim is available, try to install if not
68
+ if not MANIM_AVAILABLE:
69
+ success, message = self.install_manim()
70
+ if not success:
71
+ return None, f"❌ Manim Installation Error: {message}", ""
72
+ MANIM_AVAILABLE = True
73
+
74
  try:
75
  # Validate code
76
  is_valid, message = self.validate_manim_code(code)
 
104
 
105
  # Build Manim command
106
  cmd = [
107
+ sys.executable, "-m", "manim",
108
  quality_flag,
109
  python_file,
110
  class_name
 
113
  if format_flag:
114
  cmd.append(format_flag)
115
 
116
+ # Set environment variables to help with rendering
117
+ env = os.environ.copy()
118
+ env['MPLBACKEND'] = 'Agg' # Use non-interactive backend
119
+
120
  # Execute Manim
121
  result = subprocess.run(
122
  cmd,
123
  cwd=temp_dir,
124
  capture_output=True,
125
  text=True,
126
+ timeout=120, # 2 minute timeout
127
+ env=env
128
  )
129
 
130
  if result.returncode != 0:
 
166
 
167
  def find_output_file(self, temp_dir, class_name, format_type):
168
  """Find the generated output file"""
169
+ # Search recursively for the output file
 
 
 
 
 
 
 
 
170
  for root, dirs, files in os.walk(temp_dir):
171
  for file in files:
172
  if file.startswith(class_name) and file.endswith(f".{format_type}"):
173
  return os.path.join(root, file)
174
 
 
 
 
 
 
175
  return None
176
 
177
  # Initialize the generator
 
234
  self.wait()'''
235
  }
236
 
237
+ def check_manim_installation():
238
+ """Check if Manim is properly installed"""
239
+ try:
240
+ result = subprocess.run([
241
+ sys.executable, "-c", "import manim; print('Manim version:', manim.__version__)"
242
+ ], capture_output=True, text=True, timeout=10)
243
+
244
+ if result.returncode == 0:
245
+ return True, f"βœ… Manim is available: {result.stdout.strip()}"
246
+ else:
247
+ return False, f"❌ Manim import failed: {result.stderr}"
248
+ except Exception as e:
249
+ return False, f"❌ Error checking Manim: {str(e)}"
250
+
251
  def generate_animation(code, quality, format_type, progress=gr.Progress()):
252
  """Main function to generate animation"""
253
  progress(0, desc="Starting animation generation...")
 
255
  if not code.strip():
256
  return None, "❌ Please enter some Manim code", ""
257
 
258
+ progress(0.2, desc="Checking Manim installation...")
259
+ manim_ok, manim_status = check_manim_installation()
260
+
261
  progress(0.3, desc="Validating code...")
262
  result = generator.execute_manim_code(code, quality, format_type)
263
 
 
287
  3. Click "Generate Animation"
288
  4. Wait for your animation to render
289
 
290
+ ## ⚠️ Note:
291
+ This app will automatically install Manim if it's not available. First run may take longer.
292
+
293
  ## πŸ’‘ Tips:
294
  - Your code must include `from manim import *`
295
  - Create a class that inherits from `Scene`
296
  - Use the `construct` method to define your animation
297
  """)
298
 
299
+ # System status
300
+ manim_available, status_msg = check_manim_installation()
301
+ gr.Markdown(f"**System Status:** {status_msg}")
302
+
303
  with gr.Row():
304
  with gr.Column(scale=2):
305
  code_input = gr.Code(
 
372
 
373
  gr.Markdown("""
374
  ## πŸ”§ Troubleshooting:
375
+ - **Installation errors**: The app will try to install Manim automatically
376
  - **Timeout errors**: Try simpler animations or lower quality
377
  - **Import errors**: Make sure to include `from manim import *`
378
  - **Class errors**: Your class must inherit from `Scene`
requirements.txt CHANGED
@@ -1,5 +1,14 @@
1
- gradio>=4.0.0
2
- manim>=0.18.0
3
- numpy
4
- pillow
5
- ffmpeg-python
 
 
 
 
 
 
 
 
 
 
1
+ ffmpeg
2
+ libcairo2-dev
3
+ libpango1.0-dev
4
+ libgdk-pixbuf2.0-dev
5
+ libffi-dev
6
+ build-essential
7
+ pkg-config
8
+ libpangocairo-1.0-0
9
+ libcairo-gobject2
10
+ libpango-1.0-0
11
+ libgdk-pixbuf2.0-0
12
+ libharfbuzz0b
13
+ libfribidi0
14
+ libfontconfig1