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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
|
| 4 |
+
import sys
|
| 5 |
+
import io
|
| 6 |
+
import os
|
| 7 |
+
import locale
|
| 8 |
+
|
| 9 |
+
# Comprehensive UTF-8 encoding setup for Windows
|
| 10 |
+
if sys.platform.startswith('win'):
|
| 11 |
+
try:
|
| 12 |
+
# Set locale to UTF-8
|
| 13 |
+
try:
|
| 14 |
+
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
|
| 15 |
+
except:
|
| 16 |
+
try:
|
| 17 |
+
locale.setlocale(locale.LC_ALL, 'C.UTF-8')
|
| 18 |
+
except:
|
| 19 |
+
pass
|
| 20 |
+
|
| 21 |
+
# Set console to UTF-8 mode
|
| 22 |
+
os.system('chcp 65001 > nul 2>&1')
|
| 23 |
+
|
| 24 |
+
# Set environment variables for UTF-8
|
| 25 |
+
os.environ['PYTHONIOENCODING'] = 'utf-8:replace'
|
| 26 |
+
os.environ['PYTHONUTF8'] = '1'
|
| 27 |
+
|
| 28 |
+
# Force UTF-8 encoding for stdout/stderr with error handling
|
| 29 |
+
try:
|
| 30 |
+
if hasattr(sys.stdout, 'reconfigure'):
|
| 31 |
+
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
|
| 32 |
+
sys.stderr.reconfigure(encoding='utf-8', errors='replace')
|
| 33 |
+
else:
|
| 34 |
+
# Fallback for older Python versions
|
| 35 |
+
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
|
| 36 |
+
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')
|
| 37 |
+
except Exception:
|
| 38 |
+
# Final fallback
|
| 39 |
+
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding='utf-8', errors='replace')
|
| 40 |
+
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding='utf-8', errors='replace')
|
| 41 |
+
|
| 42 |
+
except Exception as e:
|
| 43 |
+
# Silently continue if encoding setup fails
|
| 44 |
+
pass
|
| 45 |
+
|
| 46 |
+
# Store original print function before any imports
|
| 47 |
+
import builtins
|
| 48 |
+
_original_print = builtins.print
|
| 49 |
+
|
| 50 |
+
def safe_print(*args, **kwargs):
|
| 51 |
+
"""Safe print function that handles UTF-8 encoding"""
|
| 52 |
+
try:
|
| 53 |
+
# Convert all arguments to strings first to avoid encoding issues
|
| 54 |
+
safe_args = []
|
| 55 |
+
for arg in args:
|
| 56 |
+
if isinstance(arg, str):
|
| 57 |
+
# Ensure string can be encoded/decoded properly
|
| 58 |
+
try:
|
| 59 |
+
arg.encode('utf-8')
|
| 60 |
+
safe_args.append(arg)
|
| 61 |
+
except UnicodeEncodeError:
|
| 62 |
+
safe_args.append(arg.encode('utf-8', errors='replace').decode('utf-8'))
|
| 63 |
+
else:
|
| 64 |
+
safe_args.append(str(arg))
|
| 65 |
+
|
| 66 |
+
_original_print(*safe_args, **kwargs)
|
| 67 |
+
except (UnicodeEncodeError, UnicodeDecodeError) as e:
|
| 68 |
+
# Last resort: convert to ASCII with replacement
|
| 69 |
+
ascii_args = []
|
| 70 |
+
for arg in args:
|
| 71 |
+
if isinstance(arg, str):
|
| 72 |
+
ascii_args.append(arg.encode('ascii', errors='replace').decode('ascii'))
|
| 73 |
+
else:
|
| 74 |
+
ascii_args.append(str(arg).encode('ascii', errors='replace').decode('ascii'))
|
| 75 |
+
_original_print(*ascii_args, **kwargs)
|
| 76 |
+
except Exception:
|
| 77 |
+
# Ultimate fallback
|
| 78 |
+
_original_print("[Encoding Error in Print]")
|
| 79 |
+
|
| 80 |
+
# Override built-in print
|
| 81 |
+
builtins.print = safe_print
|
| 82 |
+
"""
|
| 83 |
+
Live Translation AI Agent - Two Person Mode
|
| 84 |
+
Real-time Cross-Translation between Person A & Person B
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
import gradio as gr
|
| 88 |
+
import numpy as np
|
| 89 |
+
import librosa
|
| 90 |
+
import soundfile as sf
|
| 91 |
+
import tempfile
|
| 92 |
+
import os
|
| 93 |
+
import time
|
| 94 |
+
import logging
|
| 95 |
+
import json
|
| 96 |
+
from typing import Optional, Tuple, Dict, List
|
| 97 |
+
import asyncio
|
| 98 |
+
import threading
|
| 99 |
+
from pathlib import Path
|
| 100 |
+
|
| 101 |
+
# Load environment variables from .env file
|
| 102 |
+
try:
|
| 103 |
+
from dotenv import load_dotenv
|
| 104 |
+
load_dotenv()
|
| 105 |
+
print("Environment variables loaded from .env file")
|
| 106 |
+
except ImportError:
|
| 107 |
+
print("python-dotenv not available, using system environment variables")
|
| 108 |
+
|
| 109 |
+
# OpenAI integration
|
| 110 |
+
try:
|
| 111 |
+
import openai
|
| 112 |
+
OPENAI_AVAILABLE = True
|
| 113 |
+
print("OpenAI library loaded successfully")
|
| 114 |
+
except ImportError:
|
| 115 |
+
OPENAI_AVAILABLE = False
|
| 116 |
+
print("OpenAI library not available")
|
| 117 |
+
|
| 118 |
+
# Edge TTS for speech synthesis
|
| 119 |
+
try:
|
| 120 |
+
import edge_tts
|
| 121 |
+
EDGE_TTS_AVAILABLE = True
|
| 122 |
+
print("Edge TTS loaded successfully")
|
| 123 |
+
except ImportError:
|
| 124 |
+
EDGE_TTS_AVAILABLE = False
|
| 125 |
+
print("Edge TTS not available")
|
| 126 |
+
|
| 127 |
+
# Configure logging
|
| 128 |
+
logging.basicConfig(level=logging.INFO)
|
| 129 |
+
logger = logging.getLogger(__name__)
|
| 130 |
+
|
| 131 |
+
class TranslationAIAgent:
|
| 132 |
+
"""Main AI Agent for translation tasks - OpenAI Powered"""
|
| 133 |
+
|
| 134 |
+
def __init__(self):
|
| 135 |
+
# Enhanced language and voice options with country flags
|
| 136 |
+
self.language_voice_options = {
|
| 137 |
+
'en': {
|
| 138 |
+
'name': 'English',
|
| 139 |
+
'options': [
|
| 140 |
+
{'code': 'en-us', 'display': 'English (United States)', 'voice': 'en-US-JennyNeural', 'alt_voice': 'en-US-GuyNeural'},
|
| 141 |
+
{'code': 'en-gb', 'display': 'English (United Kingdom)', 'voice': 'en-GB-LibbyNeural', 'alt_voice': 'en-GB-RyanNeural'},
|
| 142 |
+
]
|
| 143 |
+
},
|
| 144 |
+
'es': {
|
| 145 |
+
'name': 'Spanish',
|
| 146 |
+
'options': [
|
| 147 |
+
{'code': 'es-es', 'display': 'Spanish (Spain)', 'voice': 'es-ES-ElviraNeural', 'alt_voice': 'es-ES-AlvaroNeural'},
|
| 148 |
+
{'code': 'es-mx', 'display': 'Spanish (Mexico)', 'voice': 'es-MX-DaliaNeural', 'alt_voice': 'es-MX-JorgeNeural'},
|
| 149 |
+
]
|
| 150 |
+
},
|
| 151 |
+
'fr': {
|
| 152 |
+
'name': 'French',
|
| 153 |
+
'options': [
|
| 154 |
+
{'code': 'fr-fr', 'display': 'French (France)', 'voice': 'fr-FR-DeniseNeural', 'alt_voice': 'fr-FR-HenriNeural'},
|
| 155 |
+
{'code': 'fr-ca', 'display': 'French (Canada)', 'voice': 'fr-CA-SylvieNeural', 'alt_voice': 'fr-CA-AntoineNeural'},
|
| 156 |
+
]
|
| 157 |
+
},
|
| 158 |
+
'de': {
|
| 159 |
+
'name': 'German',
|
| 160 |
+
'options': [
|
| 161 |
+
{'code': 'de-de', 'display': 'German (Germany)', 'voice': 'de-DE-KatjaNeural', 'alt_voice': 'de-DE-ConradNeural'},
|
| 162 |
+
]
|
| 163 |
+
},
|
| 164 |
+
'vi': {
|
| 165 |
+
'name': 'Vietnamese',
|
| 166 |
+
'options': [
|
| 167 |
+
{'code': 'vi-vn', 'display': 'Vietnamese (Vietnam)', 'voice': 'vi-VN-HoaiMyNeural', 'alt_voice': 'vi-VN-NamMinhNeural'}
|
| 168 |
+
]
|
| 169 |
+
},
|
| 170 |
+
'ja': {
|
| 171 |
+
'name': 'Japanese',
|
| 172 |
+
'options': [
|
| 173 |
+
{'code': 'ja-jp', 'display': 'Japanese (Japan)', 'voice': 'ja-JP-NanamiNeural', 'alt_voice': 'ja-JP-KeitaNeural'}
|
| 174 |
+
]
|
| 175 |
+
},
|
| 176 |
+
'zh': {
|
| 177 |
+
'name': 'Chinese',
|
| 178 |
+
'options': [
|
| 179 |
+
{'code': 'zh-cn', 'display': 'Chinese (Simplified)', 'voice': 'zh-CN-XiaoxiaoNeural', 'alt_voice': 'zh-CN-YunxiNeural'},
|
| 180 |
+
]
|
| 181 |
+
}
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
# Create simple supported languages mapping for backward compatibility
|
| 185 |
+
self.supported_languages = {
|
| 186 |
+
lang_code: lang_info['name']
|
| 187 |
+
for lang_code, lang_info in self.language_voice_options.items()
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
# Create default voice mapping for backward compatibility
|
| 191 |
+
self.voice_map = {
|
| 192 |
+
lang_code: lang_info['options'][0]['voice']
|
| 193 |
+
for lang_code, lang_info in self.language_voice_options.items()
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
self.setup_openai_client()
|
| 197 |
+
|
| 198 |
+
def setup_openai_client(self):
|
| 199 |
+
"""Setup OpenAI client for translation and transcription"""
|
| 200 |
+
try:
|
| 201 |
+
if not OPENAI_AVAILABLE:
|
| 202 |
+
logger.error("OpenAI library not available - please install: pip install openai")
|
| 203 |
+
self.openai_client = None
|
| 204 |
+
self.openai_configured = False
|
| 205 |
+
return
|
| 206 |
+
|
| 207 |
+
# Get OpenAI API key from environment
|
| 208 |
+
api_key = (
|
| 209 |
+
os.environ.get("OPENAI_API_KEY") or
|
| 210 |
+
os.environ.get("OPENAI_KEY") or
|
| 211 |
+
os.getenv("OPENAI_API_KEY")
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
if api_key and api_key.strip() and not api_key.strip().startswith("your-"):
|
| 215 |
+
self.openai_client = openai.OpenAI(api_key=api_key.strip())
|
| 216 |
+
self.openai_configured = True
|
| 217 |
+
logger.info("[SUCCESS] OpenAI client configured successfully - Real translation mode enabled")
|
| 218 |
+
else:
|
| 219 |
+
self.openai_client = None
|
| 220 |
+
self.openai_configured = False
|
| 221 |
+
logger.error("β OpenAI API key not found or invalid in environment variables")
|
| 222 |
+
logger.error("Please set OPENAI_API_KEY in your .env file with a valid API key")
|
| 223 |
+
|
| 224 |
+
except Exception as e:
|
| 225 |
+
logger.error(f"OpenAI setup failed: {e}")
|
| 226 |
+
self.openai_client = None
|
| 227 |
+
self.openai_configured = False
|
| 228 |
+
|
| 229 |
+
def speech_to_text(self, audio_path: str, language: str = 'auto') -> tuple[str, str]:
|
| 230 |
+
"""Convert speech to text using OpenAI Whisper API with language detection"""
|
| 231 |
+
try:
|
| 232 |
+
if not self.openai_configured:
|
| 233 |
+
raise Exception("OpenAI client not configured. Please check your API key.")
|
| 234 |
+
|
| 235 |
+
if not os.path.exists(audio_path):
|
| 236 |
+
raise Exception(f"Audio file not found: {audio_path}")
|
| 237 |
+
|
| 238 |
+
with open(audio_path, "rb") as audio_file:
|
| 239 |
+
# Use verbose_json to get language detection
|
| 240 |
+
transcript = self.openai_client.audio.transcriptions.create(
|
| 241 |
+
model="whisper-1",
|
| 242 |
+
file=audio_file,
|
| 243 |
+
response_format="verbose_json",
|
| 244 |
+
language=None # Auto-detect language
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
text = transcript.text.strip()
|
| 248 |
+
detected_language = transcript.language
|
| 249 |
+
|
| 250 |
+
# Map language code to display name
|
| 251 |
+
language_names = {
|
| 252 |
+
'en': 'English',
|
| 253 |
+
'vi': 'Vietnamese',
|
| 254 |
+
'es': 'Spanish',
|
| 255 |
+
'fr': 'French',
|
| 256 |
+
'de': 'German',
|
| 257 |
+
'it': 'Italian',
|
| 258 |
+
'pt': 'Portuguese',
|
| 259 |
+
'ru': 'Russian',
|
| 260 |
+
'ja': 'Japanese',
|
| 261 |
+
'ko': 'Korean',
|
| 262 |
+
'zh': 'Chinese',
|
| 263 |
+
'ar': 'Arabic',
|
| 264 |
+
'hi': 'Hindi',
|
| 265 |
+
'th': 'Thai',
|
| 266 |
+
'tr': 'Turkish'
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
detected_language_name = language_names.get(detected_language, detected_language)
|
| 270 |
+
|
| 271 |
+
if text and len(text) > 2:
|
| 272 |
+
logger.info(f"OpenAI Whisper transcription: {text[:100]}...")
|
| 273 |
+
logger.info(f"Detected Language: {detected_language_name} ({detected_language})")
|
| 274 |
+
return text, detected_language_name
|
| 275 |
+
else:
|
| 276 |
+
return "No speech detected in audio file", "unknown"
|
| 277 |
+
|
| 278 |
+
except Exception as e:
|
| 279 |
+
error_msg = str(e)
|
| 280 |
+
logger.error(f"Speech recognition error: {error_msg}")
|
| 281 |
+
|
| 282 |
+
# Check for quota exceeded error
|
| 283 |
+
if "429" in error_msg or "quota" in error_msg.lower() or "insufficient_quota" in error_msg.lower():
|
| 284 |
+
logger.warning("[WARNING] OpenAI API quota exceeded - using fallback mode")
|
| 285 |
+
duration = self.get_audio_duration(audio_path)
|
| 286 |
+
return f"[API Quota Exceeded] Please add credits to your OpenAI account. Audio duration: {duration:.1f}s", "English"
|
| 287 |
+
|
| 288 |
+
raise Exception(f"Speech recognition failed: {error_msg}")
|
| 289 |
+
|
| 290 |
+
def get_audio_duration(self, audio_path: str) -> float:
|
| 291 |
+
"""Get duration of audio file"""
|
| 292 |
+
try:
|
| 293 |
+
y, sr = librosa.load(audio_path)
|
| 294 |
+
return len(y) / sr
|
| 295 |
+
except:
|
| 296 |
+
return 0.0
|
| 297 |
+
|
| 298 |
+
def translate_text(self, text: str, source_lang: str, target_lang: str) -> str:
|
| 299 |
+
"""Translate text using OpenAI GPT-4o Mini"""
|
| 300 |
+
try:
|
| 301 |
+
if not self.openai_configured:
|
| 302 |
+
raise Exception("OpenAI client not configured. Please check your API key.")
|
| 303 |
+
|
| 304 |
+
# Create translation prompt
|
| 305 |
+
source_name = self.supported_languages.get(source_lang, source_lang)
|
| 306 |
+
target_name = self.supported_languages.get(target_lang, target_lang)
|
| 307 |
+
|
| 308 |
+
prompt = f"""Translate the following {source_name} text to {target_name}. Provide only the translation, no explanations:
|
| 309 |
+
|
| 310 |
+
{text}"""
|
| 311 |
+
|
| 312 |
+
response = self.openai_client.chat.completions.create(
|
| 313 |
+
model="gpt-4o-mini", # Using latest GPT-4o-mini model
|
| 314 |
+
messages=[{"role": "user", "content": prompt}],
|
| 315 |
+
max_tokens=500,
|
| 316 |
+
temperature=0.3
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
translated_text = response.choices[0].message.content.strip()
|
| 320 |
+
logger.info(f"OpenAI translation successful: {translated_text[:100]}...")
|
| 321 |
+
return translated_text
|
| 322 |
+
|
| 323 |
+
except Exception as e:
|
| 324 |
+
error_msg = str(e)
|
| 325 |
+
logger.error(f"Translation error: {error_msg}")
|
| 326 |
+
|
| 327 |
+
# Check for quota exceeded error
|
| 328 |
+
if "429" in error_msg or "quota" in error_msg.lower() or "insufficient_quota" in error_msg.lower():
|
| 329 |
+
logger.warning("[WARNING] OpenAI API quota exceeded - using fallback translation")
|
| 330 |
+
target_name = self.supported_languages.get(target_lang, target_lang)
|
| 331 |
+
return f"[API Quota Exceeded] Please add credits to your OpenAI account. Original text: {text}"
|
| 332 |
+
|
| 333 |
+
raise Exception(f"Translation failed: {error_msg}")
|
| 334 |
+
|
| 335 |
+
async def generate_speech_with_custom_voice(self, text: str, voice: str) -> str:
|
| 336 |
+
"""Generate speech using Edge TTS with custom voice"""
|
| 337 |
+
try:
|
| 338 |
+
if not EDGE_TTS_AVAILABLE:
|
| 339 |
+
logger.warning("Edge TTS not available")
|
| 340 |
+
return None
|
| 341 |
+
|
| 342 |
+
# Create temporary output file
|
| 343 |
+
temp_dir = tempfile.gettempdir()
|
| 344 |
+
output_path = os.path.join(temp_dir, f"tts_output_{int(time.time())}.wav")
|
| 345 |
+
|
| 346 |
+
# Generate speech with specific voice
|
| 347 |
+
communicate = edge_tts.Communicate(text, voice)
|
| 348 |
+
await communicate.save(output_path)
|
| 349 |
+
|
| 350 |
+
if os.path.exists(output_path):
|
| 351 |
+
logger.info(f"Edge TTS generated with {voice}: {output_path}")
|
| 352 |
+
return output_path
|
| 353 |
+
else:
|
| 354 |
+
return None
|
| 355 |
+
|
| 356 |
+
except Exception as e:
|
| 357 |
+
logger.error(f"TTS Error: {e}")
|
| 358 |
+
return None
|
| 359 |
+
|
| 360 |
+
def process_audio_translation_with_voice(
|
| 361 |
+
self,
|
| 362 |
+
audio_path: str,
|
| 363 |
+
target_lang: str,
|
| 364 |
+
voice: str
|
| 365 |
+
) -> Tuple[str, str, str, Optional[str]]:
|
| 366 |
+
"""Complete audio translation pipeline with custom voice selection"""
|
| 367 |
+
|
| 368 |
+
if not audio_path:
|
| 369 |
+
return "Please upload an audio file", "", "", None
|
| 370 |
+
|
| 371 |
+
logger.info(f"Processing audio translation with auto-detection -> {target_lang} (voice: {voice})")
|
| 372 |
+
|
| 373 |
+
# Step 1: Speech to text with OpenAI Whisper + Language Detection
|
| 374 |
+
logger.info("Step 1: Transcribing audio with language detection...")
|
| 375 |
+
transcribed_text, detected_language = self.speech_to_text(audio_path)
|
| 376 |
+
|
| 377 |
+
if transcribed_text.startswith("Error"):
|
| 378 |
+
return transcribed_text, "", "", None
|
| 379 |
+
|
| 380 |
+
logger.info(f"Transcription: {transcribed_text[:100]}...")
|
| 381 |
+
logger.info(f"Detected Language: {detected_language}")
|
| 382 |
+
|
| 383 |
+
# Step 2: Translate text with OpenAI GPT-4o Mini using detected language
|
| 384 |
+
logger.info("Step 2: Translating text...")
|
| 385 |
+
# Map detected language name to code for translation
|
| 386 |
+
lang_code_map = {
|
| 387 |
+
'English': 'en', 'Vietnamese': 'vi', 'Spanish': 'es', 'French': 'fr',
|
| 388 |
+
'German': 'de', 'Italian': 'it', 'Portuguese': 'pt', 'Russian': 'ru',
|
| 389 |
+
'Japanese': 'ja', 'Korean': 'ko', 'Chinese': 'zh', 'Arabic': 'ar',
|
| 390 |
+
'Hindi': 'hi', 'Thai': 'th', 'Turkish': 'tr'
|
| 391 |
+
}
|
| 392 |
+
|
| 393 |
+
detected_lang_code = lang_code_map.get(detected_language, 'en')
|
| 394 |
+
translated_text = self.translate_text(transcribed_text, detected_lang_code, target_lang)
|
| 395 |
+
|
| 396 |
+
if translated_text.startswith("[Translation Error]"):
|
| 397 |
+
return transcribed_text, detected_language, translated_text, None
|
| 398 |
+
|
| 399 |
+
logger.info(f"Translation: {translated_text[:100]}...")
|
| 400 |
+
|
| 401 |
+
# Step 3: Generate speech with Edge TTS using custom voice
|
| 402 |
+
logger.info(f"Step 3: Generating speech with voice: {voice}")
|
| 403 |
+
audio_output = asyncio.run(self.generate_speech_with_custom_voice(translated_text, voice))
|
| 404 |
+
|
| 405 |
+
if audio_output:
|
| 406 |
+
logger.info("Complete translation pipeline successful!")
|
| 407 |
+
else:
|
| 408 |
+
logger.warning("TTS generation failed, returning text only")
|
| 409 |
+
|
| 410 |
+
return transcribed_text, detected_language, translated_text, audio_output
|
| 411 |
+
|
| 412 |
+
# Initialize AI Agent
|
| 413 |
+
agent = TranslationAIAgent()
|
| 414 |
+
|
| 415 |
+
# Interface Functions
|
| 416 |
+
def get_country_options() -> List[str]:
|
| 417 |
+
"""Get country options with flags for target language"""
|
| 418 |
+
choices = []
|
| 419 |
+
for lang_code, lang_info in agent.language_voice_options.items():
|
| 420 |
+
for option in lang_info['options']:
|
| 421 |
+
choice = f"{option['code']} | {option['display']}"
|
| 422 |
+
choices.append(choice)
|
| 423 |
+
return sorted(choices)
|
| 424 |
+
|
| 425 |
+
def get_voice_options_for_country(country_selection: str) -> List[str]:
|
| 426 |
+
"""Get voice options for selected country"""
|
| 427 |
+
if not country_selection or '|' not in country_selection:
|
| 428 |
+
return ["Jenny (Female)", "Guy (Male)"]
|
| 429 |
+
|
| 430 |
+
code = country_selection.split(' | ')[0].strip()
|
| 431 |
+
|
| 432 |
+
for lang_info in agent.language_voice_options.values():
|
| 433 |
+
for option in lang_info['options']:
|
| 434 |
+
if option['code'] == code:
|
| 435 |
+
main_voice = option['voice'].replace('Neural', '').split('-')[-1]
|
| 436 |
+
alt_voice = option['alt_voice'].replace('Neural', '').split('-')[-1]
|
| 437 |
+
|
| 438 |
+
def get_gender(voice_name):
|
| 439 |
+
female_names = ['Jenny', 'Libby', 'Natasha', 'Clara', 'Elvira', 'Dalia', 'Denise', 'Sylvie', 'Katja', 'Elsa', 'Raquel', 'Francisca', 'Svetlana', 'Nanami', 'SunHi', 'Xiaoxiao', 'HoaiMy']
|
| 440 |
+
return "(Female)" if any(name in voice_name for name in female_names) else "(Male)"
|
| 441 |
+
|
| 442 |
+
return [
|
| 443 |
+
f"{main_voice} {get_gender(main_voice)}",
|
| 444 |
+
f"{alt_voice} {get_gender(alt_voice)}"
|
| 445 |
+
]
|
| 446 |
+
|
| 447 |
+
return ["Jenny (Female)", "Guy (Male)"]
|
| 448 |
+
|
| 449 |
+
def get_voice_code_from_selections(country_selection: str, voice_selection: str) -> str:
|
| 450 |
+
"""Get full voice code from country and voice selections"""
|
| 451 |
+
if not country_selection or '|' not in country_selection:
|
| 452 |
+
return 'en-US-JennyNeural'
|
| 453 |
+
|
| 454 |
+
code = country_selection.split(' | ')[0].strip()
|
| 455 |
+
voice_name = voice_selection.split(' (')[0].strip()
|
| 456 |
+
|
| 457 |
+
for lang_info in agent.language_voice_options.values():
|
| 458 |
+
for option in lang_info['options']:
|
| 459 |
+
if option['code'] == code:
|
| 460 |
+
main_voice_name = option['voice'].replace('Neural', '').split('-')[-1]
|
| 461 |
+
alt_voice_name = option['alt_voice'].replace('Neural', '').split('-')[-1]
|
| 462 |
+
|
| 463 |
+
if voice_name == main_voice_name:
|
| 464 |
+
return option['voice']
|
| 465 |
+
elif voice_name == alt_voice_name:
|
| 466 |
+
return option['alt_voice']
|
| 467 |
+
|
| 468 |
+
return 'en-US-JennyNeural'
|
| 469 |
+
|
| 470 |
+
def get_language_code_from_country(country_selection: str) -> str:
|
| 471 |
+
"""Extract language code from country selection"""
|
| 472 |
+
if not country_selection or '|' not in country_selection:
|
| 473 |
+
return 'en'
|
| 474 |
+
|
| 475 |
+
code = country_selection.split(' | ')[0].strip()
|
| 476 |
+
return code.split('-')[0]
|
| 477 |
+
|
| 478 |
+
def update_voice_options(country_selection: str) -> gr.Dropdown:
|
| 479 |
+
"""Update voice dropdown based on country selection"""
|
| 480 |
+
voice_options = get_voice_options_for_country(country_selection)
|
| 481 |
+
return gr.Dropdown(choices=voice_options, value=voice_options[0] if voice_options else "Jenny (Female)")
|
| 482 |
+
|
| 483 |
+
# Global conversation and audio state
|
| 484 |
+
conversation_state = {
|
| 485 |
+
"person_a_messages": [],
|
| 486 |
+
"person_b_messages": [],
|
| 487 |
+
"person_a_translations": [],
|
| 488 |
+
"person_b_translations": [],
|
| 489 |
+
"latest_audio_for_a": None, # Audio that Person A should hear
|
| 490 |
+
"latest_audio_for_b": None # Audio that Person B should hear
|
| 491 |
+
}
|
| 492 |
+
|
| 493 |
+
def add_message_to_conversation(person, original, detected_lang, translation, target_person):
|
| 494 |
+
"""Add message to global conversation state"""
|
| 495 |
+
if original and translation:
|
| 496 |
+
timestamp = time.strftime("%H:%M")
|
| 497 |
+
|
| 498 |
+
if person == "A":
|
| 499 |
+
conversation_state["person_a_messages"].append(f"[{timestamp}] Person A ({detected_lang}): {original}")
|
| 500 |
+
conversation_state["person_b_translations"].append(f"[{timestamp}] -> Person B: {translation}")
|
| 501 |
+
else: # person == "B"
|
| 502 |
+
conversation_state["person_b_messages"].append(f"[{timestamp}] Person B ({detected_lang}): {original}")
|
| 503 |
+
conversation_state["person_a_translations"].append(f"[{timestamp}] -> Person A: {translation}")
|
| 504 |
+
|
| 505 |
+
def get_full_conversation():
|
| 506 |
+
"""Get complete conversation history for both tabs"""
|
| 507 |
+
all_messages = []
|
| 508 |
+
max_length = max(
|
| 509 |
+
len(conversation_state["person_a_messages"]),
|
| 510 |
+
len(conversation_state["person_b_messages"]),
|
| 511 |
+
len(conversation_state["person_a_translations"]),
|
| 512 |
+
len(conversation_state["person_b_translations"])
|
| 513 |
+
)
|
| 514 |
+
|
| 515 |
+
for i in range(max_length):
|
| 516 |
+
if i < len(conversation_state["person_a_messages"]):
|
| 517 |
+
all_messages.append(conversation_state["person_a_messages"][i])
|
| 518 |
+
if i < len(conversation_state["person_b_translations"]):
|
| 519 |
+
all_messages.append(conversation_state["person_b_translations"][i])
|
| 520 |
+
if i < len(conversation_state["person_b_messages"]):
|
| 521 |
+
all_messages.append(conversation_state["person_b_messages"][i])
|
| 522 |
+
if i < len(conversation_state["person_a_translations"]):
|
| 523 |
+
all_messages.append(conversation_state["person_a_translations"][i])
|
| 524 |
+
|
| 525 |
+
return "\n".join(all_messages[-10:]) # Show last 10 messages
|
| 526 |
+
|
| 527 |
+
def translate_person_a_to_b(audio_file, country_b: str, voice_b: str) -> tuple[str, Optional[str]]:
|
| 528 |
+
"""Person A speaks -> results appear in Person B's tab"""
|
| 529 |
+
if audio_file is None:
|
| 530 |
+
return "", None
|
| 531 |
+
|
| 532 |
+
try:
|
| 533 |
+
print(f"[DEBUG] Person A recording: {audio_file}")
|
| 534 |
+
tgt_code = get_language_code_from_country(country_b)
|
| 535 |
+
selected_voice = get_voice_code_from_selections(country_b, voice_b)
|
| 536 |
+
print(f"[DEBUG] Target: {tgt_code}, Voice: {selected_voice}")
|
| 537 |
+
|
| 538 |
+
original_text, detected_lang, translated_text, audio_output = agent.process_audio_translation_with_voice(
|
| 539 |
+
audio_file, tgt_code, selected_voice
|
| 540 |
+
)
|
| 541 |
+
|
| 542 |
+
print(f"[DEBUG] Results: {original_text[:50]}... -> {translated_text[:50]}...")
|
| 543 |
+
print(f"[DEBUG] Audio output: {audio_output}")
|
| 544 |
+
|
| 545 |
+
# Add to conversation
|
| 546 |
+
add_message_to_conversation("A", original_text, detected_lang, translated_text, "B")
|
| 547 |
+
|
| 548 |
+
# Return conversation for Person B's tab and audio
|
| 549 |
+
conversation_history = get_full_conversation()
|
| 550 |
+
print(f"[DEBUG] Conversation length: {len(conversation_history)}")
|
| 551 |
+
|
| 552 |
+
return conversation_history, audio_output
|
| 553 |
+
|
| 554 |
+
except Exception as e:
|
| 555 |
+
print(f"[ERROR] translate_person_a_to_b: {e}")
|
| 556 |
+
return f"Error: {str(e)}", None
|
| 557 |
+
|
| 558 |
+
def translate_person_b_to_a(audio_file, country_a: str, voice_a: str) -> tuple[str, Optional[str]]:
|
| 559 |
+
"""Person B speaks -> results appear in Person A's tab"""
|
| 560 |
+
if audio_file is None:
|
| 561 |
+
return "", None
|
| 562 |
+
|
| 563 |
+
try:
|
| 564 |
+
print(f"[DEBUG] Person B recording: {audio_file}")
|
| 565 |
+
tgt_code = get_language_code_from_country(country_a)
|
| 566 |
+
selected_voice = get_voice_code_from_selections(country_a, voice_a)
|
| 567 |
+
print(f"[DEBUG] Target: {tgt_code}, Voice: {selected_voice}")
|
| 568 |
+
|
| 569 |
+
original_text, detected_lang, translated_text, audio_output = agent.process_audio_translation_with_voice(
|
| 570 |
+
audio_file, tgt_code, selected_voice
|
| 571 |
+
)
|
| 572 |
+
|
| 573 |
+
print(f"[DEBUG] Results: {original_text[:50]}... -> {translated_text[:50]}...")
|
| 574 |
+
print(f"[DEBUG] Audio output: {audio_output}")
|
| 575 |
+
|
| 576 |
+
# Add to conversation
|
| 577 |
+
add_message_to_conversation("B", original_text, detected_lang, translated_text, "A")
|
| 578 |
+
|
| 579 |
+
# Return conversation for Person A's tab and audio
|
| 580 |
+
conversation_history = get_full_conversation()
|
| 581 |
+
print(f"[DEBUG] Conversation length: {len(conversation_history)}")
|
| 582 |
+
|
| 583 |
+
return conversation_history, audio_output
|
| 584 |
+
|
| 585 |
+
except Exception as e:
|
| 586 |
+
print(f"[ERROR] translate_person_b_to_a: {e}")
|
| 587 |
+
return f"Error: {str(e)}", None
|
| 588 |
+
|
| 589 |
+
def get_audio_for_person_a() -> Optional[str]:
|
| 590 |
+
"""Get latest audio that Person A should hear"""
|
| 591 |
+
return conversation_state.get("latest_audio_for_a")
|
| 592 |
+
|
| 593 |
+
def get_audio_for_person_b() -> Optional[str]:
|
| 594 |
+
"""Get latest audio that Person B should hear"""
|
| 595 |
+
return conversation_state.get("latest_audio_for_b")
|
| 596 |
+
|
| 597 |
+
# Create Two-Person Translation Interface
|
| 598 |
+
with gr.Blocks(
|
| 599 |
+
title="ποΈ Two-Person Live Translation",
|
| 600 |
+
theme=gr.themes.Soft(),
|
| 601 |
+
css="""
|
| 602 |
+
.gradio-container { max-width: 1400px !important; margin: 0 auto !important; }
|
| 603 |
+
.header {
|
| 604 |
+
text-align: center;
|
| 605 |
+
background: linear-gradient(135deg, #4A90E2 0%, #FF6B9D 100%);
|
| 606 |
+
color: white;
|
| 607 |
+
padding: 20px;
|
| 608 |
+
border-radius: 10px;
|
| 609 |
+
margin-bottom: 20px;
|
| 610 |
+
}
|
| 611 |
+
.status-box {
|
| 612 |
+
background: rgba(78, 205, 196, 0.1);
|
| 613 |
+
border: 2px solid rgba(78, 205, 196, 0.3);
|
| 614 |
+
border-radius: 10px;
|
| 615 |
+
padding: 15px;
|
| 616 |
+
text-align: center;
|
| 617 |
+
margin: 15px 0;
|
| 618 |
+
}
|
| 619 |
+
"""
|
| 620 |
+
) as demo:
|
| 621 |
+
|
| 622 |
+
# Header
|
| 623 |
+
api_status = "Ready" if agent.openai_configured else "Missing API Key"
|
| 624 |
+
edge_tts_status = "Ready" if EDGE_TTS_AVAILABLE else "Not Available"
|
| 625 |
+
|
| 626 |
+
gr.HTML(f"""
|
| 627 |
+
<div class="header">
|
| 628 |
+
<h1>ποΈ Two-Person Live Translation</h1>
|
| 629 |
+
<p>Real-time Cross-Translation between Person A & Person B</p>
|
| 630 |
+
<div style="margin-top: 15px;">
|
| 631 |
+
<span style="background: rgba(255,255,255,0.2); padding: 6px 12px; border-radius: 15px; margin: 0 5px;">
|
| 632 |
+
<strong>OpenAI:</strong> {api_status}
|
| 633 |
+
</span>
|
| 634 |
+
<span style="background: rgba(255,255,255,0.2); padding: 6px 12px; border-radius: 15px; margin: 0 5px;">
|
| 635 |
+
<strong>Edge TTS:</strong> {edge_tts_status}
|
| 636 |
+
</span>
|
| 637 |
+
</div>
|
| 638 |
+
<div style="margin-top: 10px;">π§ <strong>Digitized Brains</strong></div>
|
| 639 |
+
</div>
|
| 640 |
+
""")
|
| 641 |
+
|
| 642 |
+
# Status Box
|
| 643 |
+
gr.HTML(f"""
|
| 644 |
+
<div class="status-box">
|
| 645 |
+
<h4>π€ AI Pipeline Status</h4>
|
| 646 |
+
<div style="display: flex; justify-content: center; gap: 20px; flex-wrap: wrap;">
|
| 647 |
+
<span><strong>Whisper:</strong> {'Ready' if agent.openai_configured else 'Not Ready'}</span>
|
| 648 |
+
<span><strong>π§ GPT-4o:</strong> {'π’ Ready' if agent.openai_configured else 'π΄ Not Ready'}</span>
|
| 649 |
+
<span><strong>π TTS:</strong> {'π’ Ready' if EDGE_TTS_AVAILABLE else 'π΄ Not Ready'}</span>
|
| 650 |
+
</div>
|
| 651 |
+
</div>
|
| 652 |
+
""")
|
| 653 |
+
|
| 654 |
+
with gr.Tabs():
|
| 655 |
+
# Person A Tab - Only shows translation FROM Person B
|
| 656 |
+
with gr.TabItem("Person A View"):
|
| 657 |
+
gr.Markdown("### Person A receives translations from Person B")
|
| 658 |
+
|
| 659 |
+
# Conversation History for Person A
|
| 660 |
+
conversation_display_a = gr.Textbox(
|
| 661 |
+
label="Full Conversation",
|
| 662 |
+
lines=8,
|
| 663 |
+
interactive=False,
|
| 664 |
+
placeholder="Conversation will appear here...",
|
| 665 |
+
value=""
|
| 666 |
+
)
|
| 667 |
+
|
| 668 |
+
with gr.Row():
|
| 669 |
+
with gr.Column(scale=2):
|
| 670 |
+
mic_a = gr.Audio(
|
| 671 |
+
sources=["microphone"],
|
| 672 |
+
type="filepath",
|
| 673 |
+
label="Person A: Record Your Voice"
|
| 674 |
+
)
|
| 675 |
+
|
| 676 |
+
with gr.Column(scale=1):
|
| 677 |
+
country_b_for_a = gr.Dropdown(
|
| 678 |
+
choices=get_country_options(),
|
| 679 |
+
label="Person B's Language",
|
| 680 |
+
value="vi-vn | Vietnamese (Vietnam)"
|
| 681 |
+
)
|
| 682 |
+
voice_b_for_a = gr.Dropdown(
|
| 683 |
+
choices=["HoaiMy (Female)", "NamMinh (Male)"],
|
| 684 |
+
label="Person B's Voice",
|
| 685 |
+
value="HoaiMy (Female)"
|
| 686 |
+
)
|
| 687 |
+
|
| 688 |
+
# Only show audio FROM Person B (Person A hears this)
|
| 689 |
+
audio_from_b = gr.Audio(
|
| 690 |
+
label="π Translation Audio from Person B",
|
| 691 |
+
interactive=False,
|
| 692 |
+
value=None
|
| 693 |
+
)
|
| 694 |
+
|
| 695 |
+
# Person B Tab - Only shows translation FROM Person A
|
| 696 |
+
with gr.TabItem("Person B View"):
|
| 697 |
+
gr.Markdown("### Person B receives translations from Person A")
|
| 698 |
+
|
| 699 |
+
# Conversation History for Person B
|
| 700 |
+
conversation_display_b = gr.Textbox(
|
| 701 |
+
label="Full Conversation",
|
| 702 |
+
lines=8,
|
| 703 |
+
interactive=False,
|
| 704 |
+
placeholder="Conversation will appear here...",
|
| 705 |
+
value=""
|
| 706 |
+
)
|
| 707 |
+
|
| 708 |
+
with gr.Row():
|
| 709 |
+
with gr.Column(scale=2):
|
| 710 |
+
mic_b = gr.Audio(
|
| 711 |
+
sources=["microphone"],
|
| 712 |
+
type="filepath",
|
| 713 |
+
label="Person B: Record Your Voice"
|
| 714 |
+
)
|
| 715 |
+
|
| 716 |
+
with gr.Column(scale=1):
|
| 717 |
+
country_a_for_b = gr.Dropdown(
|
| 718 |
+
choices=get_country_options(),
|
| 719 |
+
label="Person A's Language",
|
| 720 |
+
value="en-us | English (United States)"
|
| 721 |
+
)
|
| 722 |
+
voice_a_for_b = gr.Dropdown(
|
| 723 |
+
choices=["Jenny (Female)", "Guy (Male)"],
|
| 724 |
+
label="Person A's Voice",
|
| 725 |
+
value="Jenny (Female)"
|
| 726 |
+
)
|
| 727 |
+
|
| 728 |
+
# Only show audio FROM Person A (Person B hears this)
|
| 729 |
+
audio_from_a = gr.Audio(
|
| 730 |
+
label="π Translation Audio from Person A",
|
| 731 |
+
interactive=False,
|
| 732 |
+
value=None
|
| 733 |
+
)
|
| 734 |
+
|
| 735 |
+
# Event Handlers
|
| 736 |
+
# Person A -> Person B
|
| 737 |
+
country_b_for_a.change(
|
| 738 |
+
fn=update_voice_options,
|
| 739 |
+
inputs=[country_b_for_a],
|
| 740 |
+
outputs=[voice_b_for_a]
|
| 741 |
+
)
|
| 742 |
+
|
| 743 |
+
# Person A records -> Audio & translation appears in Person B's tab
|
| 744 |
+
mic_a.change(
|
| 745 |
+
fn=translate_person_a_to_b,
|
| 746 |
+
inputs=[mic_a, country_b_for_a, voice_b_for_a],
|
| 747 |
+
outputs=[conversation_display_b, audio_from_a] # Results appear in Person B's tab
|
| 748 |
+
)
|
| 749 |
+
|
| 750 |
+
# Person B -> Person A
|
| 751 |
+
country_a_for_b.change(
|
| 752 |
+
fn=update_voice_options,
|
| 753 |
+
inputs=[country_a_for_b],
|
| 754 |
+
outputs=[voice_a_for_b]
|
| 755 |
+
)
|
| 756 |
+
|
| 757 |
+
# Person B records -> Audio & translation appears in Person A's tab
|
| 758 |
+
mic_b.change(
|
| 759 |
+
fn=translate_person_b_to_a,
|
| 760 |
+
inputs=[mic_b, country_a_for_b, voice_a_for_b],
|
| 761 |
+
outputs=[conversation_display_a, audio_from_b] # Results appear in Person A's tab
|
| 762 |
+
)
|
| 763 |
+
|
| 764 |
+
if __name__ == "__main__":
|
| 765 |
+
print("===== Two-Person Live Translation Startup =====")
|
| 766 |
+
print("Starting Two-Person Live Translation")
|
| 767 |
+
print(f"OpenAI API Status: {'Ready' if agent.openai_configured else 'Missing - Set OPENAI_API_KEY'}")
|
| 768 |
+
print(f"Edge TTS Status: {'Ready' if EDGE_TTS_AVAILABLE else 'Not Available'}")
|
| 769 |
+
|
| 770 |
+
if agent.openai_configured:
|
| 771 |
+
print("Production Mode - Real AI Translation enabled")
|
| 772 |
+
print("Translation Model: GPT-4o-mini")
|
| 773 |
+
print("Speech Recognition: OpenAI Whisper-1")
|
| 774 |
+
else:
|
| 775 |
+
print("Demo Mode - Configure OPENAI_API_KEY for full functionality")
|
| 776 |
+
|
| 777 |
+
# Use environment port or default (7901 for testing)
|
| 778 |
+
port = int(os.environ.get("GRADIO_SERVER_PORT", 7901))
|
| 779 |
+
demo.launch(
|
| 780 |
+
server_name="0.0.0.0",
|
| 781 |
+
server_port=port,
|
| 782 |
+
share=False,
|
| 783 |
+
show_error=True
|
| 784 |
+
)
|