theminji commited on
Commit
9ed758b
·
verified ·
1 Parent(s): 212f1ce

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +9 -40
app.py CHANGED
@@ -7,7 +7,6 @@ import shutil
7
  import time
8
  from threading import Timer
9
  import uuid
10
- import sys
11
 
12
  app = Flask(__name__)
13
 
@@ -33,8 +32,6 @@ def index():
33
  last_error = None
34
  while attempt < max_retries:
35
  try:
36
- print("Calling GenAI API...")
37
- sys.stdout.flush()
38
  ai_response = client.models.generate_content(
39
  model="gemini-2.0-flash-lite-preview-02-05",
40
  contents=f"""You are 'Manimator', an expert Manim animator and coder.
@@ -48,32 +45,22 @@ You got this!! <3
48
  """
49
  )
50
 
51
- # Extract the Python code block from the AI response
52
  pattern = r"```python\s*(.*?)\s*```"
53
  match = re.search(pattern, ai_response.text, re.DOTALL)
54
  if not match:
55
  raise Exception("No python code block found in the AI response.")
56
  code = match.group(1)
57
- print("Extracted code (first 200 chars):", code[:200])
58
- sys.stdout.flush()
59
 
60
- # Determine the scene class name from the generated code
61
  scene_match = re.search(r"class\s+(\w+)\(.*Scene.*\):", code)
62
- if scene_match:
63
- scene_name = scene_match.group(1)
64
- else:
65
- scene_name = "MyScene"
66
 
67
- # Generate randomized filenames for the generated code and video
68
  code_filename = f"generated_video_{uuid.uuid4().hex}.py"
69
  video_filename = f"output_video_{uuid.uuid4().hex}.mp4"
70
 
71
- # Write the generated code file directly to /tmp
72
  code_filepath = os.path.join("/tmp", code_filename)
73
  with open(code_filepath, "w") as f:
74
  f.write(code)
75
 
76
- # Prepare the Manim command with --media_dir flag
77
  cmd = [
78
  "manim",
79
  "-qm",
@@ -82,40 +69,25 @@ You got this!! <3
82
  code_filepath,
83
  scene_name
84
  ]
85
- print("Running Manim command:", " ".join(cmd))
86
- sys.stdout.flush()
87
- result = subprocess.run(cmd, check=True, capture_output=True, text=True)
88
- print("Manim stdout:", result.stdout)
89
- print("Manim stderr:", result.stderr)
90
- sys.stdout.flush()
91
 
92
- # Debug: List the media directory structure
93
- for root, dirs, files in os.walk(media_dir):
94
- print(root, dirs, files)
95
- sys.stdout.flush()
96
-
97
- # Construct the expected output path from Manim.
98
- # With --media_dir set, output should be in:
99
- # {media_dir}/videos/<code_filename_without_.py>/720p30/<video_filename>
100
  expected_dir = os.path.join(media_dir, "videos", code_filename.replace(".py", ""), "720p30")
101
  video_path_in_media = os.path.join(expected_dir, video_filename)
102
  if not os.path.exists(video_path_in_media):
103
  raise Exception(f"Manim did not produce the expected output file at {video_path_in_media}")
104
 
105
- # Move the video file to /tmp (it will be served from here)
106
  tmp_video_path = os.path.join("/tmp", video_filename)
107
  shutil.move(video_path_in_media, tmp_video_path)
108
- # The code file is already in /tmp (at code_filepath)
109
 
110
- # Schedule deletion of both files after 10 minutes (600 seconds)
 
 
111
  def remove_files():
112
  try:
113
  if os.path.exists(tmp_video_path):
114
  os.remove(tmp_video_path)
115
- if os.path.exists(code_filepath):
116
- os.remove(code_filepath)
117
- print("Removed files:", tmp_video_path, code_filepath)
118
- sys.stdout.flush()
119
  except Exception as e:
120
  app.logger.error("Error removing files: %s", e)
121
  Timer(600, remove_files).start()
@@ -124,20 +96,17 @@ You got this!! <3
124
  return render_template("result.html", video_url=video_url)
125
 
126
  except Exception as e:
127
- print(f"Attempt {attempt + 1} failed: {type(e).__name__}: {e}")
128
- sys.stdout.flush()
129
  last_error = e
130
  attempt += 1
131
  time.sleep(1)
132
 
133
- return render_template("result.html", error=f"Error: {last_error}")
134
 
135
  return render_template("index.html")
136
 
137
  @app.route("/video/<filename>")
138
  def get_video(filename):
139
- # Serve the video file from /tmp
140
  return send_from_directory("/tmp", filename)
141
 
142
  if __name__ == "__main__":
143
- app.run(host="0.0.0.0", port=7860, debug=True)
 
7
  import time
8
  from threading import Timer
9
  import uuid
 
10
 
11
  app = Flask(__name__)
12
 
 
32
  last_error = None
33
  while attempt < max_retries:
34
  try:
 
 
35
  ai_response = client.models.generate_content(
36
  model="gemini-2.0-flash-lite-preview-02-05",
37
  contents=f"""You are 'Manimator', an expert Manim animator and coder.
 
45
  """
46
  )
47
 
 
48
  pattern = r"```python\s*(.*?)\s*```"
49
  match = re.search(pattern, ai_response.text, re.DOTALL)
50
  if not match:
51
  raise Exception("No python code block found in the AI response.")
52
  code = match.group(1)
 
 
53
 
 
54
  scene_match = re.search(r"class\s+(\w+)\(.*Scene.*\):", code)
55
+ scene_name = scene_match.group(1) if scene_match else "MyScene"
 
 
 
56
 
 
57
  code_filename = f"generated_video_{uuid.uuid4().hex}.py"
58
  video_filename = f"output_video_{uuid.uuid4().hex}.mp4"
59
 
 
60
  code_filepath = os.path.join("/tmp", code_filename)
61
  with open(code_filepath, "w") as f:
62
  f.write(code)
63
 
 
64
  cmd = [
65
  "manim",
66
  "-qm",
 
69
  code_filepath,
70
  scene_name
71
  ]
72
+ subprocess.run(cmd, check=True, capture_output=True, text=True)
 
 
 
 
 
73
 
 
 
 
 
 
 
 
 
74
  expected_dir = os.path.join(media_dir, "videos", code_filename.replace(".py", ""), "720p30")
75
  video_path_in_media = os.path.join(expected_dir, video_filename)
76
  if not os.path.exists(video_path_in_media):
77
  raise Exception(f"Manim did not produce the expected output file at {video_path_in_media}")
78
 
 
79
  tmp_video_path = os.path.join("/tmp", video_filename)
80
  shutil.move(video_path_in_media, tmp_video_path)
 
81
 
82
+ # The code file is already at code_filepath in /tmp.
83
+ tmp_code_path = code_filepath
84
+
85
  def remove_files():
86
  try:
87
  if os.path.exists(tmp_video_path):
88
  os.remove(tmp_video_path)
89
+ if os.path.exists(tmp_code_path):
90
+ os.remove(tmp_code_path)
 
 
91
  except Exception as e:
92
  app.logger.error("Error removing files: %s", e)
93
  Timer(600, remove_files).start()
 
96
  return render_template("result.html", video_url=video_url)
97
 
98
  except Exception as e:
 
 
99
  last_error = e
100
  attempt += 1
101
  time.sleep(1)
102
 
103
+ return render_template("result.html", error="An error occurred. Please try again later.")
104
 
105
  return render_template("index.html")
106
 
107
  @app.route("/video/<filename>")
108
  def get_video(filename):
 
109
  return send_from_directory("/tmp", filename)
110
 
111
  if __name__ == "__main__":
112
+ app.run(host="0.0.0.0", port=7860, debug=False)