Spaces:
Sleeping
Sleeping
File size: 8,877 Bytes
6db3515 | 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 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 | #!/usr/bin/env python3
"""
Setup script for Optimized Twi Speech Recognition Engine
=======================================================
This script sets up the optimized speech recognition engine with all
necessary dependencies and configurations.
Author: AI Assistant
Date: 2025-11-05
"""
import os
import sys
import subprocess
import logging
from pathlib import Path
# Configure logging
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
def check_python_version():
"""Check if Python version is compatible."""
required_version = (3, 8)
current_version = sys.version_info[:2]
if current_version < required_version:
logger.error(
f"Python {required_version[0]}.{required_version[1]}+ required, but {current_version[0]}.{current_version[1]} found"
)
return False
logger.info(
f"Python version {current_version[0]}.{current_version[1]} is compatible"
)
return True
def install_requirements():
"""Install required packages."""
requirements_file = Path(__file__).parent / "requirements.txt"
if not requirements_file.exists():
logger.error(f"Requirements file not found: {requirements_file}")
return False
try:
logger.info("Installing requirements...")
result = subprocess.run(
[sys.executable, "-m", "pip", "install", "-r", str(requirements_file)],
capture_output=True,
text=True,
timeout=1800,
) # 30 minute timeout
if result.returncode != 0:
logger.error(f"Failed to install requirements: {result.stderr}")
return False
logger.info("Requirements installed successfully")
return True
except subprocess.TimeoutExpired:
logger.error("Installation timed out")
return False
except Exception as e:
logger.error(f"Error installing requirements: {e}")
return False
def setup_directories():
"""Create necessary directories."""
base_dir = Path(__file__).parent
directories = [
base_dir / "data",
base_dir / "data" / "audio",
base_dir / "data" / "models",
base_dir / "data" / "cache",
base_dir / "logs",
base_dir / "models",
base_dir / "models" / "intent_classifier",
base_dir / "models" / "whisper_cache",
]
for directory in directories:
try:
directory.mkdir(parents=True, exist_ok=True)
logger.info(f"Created directory: {directory}")
except Exception as e:
logger.error(f"Failed to create directory {directory}: {e}")
return False
return True
def download_whisper_model():
"""Download and cache Whisper model."""
try:
logger.info("Downloading Whisper model (this may take a few minutes)...")
# Import here to ensure whisper is installed
import whisper
# Download the large-v3 model
model = whisper.load_model("large-v3")
logger.info("Whisper model downloaded and cached successfully")
# Clean up
del model
return True
except ImportError:
logger.error("Whisper not installed. Please install openai-whisper package.")
return False
except Exception as e:
logger.error(f"Failed to download Whisper model: {e}")
return False
def create_config_files():
"""Create default configuration files."""
base_dir = Path(__file__).parent
# Create .env file
env_file = base_dir / ".env"
if not env_file.exists():
env_content = """# Optimized Engine Environment Configuration
ENVIRONMENT=development
LOG_LEVEL=INFO
WHISPER_MODEL_SIZE=large-v3
DEVICE=auto
API_HOST=0.0.0.0
API_PORT=8000
ENABLE_GPU=true
CACHE_RESULTS=true
"""
try:
with open(env_file, "w") as f:
f.write(env_content)
logger.info(f"Created environment file: {env_file}")
except Exception as e:
logger.error(f"Failed to create .env file: {e}")
return False
return True
def verify_installation():
"""Verify that the installation is working."""
try:
logger.info("Verifying installation...")
# Test imports
import torch
import whisper
import transformers
import fastapi
import librosa
import soundfile
logger.info(f"PyTorch version: {torch.__version__}")
logger.info(f"CUDA available: {torch.cuda.is_available()}")
logger.info(f"Whisper available: {whisper.__version__}")
logger.info(f"Transformers version: {transformers.__version__}")
logger.info(f"FastAPI version: {fastapi.__version__}")
# Test basic functionality
try:
from src.speech_recognizer import create_speech_recognizer
recognizer = create_speech_recognizer()
health = recognizer.health_check()
if health["status"] == "healthy":
logger.info("β
Speech recognizer is working correctly")
else:
logger.warning(f"β οΈ Speech recognizer health check: {health['status']}")
except Exception as e:
logger.warning(f"Could not test speech recognizer: {e}")
logger.info("Installation verification completed")
return True
except ImportError as e:
logger.error(f"Missing dependency: {e}")
return False
except Exception as e:
logger.error(f"Verification failed: {e}")
return False
def print_usage_instructions():
"""Print usage instructions."""
base_dir = Path(__file__).parent
instructions = f"""
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β OPTIMIZED TWI SPEECH ENGINE SETUP COMPLETE β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
π Installation completed successfully!
π Project Structure:
{base_dir}/
βββ src/ # Source code
βββ config/ # Configuration files
βββ data/ # Data storage
βββ models/ # Model storage
βββ logs/ # Log files
βββ tests/ # Test files
π Quick Start:
1. Start the API server:
cd {base_dir}
python -m src.api_server
2. Test the health endpoint:
curl http://localhost:8000/health
3. Upload audio for recognition:
curl -X POST -F "file=@audio.wav" http://localhost:8000/test-
intent
4. View API documentation:
Open http://localhost:8000/docs in your browser
π Configuration:
- Edit .env file for environment settings
- Modify config/config.py for advanced configuration
- Check logs/ directory for debugging information
π§ Supported Features:
β
Whisper speech-to-text (25+ languages)
β
Twi intent classification (25 intents)
β
WebM/WAV audio support
β
Real-time processing
β
Batch processing
β
Performance monitoring
π‘ Tips:
- Use GPU for faster processing (CUDA detected: {torch.cuda.is_available() if "torch" in globals() else "Unknown"})
- Monitor logs/optimized_engine.log for debugging
- Check /statistics endpoint for performance metrics
Need help? Check the documentation or logs for troubleshooting.
"""
print(instructions)
def main():
"""Main setup function."""
logger.info("Starting Optimized Twi Speech Engine setup...")
# Check Python version
if not check_python_version():
sys.exit(1)
# Setup directories
if not setup_directories():
logger.error("Failed to setup directories")
sys.exit(1)
# Install requirements
if not install_requirements():
logger.error("Failed to install requirements")
sys.exit(1)
# Create configuration files
if not create_config_files():
logger.error("Failed to create configuration files")
sys.exit(1)
# Download Whisper model
if not download_whisper_model():
logger.warning("Failed to download Whisper model (will download on first use)")
# Verify installation
if not verify_installation():
logger.warning(
"Installation verification had some issues, but setup may still work"
)
# Print usage instructions
print_usage_instructions()
logger.info("Setup completed successfully! π")
if __name__ == "__main__":
main()
|