File size: 5,237 Bytes
71905d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Startup script for C-3PO TTS API
Handles model download, initialization, and server startup
"""

import os
import sys
import subprocess
import logging
import time
from pathlib import Path

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

def check_dependencies():
    """Check if all required dependencies are installed"""
    logger.info("๐Ÿ” Checking dependencies...")
    
    try:
        import torch
        import TTS
        import fastapi
        import huggingface_hub
        logger.info("โœ… All core dependencies found")
        return True
    except ImportError as e:
        logger.error(f"โŒ Missing dependency: {e}")
        logger.info("๐Ÿ’ก Install with: pip install -r requirements.txt")
        return False

def check_gpu():
    """Check GPU availability"""
    try:
        import torch
        if torch.cuda.is_available():
            gpu_name = torch.cuda.get_device_name(0)
            logger.info(f"๐ŸŽฎ GPU available: {gpu_name}")
            return True
        else:
            logger.info("๐Ÿ’ป No GPU available, using CPU")
            return False
    except Exception as e:
        logger.warning(f"โš ๏ธ  GPU check failed: {e}")
        return False

def check_disk_space():
    """Check available disk space for model download"""
    try:
        import shutil
        free_space = shutil.disk_usage('.').free / (1024**3)  # GB
        
        if free_space < 5:
            logger.warning(f"โš ๏ธ  Low disk space: {free_space:.1f}GB available")
            logger.warning("๐Ÿ’ฝ C-3PO model requires ~2GB space")
        else:
            logger.info(f"๐Ÿ’พ Disk space: {free_space:.1f}GB available")
        
        return free_space > 2
    except Exception as e:
        logger.warning(f"โš ๏ธ  Disk space check failed: {e}")
        return True

def setup_environment():
    """Set up environment variables"""
    os.environ["COQUI_TOS_AGREED"] = "1"
    os.environ["HF_HUB_DISABLE_TELEMETRY"] = "1"
    
    # Create models directory
    models_dir = Path("./models")
    models_dir.mkdir(exist_ok=True)
    
    logger.info("๐ŸŒ Environment configured")

def install_dependencies():
    """Install missing dependencies"""
    logger.info("๐Ÿ“ฆ Installing dependencies...")
    
    try:
        subprocess.check_call([
            sys.executable, "-m", "pip", "install", "-r", "requirements.txt"
        ])
        logger.info("โœ… Dependencies installed successfully")
        return True
    except subprocess.CalledProcessError as e:
        logger.error(f"โŒ Failed to install dependencies: {e}")
        return False

def test_model_download():
    """Test if the C-3PO model can be downloaded"""
    logger.info("๐Ÿค– Testing C-3PO model availability...")
    
    try:
        from huggingface_hub import repo_info
        
        # Check if the repo exists and is accessible
        info = repo_info(repo_id="Borcherding/XTTS-v2_C3PO")
        logger.info(f"โœ… C-3PO model accessible: {info.id}")
        logger.info(f"   Last modified: {info.last_modified}")
        
        return True
    except Exception as e:
        logger.error(f"โŒ C-3PO model not accessible: {e}")
        return False

def start_api_server():
    """Start the FastAPI server"""
    logger.info("๐Ÿš€ Starting C-3PO TTS API server...")
    
    try:
        # Import and run the API
        import uvicorn
        from coqui_api import app
        
        logger.info("๐ŸŽญ C-3PO TTS API starting on http://localhost:7860")
        logger.info("๐Ÿ“– API documentation available at http://localhost:7860/docs")
        
        uvicorn.run(
            app, 
            host="0.0.0.0", 
            port=7860,
            log_level="info"
        )
        
    except Exception as e:
        logger.error(f"โŒ Failed to start API server: {e}")
        return False

def main():
    """Main startup sequence"""
    print("๐Ÿค– C-3PO TTS API Startup")
    print("=" * 50)
    
    # Step 1: Check dependencies
    if not check_dependencies():
        logger.info("๐Ÿ“ฆ Attempting to install dependencies...")
        if not install_dependencies():
            logger.error("โŒ Failed to install dependencies. Exiting.")
            sys.exit(1)
    
    # Step 2: Setup environment
    setup_environment()
    
    # Step 3: Check system resources
    has_gpu = check_gpu()
    has_space = check_disk_space()
    
    if not has_space:
        logger.error("โŒ Insufficient disk space. Exiting.")
        sys.exit(1)
    
    # Step 4: Test model availability
    if not test_model_download():
        logger.warning("โš ๏ธ  C-3PO model may not be accessible")
        logger.warning("   The API will fall back to standard XTTS v2")
    
    # Step 5: Start the server
    print("\n" + "=" * 50)
    logger.info("๐ŸŽฌ All checks passed! Starting C-3PO TTS API...")
    print("=" * 50)
    
    try:
        start_api_server()
    except KeyboardInterrupt:
        logger.info("\n๐Ÿ›‘ Server stopped by user")
    except Exception as e:
        logger.error(f"โŒ Server error: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()