Spaces:
Sleeping
Sleeping
File size: 8,218 Bytes
4588d9f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 |
#!/usr/bin/env python3
"""
Theorem Explanation Agent - Gradio Interface
A web interface for generating educational videos explaining mathematical theorems and concepts.
"""
import os
import sys
import json
import traceback
import tempfile
import shutil
from typing import Optional, List, Dict, Any
import gradio as gr
from pathlib import Path
import asyncio
import threading
from datetime import datetime
# Add the project root to Python path
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))
# Demo mode flag - set to True for deployment environments with limited resources
DEMO_MODE = os.getenv("DEMO_MODE", "true").lower() == "true" # Default to demo mode for HF Spaces
# Global variables for managing video generation
video_generator = None
generation_status = {}
# Flag to track if we can import all dependencies
CAN_IMPORT_DEPENDENCIES = True
def initialize_video_generator():
"""Initialize the video generator with default settings."""
global video_generator, CAN_IMPORT_DEPENDENCIES
try:
if DEMO_MODE:
return "β
Demo mode - Video generator simulation enabled"
if not CAN_IMPORT_DEPENDENCIES:
return "β οΈ Running in fallback mode due to missing dependencies"
from generate_video import VideoGenerator
video_generator = VideoGenerator(
planner_model="gemini/gemini-2.0-flash",
helper_model="gemini/gemini-2.0-flash",
scene_model="gemini/gemini-2.0-flash",
output_dir="output",
use_rag=False,
use_context_learning=False,
use_visual_fix_code=False,
print_response=False
)
return "β
Video generator initialized successfully"
except Exception as e:
CAN_IMPORT_DEPENDENCIES = False
return f"β Failed to initialize video generator: {str(e)}\n\nπ§ Running in demo mode"
def simulate_video_generation(topic: str, context: str, max_scenes: int) -> Dict[str, Any]:
"""Simulate video generation for demo purposes."""
import time
import random
# Simulate different stages
stages = [
("Planning video structure", 20),
("Generating scene outlines", 40),
("Creating animations", 60),
("Rendering videos", 80),
("Finalizing output", 100)
]
for stage, progress in stages:
time.sleep(random.uniform(0.1, 0.3)) # Faster for demo
return {
"success": True,
"message": f"Demo video generated for topic: {topic}",
"scenes_created": max_scenes,
"total_duration": "2.5 minutes",
"demo_note": "This is a simulated result. In production, actual Manim videos would be generated."
}
def generate_video_demo(topic: str, context: str = "", max_scenes: int = 3) -> str:
"""Generate a video explanation for the given topic (demo version)."""
if not topic.strip():
return "β Please enter a topic to explain"
try:
# Simulate video generation
result = simulate_video_generation(topic, context, max_scenes)
output = f"""π **Theorem Explanation Agent**
**Topic:** {topic}
**Context:** {context if context else "None provided"}
**Max Scenes:** {max_scenes}
**β
Demo Generation Complete!**
π **Results:**
- Scenes Created: {result['scenes_created']}
- Total Duration: {result['total_duration']}
- Status: {result['message']}
β οΈ **Demo Mode Note:**
{result['demo_note']}
π **To enable full video generation:**
1. Set up API keys (GEMINI_API_KEY, etc.)
2. Install full dependencies (Manim, FFmpeg, etc.)
3. Set DEMO_MODE=false
π **Example topics to try:**
- Pythagorean Theorem
- Velocity in Physics
- Derivatives in Calculus
- Newton's Laws of Motion
"""
return output
except Exception as e:
return f"β Error during generation: {str(e)}\n\nPlease try with a simpler topic."
def get_example_topics() -> List[List[str]]:
"""Get example topics for the interface."""
return [
["Pythagorean Theorem", "Explain with visual proof and real-world applications"],
["Velocity", "Explain velocity in physics with detailed examples"],
["Derivatives", "Explain derivatives in calculus with geometric interpretation"],
["Newton's Laws", "Explain Newton's three laws of motion with examples"],
["Quadratic Formula", "Derive and explain the quadratic formula step by step"],
["Logarithms", "Explain logarithms and their properties with examples"],
["Probability", "Explain basic probability concepts with practical examples"],
["Trigonometry", "Explain basic trigonometric functions and their uses"]
]
# Create the main interface
with gr.Blocks(
title="π Theorem Explanation Agent",
theme=gr.themes.Soft(),
css="""
.main-header {
text-align: center;
margin-bottom: 30px;
padding: 20px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 10px;
color: white;
}
.demo-warning {
background-color: #fff3cd;
border: 1px solid #ffeaa7;
border-radius: 5px;
padding: 15px;
margin: 10px 0;
color: #856404;
}
"""
) as demo:
# Header
gr.HTML(f"""
<div class="main-header">
<h1>π Theorem Explanation Agent</h1>
<p>Generate educational videos explaining mathematical theorems and concepts using AI</p>
{'<div class="demo-warning">β οΈ <strong>Demo Mode Active</strong> - This is a simulation for demonstration purposes.</div>' if DEMO_MODE else ''}
</div>
""")
with gr.Row():
with gr.Column(scale=2):
gr.HTML("<h3>π Video Generation Settings</h3>")
# Topic input
topic_input = gr.Textbox(
label="Topic to Explain",
placeholder="Enter the topic you want to explain (e.g., 'velocity', 'pythagorean theorem')",
lines=1
)
# Context input
context_input = gr.Textbox(
label="Additional Context (Optional)",
placeholder="Provide additional context or specific requirements for the explanation",
lines=3
)
# Max scenes
max_scenes_slider = gr.Slider(
label="Maximum Number of Scenes",
minimum=1,
maximum=5,
value=3,
step=1
)
# Example topics
gr.HTML("<h4>π‘ Example Topics</h4>")
examples = gr.Examples(
examples=get_example_topics(),
inputs=[topic_input, context_input]
)
# Generate button
generate_btn = gr.Button(
"π Generate Educational Video",
variant="primary",
size="lg"
)
with gr.Column(scale=1):
gr.HTML("<h3>π System Status</h3>")
# Initialization status
init_status = gr.Textbox(
label="System Status",
value="Click 'Initialize System' to check status",
interactive=False,
lines=3
)
init_btn = gr.Button("π§ Initialize System")
# Generation result
gr.HTML("<h3>π Generation Results</h3>")
result_display = gr.Textbox(
label="Generation Output",
lines=15,
interactive=False
)
# Event handlers
init_btn.click(
fn=initialize_video_generator,
outputs=init_status
)
generate_btn.click(
fn=generate_video_demo,
inputs=[topic_input, context_input, max_scenes_slider],
outputs=result_display
)
# Launch the interface if run directly
if __name__ == "__main__":
demo.launch(
server_name="0.0.0.0",
server_port=7860,
share=False,
show_error=True
) |