devendergarg14 commited on
Commit
3689207
Β·
verified Β·
1 Parent(s): 0e385cc

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +194 -0
app.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import subprocess
4
+ import re
5
+ import time
6
+ import glob
7
+ import shutil
8
+
9
+ # ---------------------------------------------------------
10
+ # 1. Helper Functions (Dependencies for Rendering)
11
+ # ---------------------------------------------------------
12
+
13
+ def cleanup_media_directory():
14
+ """Wipes the media/videos directory to prevent caching issues."""
15
+ media_dir = os.path.join('media', 'videos')
16
+ if os.path.exists(media_dir):
17
+ print(f"🧹 Cleaning up old media directory: {media_dir}", flush=True)
18
+ try:
19
+ shutil.rmtree(media_dir)
20
+ except OSError as e:
21
+ print(f"❌ Error during cleanup: {e}", flush=True)
22
+
23
+ def make_even(n):
24
+ n = int(n)
25
+ return n if n % 2 == 0 else n + 1
26
+
27
+ def get_resolution_flags(orientation, quality):
28
+ qual_map = {
29
+ "Preview (360p)": 360, "480p": 480, "720p": 720, "1080p": 1080, "4k": 2160
30
+ }
31
+ base_h = qual_map.get(quality, 1080)
32
+ if orientation == "Landscape (16:9)":
33
+ width = make_even(base_h * (16/9)); height = make_even(base_h)
34
+ else: # Portrait (9:16)
35
+ width = make_even(base_h); height = make_even(base_h * (16/9))
36
+ return f"{width},{height}"
37
+
38
+ def scale_animation_times(code, factor):
39
+ """
40
+ Scales run_time and wait() calls, enforcing a minimum run_time to prevent render errors.
41
+ """
42
+ print(f"⚑ Scaling animation times by a factor of {factor} for preview.", flush=True)
43
+ MIN_RUN_TIME = 0.1 # A safe minimum duration for any animation clip.
44
+
45
+ def scale_runtime(m):
46
+ new_time = max(float(m.group(2)) * factor, MIN_RUN_TIME)
47
+ return f"{m.group(1)}{new_time}"
48
+
49
+ def scale_wait(m):
50
+ new_time = float(m.group(2)) * factor
51
+ return f"{m.group(1)}{new_time}"
52
+
53
+ code = re.sub(r"(run_time\s*=\s*)(\d+\.?\d*)", scale_runtime, code)
54
+ code = re.sub(r"(self\.wait\s*\(\s*)(\d+\.?\d*)", scale_wait, code)
55
+ return code
56
+
57
+ def run_manim(code_str, orientation, quality, timeout):
58
+ timeout_sec = float(timeout) if timeout and float(timeout) > 0 else None
59
+ print(f"🎬 Starting Render: {orientation} @ {quality} (Timeout: {timeout_sec}s)...", flush=True)
60
+ with open("scene.py", "w", encoding="utf-8") as f: f.write(code_str)
61
+
62
+ timestamp = int(time.time())
63
+ output_filename = f"video_{timestamp}.mp4"
64
+ res_str = get_resolution_flags(orientation, quality)
65
+ frame_rate_flags = ["--frame_rate", "15"] if quality == "Preview (360p)" else []
66
+ cmd = ["manim", "--resolution", res_str, *frame_rate_flags, "--disable_caching", "--progress_bar", "none", "scene.py", "GenScene", "-o", output_filename]
67
+ print(f"βš™οΈ Running command: {' '.join(cmd)}", flush=True)
68
+
69
+ try:
70
+ process = subprocess.run(cmd, capture_output=True, timeout=timeout_sec, check=False)
71
+ stdout_log = process.stdout.decode('utf-8', 'ignore')
72
+ stderr_log = process.stderr.decode('utf-8', 'ignore')
73
+ full_logs = f"--- MANIM STDOUT ---\n{stdout_log}\n\n--- MANIM STDERR ---\n{stderr_log}"
74
+ if process.returncode != 0:
75
+ print(f"❌ Render Failed.\n{stderr_log}", flush=True)
76
+ return None, f"⚠️ ERROR: Manim failed to render.\n{full_logs}", False
77
+
78
+ except subprocess.TimeoutExpired as e:
79
+ print(f"βŒ› Render timed out after {timeout_sec} seconds. Attempting to recover partial video.", flush=True)
80
+ stdout_log = e.stdout.decode('utf-8', 'ignore') if e.stdout else ""
81
+ stderr_log = e.stderr.decode('utf-8', 'ignore') if e.stderr else ""
82
+ timeout_logs = f"--- MANIM STDOUT ---\n{stdout_log}\n\n--- MANIM STDERR ---\n{stderr_log}"
83
+
84
+ combined_log = stdout_log + "\n" + stderr_log
85
+ path_matches = re.findall(r"movie file written in\s*'([^']+?)'", combined_log, flags=re.DOTALL)
86
+
87
+ all_paths = []
88
+ for raw_path in path_matches:
89
+ normalized = "".join(raw_path.split())
90
+ all_paths.append(normalized)
91
+
92
+ if all_paths:
93
+ last_path = all_paths[-1]
94
+ partial_files_dir = os.path.dirname(last_path)
95
+ print(f"βœ… Successfully parsed partial files directory from logs: {partial_files_dir}", flush=True)
96
+ else:
97
+ print("❌ Could not parse partial file directory from Manim logs.", flush=True)
98
+ return None, (f"❌ ERROR: Timed out, and could not find path to partial files in log.\n{timeout_logs}"), False
99
+
100
+ if not os.path.exists(partial_files_dir):
101
+ return None, f"❌ ERROR: Timed out, and parsed directory does not exist: {partial_files_dir}\n{timeout_logs}", False
102
+
103
+ partial_files = sorted(glob.glob(os.path.join(partial_files_dir, 'uncached_*.mp4')),
104
+ key=lambda f: int(re.search(r'(\d+)\.mp4$', f).group(1)))
105
+
106
+ if not partial_files:
107
+ return None, f"❌ ERROR: Timed out, but no partial movie files were found in {partial_files_dir}.\n{timeout_logs}", False
108
+
109
+ list_file_path = os.path.join(partial_files_dir, "file_list.txt")
110
+ with open(list_file_path, 'w') as f:
111
+ for pf in partial_files:
112
+ f.write(f"file '{os.path.abspath(pf)}'\n")
113
+
114
+ combined_video_path = os.path.join(os.path.dirname(partial_files_dir), f"combined_partial_{timestamp}.mp4")
115
+ ffmpeg_cmd = ["ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", list_file_path, "-c", "copy", combined_video_path]
116
+
117
+ print(f"βš™οΈ Running ffmpeg to combine {len(partial_files)} chunks...", flush=True)
118
+ ffmpeg_process = subprocess.run(ffmpeg_cmd, capture_output=True, text=True, check=False)
119
+
120
+ if ffmpeg_process.returncode == 0 and os.path.exists(combined_video_path):
121
+ print(f"βœ… Successfully combined partial video: {combined_video_path}", flush=True)
122
+ status_message = f"⚠️ WARNING: Rendering timed out. Recovered and combined {len(partial_files)} video chunks.\n\n{timeout_logs}"
123
+ return combined_video_path, status_message, True
124
+ else:
125
+ ffmpeg_logs = f"--- FFMPEG STDOUT ---\n{ffmpeg_process.stdout}\n--- FFMPEG STDERR ---\n{ffmpeg_process.stderr}"
126
+ return None, f"❌ ERROR: Timed out and failed to combine partial videos.\n{ffmpeg_logs}", False
127
+
128
+ media_base_dir = "media/videos/scene"
129
+ for root, _, files in os.walk(media_base_dir):
130
+ if output_filename in files:
131
+ final_output_path = os.path.join(root, output_filename)
132
+ print(f"βœ… Render Success: {final_output_path}", flush=True)
133
+ return final_output_path, f"βœ… Rendering Successful\n\n{full_logs}", True
134
+
135
+ print(f"❌ Final video file '{output_filename}' not found after a successful render code.", flush=True)
136
+ return None, f"Video file not created despite success code. Check logs:\n{full_logs}", False
137
+
138
+ # ---------------------------------------------------------
139
+ # 2. Main API Function
140
+ # ---------------------------------------------------------
141
+
142
+ def render_video_from_code(code, orientation, quality, timeout, preview_factor):
143
+ """Renders a video from a given Manim code string."""
144
+ try:
145
+ # --- CACHING FIX: CLEANUP BEFORE EVERY RENDER ---
146
+ cleanup_media_directory()
147
+
148
+ if not code or "from manim import" not in code:
149
+ return None, "Error: No valid code to render.", gr.Button(visible=False)
150
+
151
+ code_to_render = code
152
+ if quality == "Preview (360p)":
153
+ try:
154
+ factor = float(preview_factor)
155
+ if factor <= 0: factor = 0.5
156
+ except (ValueError, TypeError):
157
+ factor = 0.5
158
+ code_to_render = scale_animation_times(code, factor)
159
+
160
+ video_path, logs, success = run_manim(code_to_render, orientation, quality, timeout)
161
+ return video_path, logs, gr.Button(visible=not success)
162
+ except Exception as e:
163
+ return None, f"Rendering failed: {str(e)}", gr.Button(visible=True)
164
+
165
+ # ---------------------------------------------------------
166
+ # 3. Gradio Interface (API Definition)
167
+ # ---------------------------------------------------------
168
+
169
+ with gr.Blocks(title="Manim Render API") as demo:
170
+ # Hidden components to define the API signature
171
+ code_input = gr.Code(label="Python Code", language="python", value="from manim import *\nclass GenScene(Scene):\n def construct(self):\n self.add(Circle())")
172
+ orientation_opt = gr.Radio(choices=["Landscape (16:9)", "Portrait (9:16)"], value="Portrait (9:16)", label="Orientation")
173
+ quality_opt = gr.Dropdown(choices=["Preview (360p)", "480p", "720p", "1080p", "4k"], value="Preview (360p)", label="Quality")
174
+ timeout_input = gr.Number(label="Render Timeout (seconds)", value=60)
175
+ preview_speed_factor_input = gr.Number(label="Preview Speed Factor", value=0.5)
176
+
177
+ video_output = gr.Video(label="Result")
178
+ status_output = gr.Textbox(label="Status/Logs")
179
+ # This button output is required because the render function returns a button update (for UI logic)
180
+ # Even if used purely as API, we maintain the signature.
181
+ fix_btn_output = gr.Button("Fix Error & Re-render", variant="stop")
182
+
183
+ # The trigger
184
+ render_btn = gr.Button("Render")
185
+
186
+ render_btn.click(
187
+ fn=render_video_from_code,
188
+ inputs=[code_input, orientation_opt, quality_opt, timeout_input, preview_speed_factor_input],
189
+ outputs=[video_output, status_output, fix_btn_output],
190
+ api_name="render"
191
+ )
192
+
193
+ if __name__ == "__main__":
194
+ demo.launch(server_name="0.0.0.0", server_port=7860)