ManojINaik commited on
Commit
3fffcf9
·
verified ·
1 Parent(s): ae425dd

temp update

Browse files
Files changed (1) hide show
  1. app.py +59 -159
app.py CHANGED
@@ -1,178 +1,78 @@
1
- # app.py (Corrected for pathing and live logging)
2
-
3
- import gradio as gr
4
- import uuid
5
- import subprocess
6
- import threading
7
  import os
8
  import sys
 
9
  import re
10
  import traceback
 
11
 
12
- # Add project root to Python path to fix any import issues
13
  sys.path.insert(0, os.getcwd())
14
 
15
  # --- Download Kokoro models if they don't exist ---
16
  model_dir = "models"
17
- kokoro_model_path = os.path.join(model_dir, "kokoro-v0_19.onnx")
18
- kokoro_voices_path = os.path.join(model_dir, "voices.bin")
19
-
20
- if not os.path.exists(kokoro_model_path) or not os.path.exists(kokoro_voices_path):
21
  print("Downloading Kokoro TTS models...")
22
  os.makedirs(model_dir, exist_ok=True)
23
- os.system(f"wget -O {kokoro_model_path} https://github.com/thewh1teagle/kokoro-onnx/releases/download/model-files/kokoro-v0_19.onnx")
24
- os.system(f"wget -O {kokoro_voices_path} https://github.com/thewh1teagle/kokoro-onnx/releases/download/model-files/voices.bin")
25
  print("Model download complete.")
26
 
27
- # In-memory dictionary to track task status.
28
- tasks = {}
29
-
30
- def run_video_generation(task_id: str, topic: str, context: str, model: str):
31
- """
32
- Runs the main generation script in a separate process and captures output in real-time.
33
- """
34
- tasks[task_id]['status'] = 'running'
35
- tasks[task_id]['log'] = 'Process started...\n'
36
-
37
- # Sanitize topic name to create a valid directory/file prefix
38
- file_prefix = re.sub(r'[^a-z0-9_]+', '_', topic.lower())
39
- # This is the directory where the script will create its files
40
- final_output_dir = os.path.join("output", file_prefix)
41
-
42
- # --- THIS IS THE FIX ---
43
- # We tell the script to use the general 'output' folder.
44
- # The script itself will then create the specific 'file_prefix' subfolder inside it.
45
- command = [
46
- "python", "-u", "generate_video.py",
47
- "--model", model,
48
- "--topic", topic,
49
- "--context", context,
50
- "--output_dir", "output" # Pass the general directory
51
- # Langfuse is disabled by not including the --use_langfuse flag
52
- ]
53
-
54
- print(f"Running command: {' '.join(command)}")
55
-
56
- try:
57
- process = subprocess.Popen(
58
- command,
59
- stdout=subprocess.PIPE,
60
- stderr=subprocess.STDOUT,
61
- text=True,
62
- bufsize=1,
63
- universal_newlines=True,
64
- )
65
-
66
- for line in iter(process.stdout.readline, ''):
67
- print(line, end='')
68
- tasks[task_id]['log'] += line
69
-
70
- process.wait()
71
-
72
- if process.returncode == 0:
73
- # Check for the final combined video file in the correct specific directory
74
- final_video_path = os.path.join(final_output_dir, f"{file_prefix}_combined.mp4")
75
-
76
- if os.path.exists(final_video_path):
77
- tasks[task_id]['status'] = 'completed'
78
- tasks[task_id]['video_path'] = final_video_path
79
- tasks[task_id]['log'] += f"\n✅ Success! Video available at: {final_video_path}"
80
- else:
81
- tasks[task_id]['status'] = 'failed'
82
- tasks[task_id]['error'] = "Script finished, but the final combined video file was not found."
83
- tasks[task_id]['log'] += f"\n❌ Error: Output video not found at {final_video_path}. Check full logs."
84
- else:
85
- tasks[task_id]['status'] = 'failed'
86
- tasks[task_id]['error'] = f"Process failed with return code {process.returncode}."
87
- tasks[task_id]['log'] += f"\n❌ Error: Process failed. See logs above for details."
88
-
89
- except Exception as e:
90
- print(f"Caught an exception: {e}")
91
- tasks[task_id]['status'] = 'failed'
92
- tasks[task_id]['error'] = str(e)
93
- tasks[task_id]['log'] += f"\n❌ An exception occurred: {traceback.format_exc()}"
94
-
95
- def start_generation(topic: str, context: str, model: str):
96
- if not all([topic, context, model]):
97
- return "Topic, Context, and Model cannot be empty.", ""
98
-
99
- task_id = str(uuid.uuid4())
100
- tasks[task_id] = {'status': 'queued', 'model': model, 'log': ''}
101
-
102
- thread = threading.Thread(
103
- target=run_video_generation,
104
- args=(task_id, topic, context, model)
105
  )
106
- thread.start()
107
-
108
- return f"✅ Task started with ID: {task_id}. Go to 'Check Status' tab to monitor progress.", task_id
109
 
110
- def check_status(task_id: str):
111
- if not task_id:
112
- return "Please enter a Task ID.", None, "Please enter a Task ID above and click 'Check Status'."
113
-
114
- task = tasks.get(task_id)
115
- if not task:
116
- return "Task not found.", None, f"No task found with ID: {task_id}"
117
-
118
- status = task.get('status')
119
- model = task.get('model', 'Unknown')
120
- log = task.get('log', 'No logs yet...')
121
-
122
- if status == 'completed':
123
- video_path = task.get('video_path')
124
- status_message = f"✅ Status: {status} (Model: {model})"
125
- return status_message, video_path, log
126
- elif status == 'failed':
127
- error = task.get('error', 'Unknown error')
128
- status_message = f"❌ Status: {status} (Model: {model})"
129
- return status_message, None, log
130
-
131
- status_message = f"🔄 Status: {status} (Model: {model})"
132
- return status_message, None, log
133
 
134
- with gr.Blocks(title="Theorem Explain Agent") as demo:
135
- gr.Markdown("# 🎓 Theorem Explain Agent: Video Generation")
136
- gr.Markdown("Generate educational videos explaining mathematical theorems and concepts. This may take several minutes.")
137
 
138
- with gr.Tab("🚀 Start Generation"):
139
- gr.Markdown("### 1. Enter the details for your video")
140
- model_input = gr.Dropdown(
141
- label="Model",
142
- choices=["gemini/gemini-1.5-flash-001", "gemini/gemini-1.5-pro-002"],
143
- value="gemini/gemini-1.5-flash-001",
144
- info="Select the AI model for content generation."
145
- )
146
- topic_input = gr.Textbox(label="Topic", placeholder="e.g., The Pythagorean Theorem")
147
- context_input = gr.Textbox(label="Context", placeholder="A short explanation of the theorem.", lines=3)
148
- start_button = gr.Button("🎬 Generate Video", variant="primary")
149
-
150
- gr.Markdown("### 2. Monitor your task")
151
- with gr.Row():
152
- status_output = gr.Textbox(label="Status", interactive=False)
153
- task_id_output = gr.Textbox(label="Task ID", interactive=False)
154
-
155
- with gr.Tab("📊 Check Status & View Video"):
156
- gr.Markdown("### Paste your Task ID to check progress and view the final video")
157
- with gr.Row():
158
- task_id_input = gr.Textbox(label="Task ID", placeholder="Enter the Task ID you received")
159
- check_button = gr.Button("🔍 Check Status", variant="secondary")
160
-
161
- status_display = gr.Textbox(label="Current Status", interactive=False)
162
- video_output = gr.Video(label="Generated Video", interactive=False)
163
- log_display = gr.Textbox(label="Live Generation Logs", lines=15, interactive=False)
164
 
165
- start_button.click(
166
- fn=start_generation,
167
- inputs=[topic_input, context_input, model_input],
168
- outputs=[status_output, task_id_output]
169
- )
170
-
171
- check_button.click(
172
- fn=check_status,
173
- inputs=[task_id_input],
174
- outputs=[status_display, video_output, log_display],
175
- every=2
176
- )
177
 
178
- demo.launch()
 
 
 
1
+ # app.py (Temporary script for direct testing)
 
 
 
 
 
2
  import os
3
  import sys
4
+ import subprocess
5
  import re
6
  import traceback
7
+ import time
8
 
9
+ # Add project root to Python path
10
  sys.path.insert(0, os.getcwd())
11
 
12
  # --- Download Kokoro models if they don't exist ---
13
  model_dir = "models"
14
+ if not os.path.exists(os.path.join(model_dir, "kokoro-v0_19.onnx")):
 
 
 
15
  print("Downloading Kokoro TTS models...")
16
  os.makedirs(model_dir, exist_ok=True)
17
+ os.system(f"wget -P {model_dir} https://github.com/thewh1teagle/kokoro-onnx/releases/download/model-files/kokoro-v0_19.onnx")
18
+ os.system(f"wget -P {model_dir} https://github.com/thewh1teagle/kokoro-onnx/releases/download/model-files/voices.bin")
19
  print("Model download complete.")
20
 
21
+ print("\n" + "="*50)
22
+ print("--- DIRECT EXECUTION TEST ---")
23
+ print("This script will now directly run 'generate_video.py'.")
24
+ print("Check the logs below for real-time output and the final error.")
25
+ print("="*50 + "\n")
26
+ sys.stdout.flush() # Ensures the above text is printed immediately
27
+
28
+ # --- Hardcoded Test Parameters ---
29
+ topic = "The Pythagorean Theorem"
30
+ context = "In a right-angled triangle, the square of the length of the hypotenuse is equal to the sum of the squares of the lengths of the other two sides."
31
+ model = "gemini/gemini-1.5-flash-001"
32
+ file_prefix = re.sub(r'[^a-z0-9_]+', '_', topic.lower())
33
+ output_dir = os.path.join("output", file_prefix)
34
+
35
+ # --- Construct the command ---
36
+ command = [
37
+ "python", "-u", "generate_video.py", # '-u' for unbuffered output
38
+ "--model", model,
39
+ "--topic", topic,
40
+ "--context", context,
41
+ "--output_dir", output_dir
42
+ ]
43
+
44
+ print(f"Executing command: {' '.join(command)}\n")
45
+ sys.stdout.flush()
46
+
47
+ # --- Run the command and stream output ---
48
+ try:
49
+ process = subprocess.Popen(
50
+ command,
51
+ stdout=subprocess.PIPE,
52
+ stderr=subprocess.STDOUT,
53
+ text=True,
54
+ bufsize=1,
55
+ universal_newlines=True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  )
 
 
 
57
 
58
+ # Read and print output line-by-line
59
+ for line in iter(process.stdout.readline, ''):
60
+ print(line, end='')
61
+ sys.stdout.flush()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
+ process.wait() # Wait for the process to finish
 
 
64
 
65
+ if process.returncode == 0:
66
+ print("\n--- TEST SUCCEEDED ---")
67
+ print(f"Script finished with exit code 0. Check the 'Files' tab for the video in the '{output_dir}' directory.")
68
+ else:
69
+ print(f"\n--- TEST FAILED WITH EXIT CODE {process.returncode} ---")
70
+ print("The error traceback should be visible above.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
 
72
+ except Exception:
73
+ print(f"\n--- SCRIPT CRASHED WITH AN EXCEPTION ---")
74
+ print(traceback.format_exc())
 
 
 
 
 
 
 
 
 
75
 
76
+ print("\n--- DIRECT TEST SCRIPT FINISHED ---")
77
+ print("The Space will now idle. To run another test, you must restart the Space.")
78
+ time.sleep(3600) # Keep the container alive for an hour for you to check logs