amith33/voice_agent
0
1#!/usr/bin/env python32"""3Startup script for Hugging Face Spaces deployment4Handles model downloads and initialization5"""6 7import os8import subprocess9import logging10import sys11from pathlib import Path12 13# Configure logging14logging.basicConfig(level=logging.INFO)15logger = logging.getLogger(__name__)16 17def download_sadtalker_models():18 """Download SadTalker models if they don't exist"""19 logger.info("Downloading SadTalker models...")20 try:21 # Check if models already exist22 model_dir = Path("lip_sync_test/SadTalker/checkpoints")23 if model_dir.exists() and any(model_dir.iterdir()):24 logger.info("Models already exist, skipping download")25 return26 27 # Try to run the download script28 script_path = Path("lip_sync_test/SadTalker/scripts/download_models.sh")29 if script_path.exists():30 subprocess.run(["bash", str(script_path)], check=True)31 logger.info("Models downloaded successfully")32 else:33 logger.warning("Download script not found, models will be downloaded on first use")34 except subprocess.CalledProcessError as e:35 logger.warning(f"Failed to download models: {e}. Models will be downloaded on first use.")36 37def setup_directories():38 """Create necessary directories for the application"""39 logger.info("Setting up application directories...")40 41 # Use /tmp for temporary/writable directories in restricted environments42 base_dirs = [43 "outputs",44 "/tmp/static_uploads",45 "/tmp/static_presets", 46 "/tmp/static_results"47 ]48 49 for dir_path in base_dirs:50 try:51 Path(dir_path).mkdir(parents=True, exist_ok=True)52 logger.info(f"Created directory: {dir_path}")53 except PermissionError as e:54 logger.warning(f"Permission denied for {dir_path}: {e}")55 # Try alternative path in /tmp56 alt_path = f"/tmp/{Path(dir_path).name}"57 try:58 Path(alt_path).mkdir(parents=True, exist_ok=True)59 logger.info(f"Created alternative directory: {alt_path}")60 except Exception as alt_e:61 logger.error(f"Failed to create alternative directory {alt_path}: {alt_e}")62 except Exception as e:63 logger.error(f"Failed to create directory {dir_path}: {e}")64 65 # Create symlinks or update config to use writable paths66 try:67 # Create symlinks from app directories to writable /tmp directories68 if not Path("static").exists():69 Path("static").mkdir(exist_ok=True)70 71 # Create symlinks for uploads, presets, and results72 for dir_name in ["uploads", "presets", "results"]:73 app_path = Path(f"static/{dir_name}")74 tmp_path = Path(f"/tmp/static_{dir_name}")75 76 if app_path.exists() and app_path.is_symlink():77 app_path.unlink() # Remove existing symlink78 79 if not app_path.exists():80 try:81 app_path.symlink_to(tmp_path)82 logger.info(f"Created symlink: {app_path} -> {tmp_path}")83 except Exception as e:84 logger.warning(f"Could not create symlink for {dir_name}: {e}")85 # Fallback: just use the /tmp directory directly86 logger.info(f"Using direct path: {tmp_path}")87 88 except Exception as e:89 logger.warning(f"Symlink setup failed: {e}")90 logger.info("Continuing with /tmp directories...")91 92def check_dependencies():93 """Check if all required dependencies are available"""94 try:95 import torch96 import cv297 import numpy98 import fastapi99 logger.info("All Python dependencies are available")100 except ImportError as e:101 logger.error(f"Missing dependency: {e}")102 sys.exit(1)103 104def create_app():105 """Create and configure the FastAPI application"""106 from app import app107 return app108 109def main():110 """Main startup function for Docker deployment"""111 logger.info("Starting Voice Agent Project on Hugging Face Spaces...")112 113 # Check dependencies114 check_dependencies()115 116 # Setup directories117 setup_directories()118 119 # Download models (non-blocking)120 try:121 download_sadtalker_models()122 except Exception as e:123 logger.warning(f"Model download failed: {e}. Continuing...")124 125 logger.info("Startup completed successfully!")126 127 # Start the FastAPI application128 import uvicorn129 130 # Get port from environment or use default131 port = int(os.environ.get("PORT", 8000))132 host = os.environ.get("HOST", "0.0.0.0")133 134 logger.info(f"Starting server on {host}:{port}")135 136 uvicorn.run(137 "app:app",138 host=host,139 port=port,140 log_level="info"141 )142 143if __name__ == "__main__":144 main() 