Spaces:
Sleeping
Sleeping
File size: 4,112 Bytes
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 121 122 123 124 125 126 127 128 129 130 131 132 |
#!/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 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
test_dirs = ['/tmp', '/app', '.']
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 setup_cache_dirs():
"""Setup cache directories with proper permissions"""
logger.info("=== Setting up cache directories ===")
cache_dirs = [
'/tmp/hf_cache',
'/tmp/torch_cache',
'/tmp/numba_cache'
]
for cache_dir in cache_dirs:
try:
os.makedirs(cache_dir, exist_ok=True)
os.chmod(cache_dir, 0o777)
logger.info(f"β
Created cache directory: {cache_dir}")
except Exception as e:
logger.error(f"β Failed to create {cache_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 cache dirs
from kokoro import KPipeline
logger.info("Initializing Kokoro pipeline...")
pipeline = KPipeline(lang_code='a', repo_id='hexgrad/Kokoro-82M')
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}")
return False
def main():
"""Main startup function"""
logger.info("π Starting Kokoro TTS API setup...")
check_environment()
setup_cache_dirs()
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() |