Spaces:
Build error
Build error
File size: 20,258 Bytes
8a0c4b0 |
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 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 |
"""Audio Processing Application Service for pipeline orchestration."""
import logging
import os
import tempfile
import time
import uuid
from pathlib import Path
from typing import Optional, Dict, Any
from contextlib import contextmanager
from ..dtos.audio_upload_dto import AudioUploadDto
from ..dtos.processing_request_dto import ProcessingRequestDto
from ..dtos.processing_result_dto import ProcessingResultDto
from ...domain.interfaces.speech_recognition import ISpeechRecognitionService
from ...domain.interfaces.translation import ITranslationService
from ...domain.interfaces.speech_synthesis import ISpeechSynthesisService
from ...domain.models.audio_content import AudioContent
from ...domain.models.text_content import TextContent
from ...domain.models.translation_request import TranslationRequest
from ...domain.models.speech_synthesis_request import SpeechSynthesisRequest
from ...domain.models.voice_settings import VoiceSettings
from ...domain.exceptions import (
DomainException,
AudioProcessingException,
SpeechRecognitionException,
TranslationFailedException,
SpeechSynthesisException
)
from ...infrastructure.config.app_config import AppConfig
from ...infrastructure.config.dependency_container import DependencyContainer
logger = logging.getLogger(__name__)
class AudioProcessingApplicationService:
"""Application service for orchestrating the complete audio processing pipeline."""
def __init__(
self,
container: DependencyContainer,
config: Optional[AppConfig] = None
):
"""
Initialize the audio processing application service.
Args:
container: Dependency injection container
config: Application configuration (optional, will be resolved from container)
"""
self._container = container
self._config = config or container.resolve(AppConfig)
self._temp_files: Dict[str, str] = {} # Track temporary files for cleanup
# Setup logging
self._setup_logging()
logger.info("AudioProcessingApplicationService initialized")
def _setup_logging(self) -> None:
"""Setup logging configuration."""
try:
log_config = self._config.get_logging_config()
# Configure logger level
logger.setLevel(getattr(logging, log_config['level'].upper(), logging.INFO))
# Add file handler if enabled
if log_config.get('enable_file_logging', False):
file_handler = logging.FileHandler(log_config['log_file_path'])
file_handler.setLevel(logger.level)
formatter = logging.Formatter(log_config['format'])
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
except Exception as e:
logger.warning(f"Failed to setup logging configuration: {e}")
def process_audio_pipeline(self, request: ProcessingRequestDto) -> ProcessingResultDto:
"""
Process audio through the complete pipeline: STT -> Translation -> TTS.
Args:
request: Processing request containing audio and parameters
Returns:
ProcessingResultDto: Result of the complete processing pipeline
"""
correlation_id = str(uuid.uuid4())
start_time = time.time()
logger.info(f"Starting audio processing pipeline [correlation_id={correlation_id}]")
try:
# Validate request
self._validate_request(request)
# Create temporary working directory
with self._create_temp_directory(correlation_id) as temp_dir:
# Step 1: Convert uploaded audio to domain model
audio_content = self._convert_upload_to_audio_content(request.audio, temp_dir)
# Step 2: Speech-to-Text
original_text = self._perform_speech_recognition(
audio_content,
request.asr_model,
correlation_id
)
# Step 3: Translation (if needed)
translated_text = self._perform_translation(
original_text,
request.source_language,
request.target_language,
correlation_id
) if request.requires_translation else original_text
# Step 4: Text-to-Speech
output_audio_path = self._perform_speech_synthesis(
translated_text,
request.voice,
request.speed,
request.target_language,
temp_dir,
correlation_id
)
# Calculate processing time
processing_time = time.time() - start_time
# Create successful result
result = ProcessingResultDto.success_result(
original_text=original_text.text,
translated_text=translated_text.text if translated_text != original_text else None,
audio_path=output_audio_path,
processing_time=processing_time,
metadata={
'correlation_id': correlation_id,
'asr_model': request.asr_model,
'target_language': request.target_language,
'voice': request.voice,
'speed': request.speed,
'translation_required': request.requires_translation
}
)
logger.info(
f"Audio processing pipeline completed successfully "
f"[correlation_id={correlation_id}, processing_time={processing_time:.2f}s]"
)
return result
except DomainException as e:
processing_time = time.time() - start_time
error_code = self._get_error_code_from_exception(e)
logger.error(
f"Domain error in audio processing pipeline: {e} "
f"[correlation_id={correlation_id}, processing_time={processing_time:.2f}s]"
)
return ProcessingResultDto.error_result(
error_message=str(e),
error_code=error_code,
processing_time=processing_time,
metadata={'correlation_id': correlation_id}
)
except Exception as e:
processing_time = time.time() - start_time
logger.error(
f"Unexpected error in audio processing pipeline: {e} "
f"[correlation_id={correlation_id}, processing_time={processing_time:.2f}s]",
exc_info=True
)
return ProcessingResultDto.error_result(
error_message=f"System error: {str(e)}",
error_code='SYSTEM_ERROR',
processing_time=processing_time,
metadata={'correlation_id': correlation_id}
)
finally:
# Cleanup temporary files
self._cleanup_temp_files()
def _validate_request(self, request: ProcessingRequestDto) -> None:
"""
Validate processing request.
Args:
request: Processing request to validate
Raises:
ValueError: If request is invalid
"""
if not isinstance(request, ProcessingRequestDto):
raise ValueError("Request must be a ProcessingRequestDto instance")
# Additional validation beyond DTO validation
processing_config = self._config.get_processing_config()
# Check file size limits
max_size_bytes = processing_config['max_file_size_mb'] * 1024 * 1024
if request.audio.size > max_size_bytes:
raise ValueError(
f"Audio file too large: {request.audio.size} bytes. "
f"Maximum allowed: {max_size_bytes} bytes"
)
# Check supported audio formats
supported_formats = processing_config['supported_audio_formats']
file_ext = request.audio.file_extension.lstrip('.')
if file_ext not in supported_formats:
raise ValueError(
f"Unsupported audio format: {file_ext}. "
f"Supported formats: {supported_formats}"
)
@contextmanager
def _create_temp_directory(self, correlation_id: str):
"""
Create temporary directory for processing.
Args:
correlation_id: Correlation ID for tracking
Yields:
str: Path to temporary directory
"""
processing_config = self._config.get_processing_config()
base_temp_dir = processing_config['temp_dir']
# Create unique temp directory
temp_dir = os.path.join(base_temp_dir, f"processing_{correlation_id}")
try:
os.makedirs(temp_dir, exist_ok=True)
logger.debug(f"Created temporary directory: {temp_dir}")
yield temp_dir
finally:
# Cleanup temp directory if configured
if processing_config.get('cleanup_temp_files', True):
try:
import shutil
shutil.rmtree(temp_dir, ignore_errors=True)
logger.debug(f"Cleaned up temporary directory: {temp_dir}")
except Exception as e:
logger.warning(f"Failed to cleanup temp directory {temp_dir}: {e}")
def _convert_upload_to_audio_content(
self,
upload: AudioUploadDto,
temp_dir: str
) -> AudioContent:
"""
Convert uploaded audio to domain AudioContent.
Args:
upload: Audio upload DTO
temp_dir: Temporary directory for file operations
Returns:
AudioContent: Domain audio content model
Raises:
AudioProcessingException: If conversion fails
"""
try:
# Save uploaded content to temporary file
temp_file_path = os.path.join(temp_dir, f"input_{upload.filename}")
with open(temp_file_path, 'wb') as f:
f.write(upload.content)
# Track temp file for cleanup
self._temp_files[temp_file_path] = temp_file_path
# Determine audio format from file extension
audio_format = upload.file_extension.lstrip('.').lower()
# Create AudioContent (simplified - in real implementation would extract metadata)
audio_content = AudioContent(
data=upload.content,
format=audio_format,
sample_rate=16000, # Default, would be extracted from actual file
duration=0.0 # Would be calculated from actual file
)
logger.debug(f"Converted upload to AudioContent: {upload.filename}")
return audio_content
except Exception as e:
logger.error(f"Failed to convert upload to AudioContent: {e}")
raise AudioProcessingException(f"Failed to process uploaded audio: {str(e)}")
def _perform_speech_recognition(
self,
audio: AudioContent,
model: str,
correlation_id: str
) -> TextContent:
"""
Perform speech-to-text recognition.
Args:
audio: Audio content to transcribe
model: STT model to use
correlation_id: Correlation ID for tracking
Returns:
TextContent: Transcribed text
Raises:
SpeechRecognitionException: If STT fails
"""
try:
logger.debug(f"Starting STT with model: {model} [correlation_id={correlation_id}]")
# Get STT provider from container
stt_provider = self._container.get_stt_provider(model)
# Perform transcription
text_content = stt_provider.transcribe(audio, model)
logger.info(
f"STT completed successfully [correlation_id={correlation_id}, "
f"text_length={len(text_content.text)}]"
)
return text_content
except Exception as e:
logger.error(f"STT failed: {e} [correlation_id={correlation_id}]")
raise SpeechRecognitionException(f"Speech recognition failed: {str(e)}")
def _perform_translation(
self,
text: TextContent,
source_language: Optional[str],
target_language: str,
correlation_id: str
) -> TextContent:
"""
Perform text translation.
Args:
text: Text to translate
source_language: Source language (optional, auto-detect if None)
target_language: Target language
correlation_id: Correlation ID for tracking
Returns:
TextContent: Translated text
Raises:
TranslationFailedException: If translation fails
"""
try:
logger.debug(
f"Starting translation: {source_language or 'auto'} -> {target_language} "
f"[correlation_id={correlation_id}]"
)
# Get translation provider from container
translation_provider = self._container.get_translation_provider()
# Create translation request
translation_request = TranslationRequest(
text=text.text,
source_language=source_language or 'auto',
target_language=target_language
)
# Perform translation
translated_text = translation_provider.translate(translation_request)
logger.info(
f"Translation completed successfully [correlation_id={correlation_id}, "
f"source_length={len(text.text)}, target_length={len(translated_text.text)}]"
)
return translated_text
except Exception as e:
logger.error(f"Translation failed: {e} [correlation_id={correlation_id}]")
raise TranslationFailedException(f"Translation failed: {str(e)}")
def _perform_speech_synthesis(
self,
text: TextContent,
voice: str,
speed: float,
language: str,
temp_dir: str,
correlation_id: str
) -> str:
"""
Perform text-to-speech synthesis.
Args:
text: Text to synthesize
voice: Voice to use
speed: Speech speed
language: Target language
temp_dir: Temporary directory for output
correlation_id: Correlation ID for tracking
Returns:
str: Path to generated audio file
Raises:
SpeechSynthesisException: If TTS fails
"""
try:
logger.debug(
f"Starting TTS with voice: {voice}, speed: {speed} "
f"[correlation_id={correlation_id}]"
)
# Get TTS provider from container
tts_provider = self._container.get_tts_provider(voice)
# Create voice settings
voice_settings = VoiceSettings(
voice_id=voice,
speed=speed,
language=language
)
# Create synthesis request
synthesis_request = SpeechSynthesisRequest(
text=text.text,
voice_settings=voice_settings
)
# Perform synthesis
audio_content = tts_provider.synthesize(synthesis_request)
# Save output to file
output_filename = f"output_{correlation_id}.{audio_content.format}"
output_path = os.path.join(temp_dir, output_filename)
with open(output_path, 'wb') as f:
f.write(audio_content.data)
# Track temp file for cleanup
self._temp_files[output_path] = output_path
logger.info(
f"TTS completed successfully [correlation_id={correlation_id}, "
f"output_file={output_path}]"
)
return output_path
except Exception as e:
logger.error(f"TTS failed: {e} [correlation_id={correlation_id}]")
raise SpeechSynthesisException(f"Speech synthesis failed: {str(e)}")
def _get_error_code_from_exception(self, exception: Exception) -> str:
"""
Get error code from exception type.
Args:
exception: Exception instance
Returns:
str: Error code
"""
if isinstance(exception, SpeechRecognitionException):
return 'STT_ERROR'
elif isinstance(exception, TranslationFailedException):
return 'TRANSLATION_ERROR'
elif isinstance(exception, SpeechSynthesisException):
return 'TTS_ERROR'
elif isinstance(exception, ValueError):
return 'VALIDATION_ERROR'
else:
return 'SYSTEM_ERROR'
def _cleanup_temp_files(self) -> None:
"""Cleanup tracked temporary files."""
for file_path in list(self._temp_files.keys()):
try:
if os.path.exists(file_path):
os.remove(file_path)
logger.debug(f"Cleaned up temp file: {file_path}")
except Exception as e:
logger.warning(f"Failed to cleanup temp file {file_path}: {e}")
finally:
# Remove from tracking regardless of success
self._temp_files.pop(file_path, None)
def get_processing_status(self, correlation_id: str) -> Dict[str, Any]:
"""
Get processing status for a correlation ID.
Args:
correlation_id: Correlation ID to check
Returns:
Dict[str, Any]: Processing status information
"""
# This would be implemented with actual status tracking
# For now, return basic info
return {
'correlation_id': correlation_id,
'status': 'unknown',
'message': 'Status tracking not implemented'
}
def get_supported_configurations(self) -> Dict[str, Any]:
"""
Get supported configurations for the processing pipeline.
Returns:
Dict[str, Any]: Supported configurations
"""
return {
'asr_models': ['whisper-small', 'whisper-medium', 'whisper-large', 'parakeet'],
'voices': ['kokoro', 'dia', 'cosyvoice2', 'dummy'],
'languages': [
'en', 'es', 'fr', 'de', 'it', 'pt', 'ru', 'ja', 'ko', 'zh',
'ar', 'hi', 'tr', 'pl', 'nl', 'sv', 'da', 'no', 'fi'
],
'audio_formats': self._config.get_processing_config()['supported_audio_formats'],
'max_file_size_mb': self._config.get_processing_config()['max_file_size_mb'],
'speed_range': {'min': 0.5, 'max': 2.0}
}
def cleanup(self) -> None:
"""Cleanup application service resources."""
logger.info("Cleaning up AudioProcessingApplicationService")
# Cleanup temporary files
self._cleanup_temp_files()
logger.info("AudioProcessingApplicationService cleanup completed")
def __enter__(self):
"""Context manager entry."""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""Context manager exit with cleanup."""
self.cleanup() |