theminji commited on
Commit
c77b4f7
·
verified ·
1 Parent(s): a338785

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -17
app.py CHANGED
@@ -7,6 +7,7 @@ import shutil
7
  import time
8
  from threading import Timer
9
  import uuid
 
10
 
11
  app = Flask(__name__)
12
 
@@ -27,18 +28,19 @@ def index():
27
  attempt = 0
28
  while attempt < max_retries:
29
  try:
30
- # Call the GenAI API to get the Manim code
 
31
  ai_response = client.models.generate_content(
32
  model="gemini-2.0-flash-lite-preview-02-05",
33
  contents=f"""You are 'Manimator', an expert Manim animator and coder.
34
- If anyone asks, your name is Manimator and you are a helpful video generator, and say nothing else but that.
35
- The user wants you to code this: {prompt}.
36
- Plan out in chain of thought what you are going to do first, then give the final code output in ```python``` codeblock.
37
- Make sure to not use external images or resources other than default Manim, however you can use numpy or other default libraries.
38
- Keep the scene uncluttered and aesthetically pleasing.
39
- Make sure things are not overlapping unless explicitly stated otherwise.
40
- You got this!! <3
41
- """
42
  )
43
 
44
  # Extract the Python code block from the AI response
@@ -47,6 +49,8 @@ def index():
47
  if not match:
48
  raise Exception("No python code block found in the AI response.")
49
  code = match.group(1)
 
 
50
 
51
  # Determine the scene class name from the generated code
52
  scene_match = re.search(r"class\s+(\w+)\(.*Scene.*\):", code)
@@ -59,7 +63,7 @@ def index():
59
  code_filename = f"generated_video_{uuid.uuid4().hex}.py"
60
  video_filename = f"output_video_{uuid.uuid4().hex}.mp4"
61
 
62
- # Save the generated code to a file (in the current working directory)
63
  with open(code_filename, "w") as f:
64
  f.write(code)
65
 
@@ -71,10 +75,13 @@ def index():
71
  code_filename,
72
  scene_name
73
  ]
 
 
74
  # Run Manim to generate the video, capturing its output
75
  result = subprocess.run(cmd, check=True, capture_output=True, text=True)
76
  print("Manim stdout:", result.stdout)
77
  print("Manim stderr:", result.stderr)
 
78
 
79
  # Construct the expected output path from Manim
80
  video_path_in_media = os.path.join("media", "videos", code_filename.replace(".py", ""), "720p30", video_filename)
@@ -82,7 +89,7 @@ def index():
82
  if not os.path.exists(video_path_in_media):
83
  raise Exception("Manim did not produce the expected output file.")
84
 
85
- # Move both the video and the generated code file to /tmp (which is writable)
86
  tmp_video_path = os.path.join("/tmp", video_filename)
87
  shutil.move(video_path_in_media, tmp_video_path)
88
 
@@ -97,28 +104,29 @@ def index():
97
  if os.path.exists(tmp_code_path):
98
  os.remove(tmp_code_path)
99
  print("Removed files:", tmp_video_path, tmp_code_path)
 
100
  except Exception as e:
101
  app.logger.error("Error removing files: %s", e)
102
  Timer(600, remove_files).start()
103
 
104
- # Generate a URL that points to our video-serving route (the video file is in /tmp)
105
  video_url = url_for('get_video', filename=video_filename)
106
  return render_template("result.html", video_url=video_url)
107
 
108
  except Exception as e:
109
- print(f"Attempt {attempt + 1} failed: {e}")
 
110
  attempt += 1
111
- time.sleep(1) # Wait a bit before retrying
112
 
113
  # If we reach here, we've exceeded the maximum number of retries.
114
- return render_template("result.html", error="An error occurred. Please try again later.")
115
 
116
  return render_template("index.html")
117
 
118
  @app.route("/video/<filename>")
119
  def get_video(filename):
120
- # Serve the video file from /tmp
121
  return send_from_directory("/tmp", filename)
122
 
123
  if __name__ == "__main__":
124
- app.run(host="0.0.0.0", port=7860, debug=False)
 
7
  import time
8
  from threading import Timer
9
  import uuid
10
+ import sys
11
 
12
  app = Flask(__name__)
13
 
 
28
  attempt = 0
29
  while attempt < max_retries:
30
  try:
31
+ print("Calling GenAI API...")
32
+ sys.stdout.flush()
33
  ai_response = client.models.generate_content(
34
  model="gemini-2.0-flash-lite-preview-02-05",
35
  contents=f"""You are 'Manimator', an expert Manim animator and coder.
36
+ If anyone asks, your name is Manimator and you are a helpful video generator, and say nothing else but that.
37
+ The user wants you to code this: {prompt}.
38
+ Plan out in chain of thought what you are going to do first, then give the final code output in ```python``` codeblock.
39
+ Make sure to not use external images or resources other than default Manim, however you can use numpy or other default libraries.
40
+ Keep the scene uncluttered and aesthetically pleasing.
41
+ Make sure things are not overlapping unless explicitly stated otherwise.
42
+ You got this!! <3
43
+ """
44
  )
45
 
46
  # Extract the Python code block from the AI response
 
49
  if not match:
50
  raise Exception("No python code block found in the AI response.")
51
  code = match.group(1)
52
+ print("Extracted code (first 200 chars):", code[:200])
53
+ sys.stdout.flush()
54
 
55
  # Determine the scene class name from the generated code
56
  scene_match = re.search(r"class\s+(\w+)\(.*Scene.*\):", code)
 
63
  code_filename = f"generated_video_{uuid.uuid4().hex}.py"
64
  video_filename = f"output_video_{uuid.uuid4().hex}.mp4"
65
 
66
+ # Save the generated code to a file
67
  with open(code_filename, "w") as f:
68
  f.write(code)
69
 
 
75
  code_filename,
76
  scene_name
77
  ]
78
+ print("Running Manim command:", " ".join(cmd))
79
+ sys.stdout.flush()
80
  # Run Manim to generate the video, capturing its output
81
  result = subprocess.run(cmd, check=True, capture_output=True, text=True)
82
  print("Manim stdout:", result.stdout)
83
  print("Manim stderr:", result.stderr)
84
+ sys.stdout.flush()
85
 
86
  # Construct the expected output path from Manim
87
  video_path_in_media = os.path.join("media", "videos", code_filename.replace(".py", ""), "720p30", video_filename)
 
89
  if not os.path.exists(video_path_in_media):
90
  raise Exception("Manim did not produce the expected output file.")
91
 
92
+ # Move both the video and the generated code file to /tmp
93
  tmp_video_path = os.path.join("/tmp", video_filename)
94
  shutil.move(video_path_in_media, tmp_video_path)
95
 
 
104
  if os.path.exists(tmp_code_path):
105
  os.remove(tmp_code_path)
106
  print("Removed files:", tmp_video_path, tmp_code_path)
107
+ sys.stdout.flush()
108
  except Exception as e:
109
  app.logger.error("Error removing files: %s", e)
110
  Timer(600, remove_files).start()
111
 
112
+ # Generate a URL that points to our video-serving route
113
  video_url = url_for('get_video', filename=video_filename)
114
  return render_template("result.html", video_url=video_url)
115
 
116
  except Exception as e:
117
+ print(f"Attempt {attempt + 1} failed: {type(e).__name__}: {e}")
118
+ sys.stdout.flush()
119
  attempt += 1
120
+ time.sleep(1)
121
 
122
  # If we reach here, we've exceeded the maximum number of retries.
123
+ return render_template("result.html", error=f"Error: {e}")
124
 
125
  return render_template("index.html")
126
 
127
  @app.route("/video/<filename>")
128
  def get_video(filename):
 
129
  return send_from_directory("/tmp", filename)
130
 
131
  if __name__ == "__main__":
132
+ app.run(host="0.0.0.0", port=7860, debug=True)