sreepathi-ravikumar commited on
Commit
3e20fac
·
verified ·
1 Parent(s): af34da3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +5 -135
app.py CHANGED
@@ -239,144 +239,14 @@ def generate_video():
239
 
240
 
241
 
242
- try:
243
- raw_data = request.get_json()
244
- if raw_data is None:
245
- return jsonify({"error": "Invalid or missing JSON in request body"}), 400
246
-
247
- # Extract slides; handle if input is full dict or just list
248
- if isinstance(raw_data, dict) and "slides" in raw_data:
249
- nlist = raw_data["slides"]
250
- elif isinstance(raw_data, list):
251
- nlist = raw_data
252
- else:
253
- return jsonify({"error": "Expected 'slides' array or top-level array in JSON"}), 400
254
-
255
- datalst = []
256
- for line in nlist:
257
- if not isinstance(line, (list, tuple)) or len(line) < 4:
258
- return jsonify({"error": f"Invalid slide format at index {len(datalst)}"}), 400
259
- datalst.append({
260
- "type": str(line[0]).strip(),
261
- "content": str(line[1]).strip(),
262
- "animation": str(line[2]).strip().replace(" ", ""),
263
- "duration": line[3] # Assumes float/int; JSON parses it natively
264
- })
265
-
266
- data = {
267
- "video_settings": {
268
- "background_color": "#0f0f23",
269
- "text_color": "WHITE",
270
- "highlight_color": "YELLOW",
271
- "font": "CMU Serif",
272
- "text_size": 36,
273
- "equation_size": 42,
274
- "title_size": 48
275
- },
276
- "slides": datalst
277
- }
278
-
279
- print(f"✅ Parsed {len(data['slides'])} slides from JSON.")
280
-
281
- except Exception as parse_err:
282
- print(f"JSON parse error: {parse_err}")
283
- return jsonify({"error": "Failed to parse JSON body", "details": str(parse_err)}), 400
284
- # Now proceed with video generation using 'data'
285
- print(json.dumps(data, indent=2)) # For debugging
286
- # ✅ Final validation
287
- if "slides" not in data or not data["slides"]:
288
- return jsonify({"error": "No slides provided in request"}), 400
289
-
290
- print(f"✅ Parsed {len(data['slides'])} slides successfully.")
291
-
292
- # Validate input
293
- if "slides" not in data or not data["slides"]:
294
- return jsonify({"error": "No slides provided in request"}), 400
295
-
296
- print(f"Received request with {len(data['slides'])} slides")
297
-
298
- # Create unique temporary directory
299
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
300
- temp_work_dir = os.path.join(TEMP_DIR, f"manim_{timestamp}")
301
- os.makedirs(temp_work_dir, exist_ok=True)
302
-
303
- # Generate Manim script
304
- script_path = os.path.join(temp_work_dir, "scene.py")
305
- create_manim_script(data, script_path)
306
- print(f"Created Manim script at {script_path}")
307
-
308
- # Render video using subprocess
309
- quality = request.args.get('quality', 'l') # l=low, m=medium, h=high
310
- render_command = [
311
- "manim",
312
- f"-q{quality}",
313
- "--disable_caching",
314
- "--media_dir", temp_work_dir,
315
- script_path,
316
- "GeneratedMathScene"
317
- ]
318
 
319
- print(f"Running command: {' '.join(render_command)}")
320
-
321
- result = subprocess.run(
322
- render_command,
323
- capture_output=True,
324
- text=True,
325
- cwd=temp_work_dir,
326
- timeout=120
327
- )
328
-
329
- if result.returncode != 0:
330
- error_msg = result.stderr or result.stdout
331
- print(f"Manim rendering failed: {error_msg}")
332
- return jsonify({
333
- "error": "Manim rendering failed",
334
- "details": error_msg
335
- }), 500
336
-
337
- print("Manim rendering completed successfully")
338
-
339
- # Find generated video
340
- quality_map = {'l': '480p15', 'm': '720p30', 'h': '1080p60'}
341
- video_quality = quality_map.get(quality, '480p15')
342
-
343
- video_path = os.path.join(
344
- temp_work_dir,
345
- "videos",
346
- "scene",
347
- video_quality,
348
- "GeneratedMathScene.mp4"
349
- )
350
-
351
- if not os.path.exists(video_path):
352
- print(f"Video not found at expected path: {video_path}")
353
- return jsonify({
354
- "error": "Video file not found after rendering",
355
- "expected_path": video_path
356
- }), 500
357
-
358
- print(f"Video found at: {video_path}")
359
-
360
- # Copy to media directory
361
- output_filename = f"math_video_{timestamp}.mp4"
362
- output_path = os.path.join(MEDIA_DIR, output_filename)
363
- shutil.copy(video_path, output_path)
364
- print(f"Video copied to: {output_path}")
365
-
366
- # Clean up temp directory
367
- try:
368
- shutil.rmtree(temp_work_dir)
369
- print("Cleaned up temp directory")
370
- except Exception as e:
371
- print(f"Failed to clean temp dir: {e}")
372
 
373
  # Return video file as blob
374
- return send_file(
375
- output_path,
376
- mimetype='video/mp4',
377
- as_attachment=False,
378
- download_name=output_filename
379
- )
380
 
381
  except subprocess.TimeoutExpired:
382
  print("Video rendering timeout")
 
239
 
240
 
241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242
 
243
+ raw_data = request.get_json()
244
+ print(raw_data)
245
+
246
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
247
 
248
  # Return video file as blob
249
+ return 0
 
 
 
 
 
250
 
251
  except subprocess.TimeoutExpired:
252
  print("Video rendering timeout")