Spaces:
Sleeping
Sleeping
File size: 14,579 Bytes
5a65ad6 |
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 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 |
#!/usr/bin/env python3
"""
AI Speech Translation System - Deployment Version
Optimized for Hugging Face Spaces deployment
Features:
- Real-time speech recognition with Whisper
- Auto language detection for 12+ languages
- Enhanced Hindi-English translation
- Text-to-speech output
- Beautiful Apple-style dark mode UI
"""
import gradio as gr
import sys
import os
import time
import tempfile
import threading
from pathlib import Path
from typing import Optional, Tuple, Dict, Any
import numpy as np
import soundfile as sf
# Add src to Python path for local imports
current_dir = Path(__file__).parent
src_path = current_dir / "src"
if src_path.exists():
sys.path.insert(0, str(src_path))
# Import with error handling for deployment
try:
import whisper
import librosa
WHISPER_AVAILABLE = True
except ImportError as e:
print(f"โ ๏ธ Whisper not available: {e}")
WHISPER_AVAILABLE = False
try:
from translation.improved_translator import create_improved_translator
from tts.tts_service import create_tts_service
SERVICES_AVAILABLE = True
except ImportError as e:
print(f"โ ๏ธ Services not available: {e}")
SERVICES_AVAILABLE = False
class DeploymentSpeechApp:
"""Production-ready speech translation app"""
def __init__(self):
self.whisper_model = None
self.translator = None
self.tts_service = None
self.initialization_status = "๐ Initializing system..."
self.system_ready = False
# Language options
self.languages = {
"auto": "๐ Auto-detect",
"hi": "๐ฎ๐ณ Hindi",
"en": "๐บ๐ธ English",
"es": "๐ช๐ธ Spanish",
"fr": "๐ซ๐ท French",
"de": "๐ฉ๐ช German",
"it": "๐ฎ๐น Italian",
"pt": "๐ต๐น Portuguese",
"ru": "๐ท๐บ Russian",
"ja": "๐ฏ๐ต Japanese",
"ko": "๐ฐ๐ท Korean",
"zh": "๐จ๐ณ Chinese",
"ar": "๐ธ๐ฆ Arabic"
}
self.temp_dir = Path(tempfile.gettempdir()) / "speech_translation_deploy"
self.temp_dir.mkdir(exist_ok=True)
# Start initialization
self._start_initialization()
def _start_initialization(self):
"""Initialize system components"""
def init_worker():
try:
if not WHISPER_AVAILABLE or not SERVICES_AVAILABLE:
self.initialization_status = "โ Missing dependencies for full functionality"
return
self.initialization_status = "๐๏ธ Loading speech recognition..."
self.whisper_model = whisper.load_model("small")
self.initialization_status = "๐ Setting up translation..."
self.translator = create_improved_translator()
self.initialization_status = "๐ต Preparing text-to-speech..."
self.tts_service = create_tts_service()
self.initialization_status = "โ
System ready!"
self.system_ready = True
except Exception as e:
self.initialization_status = f"โ Initialization failed: {str(e)}"
self.system_ready = False
threading.Thread(target=init_worker, daemon=True).start()
def get_system_status(self) -> str:
return self.initialization_status
def process_audio(
self,
audio_file: str,
target_lang: str = "en"
) -> Tuple[str, str, str, Optional[str], str]:
"""Process audio file and return results"""
if not self.system_ready:
status = f"โณ System not ready. Status: {self.initialization_status}"
return "", "", "", None, status
if audio_file is None:
return "", "", "", None, "โ Please upload an audio file"
try:
start_time = time.time()
# Step 1: Transcribe
result = self.whisper_model.transcribe(
audio_file,
task="transcribe",
verbose=False
)
transcription = result['text'].strip()
detected_lang = result.get('language', 'unknown')
if not transcription:
return "", "", detected_lang, None, "โ No speech detected"
# Step 2: Translate
if target_lang == "auto":
target_lang = "en" if detected_lang != "en" else "hi"
translation_result = self.translator.translate_text(
text=transcription,
source_lang=detected_lang,
target_lang=target_lang
)
if not translation_result['success']:
return transcription, "", detected_lang, None, f"โ Translation failed"
translation = translation_result['translated_text']
# Step 3: Generate speech
timestamp = int(time.time())
audio_filename = f"output_{timestamp}.wav"
audio_output_path = self.temp_dir / audio_filename
tts_result = self.tts_service.synthesize_speech(
text=translation,
language=target_lang,
output_path=str(audio_output_path)
)
if not tts_result['success']:
return transcription, translation, detected_lang, None, f"โ TTS failed"
audio_output = tts_result['audio_path']
# Final status
total_time = time.time() - start_time
status = f"""
โ
**Translation Complete!**
**๐ Summary:**
- โฑ๏ธ **Time:** {total_time:.1f}s
- ๐ **From:** {detected_lang.upper()} โ {target_lang.upper()}
- ๐ต **Engine:** {tts_result['engine']}
- ๐ **Service:** {translation_result.get('service', 'Unknown')}
"""
return transcription, translation, detected_lang, audio_output, status
except Exception as e:
return "", "", "", None, f"โ Error: {str(e)}"
def create_interface(self):
"""Create the Gradio interface"""
# Enhanced CSS for production
css = """
/* Production-ready Apple Dark Mode */
.gradio-container {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important;
background: #000000;
color: #ffffff;
}
body {
background: #000000 !important;
color: #ffffff !important;
}
.header-gradient {
background: linear-gradient(135deg, #1d1d1f 0%, #2c2c2e 100%);
color: #ffffff;
padding: 32px;
border-radius: 16px;
margin-bottom: 24px;
text-align: center;
border: 1px solid #48484a;
}
.status-box {
background: linear-gradient(135deg, #007aff 0%, #5856d6 100%);
color: #ffffff;
padding: 16px;
border-radius: 12px;
text-align: center;
margin: 16px 0;
font-weight: 500;
}
/* Force dark mode for all components */
.gradio-container * {
background-color: #1c1c1e !important;
color: #ffffff !important;
}
.gradio-container .gr-button {
background: #007aff !important;
color: #ffffff !important;
border: none !important;
border-radius: 8px !important;
font-weight: 500 !important;
}
.gradio-container .gr-button:hover {
background: #0a84ff !important;
}
.gradio-container .gr-textbox,
.gradio-container .gr-textbox input,
.gradio-container .gr-textbox textarea {
background: #2c2c2e !important;
border: 1px solid #48484a !important;
color: #ffffff !important;
border-radius: 8px !important;
}
.gradio-container .gr-dropdown,
.gradio-container .gr-dropdown select {
background: #2c2c2e !important;
border: 1px solid #48484a !important;
color: #ffffff !important;
border-radius: 8px !important;
}
"""
with gr.Blocks(css=css, title="AI Speech Translation System") as interface:
# Header
gr.HTML("""
<div class="header-gradient">
<h1 style="font-size: 2.5em; margin: 0; font-weight: 700;">๐๏ธ AI Speech Translator</h1>
<p style="font-size: 1.2em; margin: 16px 0 0 0; opacity: 0.8;">
Real-time Speech Translation โข Auto Language Detection โข 12+ Languages
</p>
<p style="font-size: 1em; margin: 8px 0 0 0; opacity: 0.6;">
Upload audio โ Automatic transcription โ Smart translation โ Natural speech output
</p>
</div>
""")
# Status display
with gr.Row():
status_display = gr.Markdown(
value=f"**{self.get_system_status()}**",
elem_classes=["status-box"]
)
# Main interface
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### ๐ค Upload & Configure")
audio_input = gr.Audio(
label="๐ค Upload Audio or Record",
type="filepath",
sources=["upload", "microphone"]
)
target_lang = gr.Dropdown(
choices=list(self.languages.keys()),
value="en",
label="๐ฏ Target Language"
)
process_btn = gr.Button("๐ Translate Audio", variant="primary", size="lg")
with gr.Column(scale=1):
gr.Markdown("### ๐ Results")
detected_lang_display = gr.Textbox(
label="๐ Detected Language",
interactive=False
)
transcription_output = gr.Textbox(
label="๐ Original Text",
lines=3
)
translation_output = gr.Textbox(
label="๐ Translated Text",
lines=3
)
audio_output = gr.Audio(label="๐ต Translated Speech")
# Detailed status
detailed_status = gr.Markdown(
value="Upload an audio file and click 'Translate Audio' to start..."
)
# Event handlers
process_btn.click(
self.process_audio,
inputs=[audio_input, target_lang],
outputs=[
transcription_output,
translation_output,
detected_lang_display,
audio_output,
detailed_status
]
)
# Tips section
with gr.Accordion("๐ก How to Use", open=False):
gr.Markdown("""
### ๐ฏ Quick Start
1. **Upload** an audio file (WAV, MP3, M4A) or record directly
2. **Select** your target language (or keep "Auto-detect")
3. **Click** "Translate Audio"
4. **Listen** to the results!
### โจ Features
- ๐ **Auto Language Detection** - Automatically detects 12+ languages
- ๐ฏ **Enhanced Hindi Support** - Optimized for Hindi-English translation
- ๐ต **Natural Speech Output** - High-quality text-to-speech synthesis
- ๐ **Beautiful UI** - Apple-inspired dark mode design
### ๐ Supported Languages
Hindi, English, Spanish, French, German, Italian, Portuguese, Russian, Japanese, Korean, Chinese, Arabic
### ๐๏ธ Tech Stack
- **Speech Recognition**: OpenAI Whisper
- **Translation**: Enhanced algorithms + API fallbacks
- **Speech Synthesis**: Google TTS + offline engines
- **Interface**: Gradio with custom styling
""")
# Footer
gr.HTML("""
<div style="text-align: center; margin-top: 32px; padding: 24px; background: #1c1c1e; border-radius: 12px;">
<p style="color: #98989d; margin: 0; font-size: 14px;">
๐ AI Speech Translation System โข Built with Whisper, Gradio & Modern ML
</p>
</div>
""")
return interface
def main():
"""Launch the application"""
print("๐ Starting AI Speech Translation System...")
print("๐ Deployment-ready version for cloud hosting")
app = DeploymentSpeechApp()
interface = app.create_interface()
# Launch configuration for deployment
interface.launch(
server_name="0.0.0.0", # Listen on all interfaces for cloud deployment
server_port=7860, # Standard port for Hugging Face Spaces
share=False,
debug=False,
show_api=False,
inbrowser=False # Don't auto-open browser in cloud
)
if __name__ == "__main__":
main() |