#!/usr/bin/env python3 """ Theorem Explanation Agent - Gradio Interface for Hugging Face Spaces """ import os import sys import json import asyncio import time import random from typing import Dict, Any, Tuple from pathlib import Path import gradio as gr # Add project root to path project_root = Path(__file__).parent sys.path.insert(0, str(project_root)) # Environment setup DEMO_MODE = os.getenv("DEMO_MODE", "true").lower() == "true" video_generator = None CAN_IMPORT_DEPENDENCIES = True def setup_environment(): """Setup environment for HF Spaces.""" print("š Setting up Theorem Explanation Agent...") gemini_keys = os.getenv("GEMINI_API_KEY", "") if gemini_keys: key_count = len([k.strip() for k in gemini_keys.split(',') if k.strip()]) print(f"ā Found {key_count} Gemini API key(s)") return True else: print("ā ļø No Gemini API keys found - running in demo mode") return False def initialize_video_generator(): """Initialize video generator.""" global video_generator, CAN_IMPORT_DEPENDENCIES try: if DEMO_MODE: return "ā Demo mode enabled - No heavy dependencies loaded" # Check if we have API keys before importing heavy dependencies gemini_keys = os.getenv("GEMINI_API_KEY", "") if not gemini_keys: return "ā ļø No API keys found - running in demo mode (prevents model downloads)" # Try to import but handle missing dependencies gracefully try: from generate_video import VideoGenerator from mllm_tools.litellm import LiteLLMWrapper except ImportError as import_err: print(f"Heavy dependencies not available: {import_err}") return "ā ļø Heavy dependencies not installed - using demo mode to prevent downloads" planner_model = LiteLLMWrapper( model_name="gemini/gemini-2.0-flash", temperature=0.7, print_cost=True, verbose=False, use_langfuse=False ) video_generator = VideoGenerator( planner_model=planner_model, helper_model=planner_model, scene_model=planner_model, output_dir="output", use_rag=False, use_context_learning=False, use_visual_fix_code=False, verbose=False ) return "ā Video generator initialized with full dependencies" except Exception as e: CAN_IMPORT_DEPENDENCIES = False print(f"Initialization error: {e}") return f"ā ļø Running in demo mode to prevent model downloads: {str(e)[:100]}..." def simulate_video_generation(topic: str, context: str, max_scenes: int, progress_callback=None): """Simulate video generation.""" stages = [ ("š Analyzing topic", 15), ("š Planning structure", 30), ("š¬ Generating scenes", 50), ("⨠Creating animations", 75), ("š„ Rendering video", 90), ("ā Finalizing", 100) ] results = [] for stage, progress in stages: if progress_callback: progress_callback(progress, stage) time.sleep(random.uniform(0.3, 0.7)) results.append(f"⢠{stage}") return { "success": True, "message": f"Demo video generated for: {topic}", "scenes_created": max_scenes, "processing_steps": results, "demo_note": "This is a simulation for demo purposes." } async def generate_video_async(topic: str, context: str, max_scenes: int, progress_callback=None): """Generate video asynchronously.""" global video_generator if not topic.strip(): return {"success": False, "error": "Please enter a topic"} try: if DEMO_MODE or not CAN_IMPORT_DEPENDENCIES: return simulate_video_generation(topic, context, max_scenes, progress_callback) if progress_callback: progress_callback(10, "š Starting generation...") result = await video_generator.generate_video_pipeline( topic=topic, description=context, max_retries=3, only_plan=False, specific_scenes=list(range(1, max_scenes + 1)) ) if progress_callback: progress_callback(100, "ā Completed!") return {"success": True, "message": f"Video generated for: {topic}", "result": result} except Exception as e: return {"success": False, "error": str(e)} def generate_video_gradio(topic: str, context: str, max_scenes: int, progress=gr.Progress()) -> Tuple[str, str]: """Main Gradio function.""" def progress_callback(percent, message): progress(percent / 100, desc=message) loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) try: result = loop.run_until_complete( generate_video_async(topic, context, max_scenes, progress_callback) ) finally: loop.close() if result["success"]: output = f"""# š Video Generation Complete! **Topic:** {topic} **Context:** {context if context else "None"} **Scenes:** {max_scenes} ## ā Result {result["message"]} """ if "processing_steps" in result: output += "## š Steps\n" for step in result["processing_steps"]: output += f"{step}\n" if "demo_note" in result: output += f"\nā ļø **{result['demo_note']}**" status = "š® Demo completed" if DEMO_MODE else "ā Generation completed" return output, status else: error_output = f"""# ā Generation Failed {result.get("error", "Unknown error")} ## š” Tips - Check topic validity - Verify API keys - Try simpler topics """ return error_output, "ā Failed" def get_examples(): """Example topics.""" return [ ["Velocity", "Physics concept with real-world examples"], ["Pythagorean Theorem", "Mathematical proof with applications"], ["Derivatives", "Calculus concept with geometric interpretation"], ["Newton's Laws", "Three laws of motion with demonstrations"], ["Quadratic Formula", "Step-by-step derivation and usage"] ] def create_interface(): """Create Gradio interface.""" setup_environment() init_status = initialize_video_generator() with gr.Blocks( title="š Theorem Explanation Agent", theme=gr.themes.Soft() ) as demo: gr.HTML("""
Generate educational videos using AI
This prevents automatic downloading of Kokoro and other heavy models.
To enable full functionality:
GEMINI_API_KEY
(supports comma-separated keys)DEMO_MODE=false
Note: Full mode requires ~2GB of model downloads.
Multiple keys:
GEMINI_API_KEY=key1,key2,key3
Single key:
GEMINI_API_KEY=your_key