File size: 3,882 Bytes
5efbc82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
703fff1
 
 
 
 
5efbc82
 
 
 
 
 
 
703fff1
 
 
 
 
 
 
 
 
 
 
5efbc82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b567fa
5efbc82
 
 
1b567fa
5efbc82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
703fff1
 
5efbc82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Startup script for Kokoro TTS API on Hugging Face Spaces
"""

import os
import sys
import logging
import subprocess

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

def check_environment():
    """Check the environment and permissions"""
    logger.info("=== Environment Check ===")
    
    # Check if running on HF Spaces
    space_id = os.environ.get('SPACE_ID')
    if space_id:
        logger.info(f"Running on Hugging Face Spaces: {space_id}")
    else:
        logger.info("Not running on Hugging Face Spaces")
    
    # Check Python version
    logger.info(f"Python version: {sys.version}")
    
    # Check current user and home directory
    logger.info(f"Current user: {os.getenv('USER', 'unknown')}")
    logger.info(f"Home directory: {os.path.expanduser('~')}")
    logger.info(f"Current working directory: {os.getcwd()}")
    
    # Check available disk space
    try:
        result = subprocess.run(['df', '-h', '/tmp'], capture_output=True, text=True)
        logger.info(f"Disk space in /tmp:\n{result.stdout}")
    except Exception as e:
        logger.warning(f"Could not check disk space: {e}")
    
    # Check write permissions for important directories
    test_dirs = ['/tmp', os.path.expanduser('~'), os.getcwd()]
    for test_dir in test_dirs:
        try:
            test_file = os.path.join(test_dir, 'test_write.tmp')
            with open(test_file, 'w') as f:
                f.write('test')
            os.remove(test_file)
            logger.info(f"βœ… Write permission OK: {test_dir}")
        except Exception as e:
            logger.warning(f"❌ Write permission failed: {test_dir} - {e}")

def check_dependencies():
    """Check if required packages are installed"""
    logger.info("=== Checking dependencies ===")
    
    required_packages = [
        'kokoro',
        'soundfile', 
        'torch',
        'fastapi',
        'uvicorn'
    ]
    
    for package in required_packages:
        try:
            __import__(package)
            logger.info(f"βœ… {package} is available")
        except ImportError:
            logger.error(f"❌ {package} is not available")

def test_kokoro():
    """Test Kokoro TTS functionality"""
    logger.info("=== Testing Kokoro TTS ===")
    
    try:
        # Import after setting up environment
        import app_config  # This will setup environment
        from kokoro import KPipeline
        
        logger.info("Initializing Kokoro pipeline...")
        pipeline = KPipeline(lang_code='a')
        logger.info("βœ… Kokoro pipeline initialized successfully")
        
        # Test generation
        logger.info("Testing speech generation...")
        text = "Hello, this is a test."
        generator = pipeline(text, voice='af_heart')
        
        for i, (gs, ps, audio) in enumerate(generator):
            logger.info(f"βœ… Generated audio segment {i}: gs={gs}, ps={ps}, audio shape: {audio.shape}")
            break
            
        logger.info("βœ… Kokoro TTS test completed successfully")
        return True
        
    except Exception as e:
        logger.error(f"❌ Kokoro TTS test failed: {e}")
        import traceback
        logger.error(f"Full traceback: {traceback.format_exc()}")
        return False

def main():
    """Main startup function"""
    logger.info("πŸš€ Starting Kokoro TTS API setup...")
    
    check_environment()
    check_dependencies()
    
    if test_kokoro():
        logger.info("πŸŽ‰ All checks passed! Starting the API...")
        # Import and start the app
        import uvicorn
        uvicorn.run("app:app", host="0.0.0.0", port=7860, log_level="info")
    else:
        logger.error("❌ Setup failed. Please check the logs above.")
        sys.exit(1)

if __name__ == "__main__":
    main()