Spaces:
Runtime error
Runtime error
Michael Hu commited on
Commit ·
6613cd9
1
Parent(s): f7492cb
Implement comprehensive error handling
Browse filesFiles changed (9)
- src/application/error_handling/__init__.pyAdded+1
- src/application/error_handling/error_mapper.pyAdded+375
- src/application/error_handling/recovery_manager.pyAdded+508
- src/application/error_handling/structured_logger.pyAdded+362
- src/application/services/audio_processing_service.py+365-95
- src/application/services/configuration_service.py+72-67
- tests/unit/application/error_handling/__init__.pyAdded+1
- tests/unit/application/error_handling/test_error_mapper.pyAdded+155
- tests/unit/application/error_handling/test_structured_logger.pyAdded+298
1"""Error handling utilities for the application layer."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375"""Error message mapping for user-friendly error handling."""
import loggingfrom typing import Dict, Optional, Anyfrom enum import Enum
from ...domain.exceptions import ( DomainException, InvalidAudioFormatException, InvalidTextContentException, TranslationFailedException, SpeechRecognitionException, SpeechSynthesisException, InvalidVoiceSettingsException, AudioProcessingException)
logger = logging.getLogger(__name__)
class ErrorSeverity(Enum): """Error severity levels.""" LOW = "low" MEDIUM = "medium" HIGH = "high" CRITICAL = "critical"
class ErrorCategory(Enum): """Error categories for classification.""" VALIDATION = "validation" PROCESSING = "processing" SYSTEM = "system" EXTERNAL = "external" CONFIGURATION = "configuration"
class ErrorMapping: """Error mapping configuration."""
def __init__(self, user_message: str, error_code: str, severity: ErrorSeverity, category: ErrorCategory, recovery_suggestions: Optional[list] = None, technical_details: Optional[str] = None): self.user_message = user_message self.error_code = error_code self.severity = severity self.category = category self.recovery_suggestions = recovery_suggestions or [] self.technical_details = technical_details
class ErrorMapper: """Maps domain exceptions to user-friendly error messages."""
def __init__(self): """Initialize error mapper with predefined mappings.""" self._mappings: Dict[type, ErrorMapping] = { # Audio format errors InvalidAudioFormatException: ErrorMapping( user_message="The uploaded audio file format is not supported. Please use WAV, MP3, FLAC, or OGG format.", error_code="INVALID_AUDIO_FORMAT", severity=ErrorSeverity.MEDIUM, category=ErrorCategory.VALIDATION, recovery_suggestions=[ "Convert your audio file to a supported format (WAV, MP3, FLAC, or OGG)", "Check that your file is not corrupted", "Ensure the file has a proper audio extension" ] ),
# Text content errors InvalidTextContentException: ErrorMapping( user_message="The text content is invalid or too long. Please check your input.", error_code="INVALID_TEXT_CONTENT", severity=ErrorSeverity.MEDIUM, category=ErrorCategory.VALIDATION, recovery_suggestions=[ "Ensure text is not empty", "Check that text length is within limits (max 10,000 characters)", "Verify text encoding is valid" ] ),
# Translation errors TranslationFailedException: ErrorMapping( user_message="Translation failed. This might be due to unsupported language pairs or service issues.", error_code="TRANSLATION_FAILED", severity=ErrorSeverity.HIGH, category=ErrorCategory.PROCESSING, recovery_suggestions=[ "Try a different target language", "Check if the source language is correctly detected", "Retry the operation after a few moments", "Ensure the text is in a supported language" ] ),
# Speech recognition errors SpeechRecognitionException: ErrorMapping( user_message="Speech recognition failed. The audio might be unclear or in an unsupported language.", error_code="SPEECH_RECOGNITION_FAILED", severity=ErrorSeverity.HIGH, category=ErrorCategory.PROCESSING, recovery_suggestions=[ "Ensure audio quality is good (clear speech, minimal background noise)", "Try a different speech recognition model", "Check that the audio contains speech in a supported language", "Verify audio file is not corrupted" ] ),
# Speech synthesis errors SpeechSynthesisException: ErrorMapping( user_message="Text-to-speech generation failed. This might be due to voice availability or text issues.", error_code="SPEECH_SYNTHESIS_FAILED", severity=ErrorSeverity.HIGH, category=ErrorCategory.PROCESSING, recovery_suggestions=[ "Try a different voice", "Check if the text contains unsupported characters", "Reduce text length if it's very long", "Retry with a different TTS provider" ] ),
# Voice settings errors InvalidVoiceSettingsException: ErrorMapping( user_message="Voice settings are invalid. Please check speed, voice selection, and language settings.", error_code="INVALID_VOICE_SETTINGS", severity=ErrorSeverity.MEDIUM, category=ErrorCategory.VALIDATION, recovery_suggestions=[ "Ensure speed is between 0.5 and 2.0", "Select a valid voice from the available options", "Check that the language is supported", "Verify voice is available for the selected language" ] ),
# General audio processing errors AudioProcessingException: ErrorMapping( user_message="Audio processing failed. There was an issue processing your audio file.", error_code="AUDIO_PROCESSING_FAILED", severity=ErrorSeverity.HIGH, category=ErrorCategory.PROCESSING, recovery_suggestions=[ "Check that your audio file is valid and not corrupted", "Try uploading a different audio file", "Ensure file size is within limits", "Retry the operation" ] ),
# Validation errors ValueError: ErrorMapping( user_message="Invalid input provided. Please check your request parameters.", error_code="VALIDATION_ERROR", severity=ErrorSeverity.MEDIUM, category=ErrorCategory.VALIDATION, recovery_suggestions=[ "Check all required fields are provided", "Verify parameter values are within valid ranges", "Ensure file formats are supported" ] ),
# File size errors PermissionError: ErrorMapping( user_message="Permission denied. Unable to access required files or directories.", error_code="PERMISSION_ERROR", severity=ErrorSeverity.HIGH, category=ErrorCategory.SYSTEM, recovery_suggestions=[ "Check file permissions", "Ensure temporary directory is writable", "Contact system administrator if issue persists" ] ),
# Memory errors MemoryError: ErrorMapping( user_message="Insufficient memory to process the request. Try with a smaller file.", error_code="MEMORY_ERROR", severity=ErrorSeverity.HIGH, category=ErrorCategory.SYSTEM, recovery_suggestions=[ "Use a smaller audio file", "Try processing shorter audio segments", "Retry the operation later" ] ),
# Timeout errors TimeoutError: ErrorMapping( user_message="Processing timed out. The operation took too long to complete.", error_code="TIMEOUT_ERROR", severity=ErrorSeverity.HIGH, category=ErrorCategory.SYSTEM, recovery_suggestions=[ "Try with a shorter audio file", "Retry the operation", "Check system load and try again later" ] ) }
# Default mapping for unknown errors self._default_mapping = ErrorMapping( user_message="An unexpected error occurred. Please try again or contact support.", error_code="UNKNOWN_ERROR", severity=ErrorSeverity.CRITICAL, category=ErrorCategory.SYSTEM, recovery_suggestions=[ "Retry the operation", "Check your input parameters", "Contact support if the issue persists" ] )
def map_exception(self, exception: Exception, context: Optional[Dict[str, Any]] = None) -> ErrorMapping: """ Map an exception to user-friendly error information.
Args: exception: The exception to map context: Optional context information
Returns: ErrorMapping: Mapped error information """ try: # Get mapping for exception type mapping = self._mappings.get(type(exception))
if mapping is None: # Try parent classes for domain exceptions for exc_type in type(exception).__mro__: if exc_type in self._mappings: mapping = self._mappings[exc_type] break
if mapping is None: # Use default mapping mapping = self._default_mapping logger.warning(f"No mapping found for exception type: {type(exception).__name__}")
# Add context-specific information if available if context: mapping = self._enhance_mapping_with_context(mapping, exception, context)
logger.debug(f"Mapped {type(exception).__name__} to {mapping.error_code}") return mapping
except Exception as e: logger.error(f"Error mapping exception {type(exception).__name__}: {e}") return self._default_mapping
def _enhance_mapping_with_context(self, mapping: ErrorMapping, exception: Exception, context: Dict[str, Any]) -> ErrorMapping: """ Enhance error mapping with context-specific information.
Args: mapping: Base error mapping exception: Original exception context: Context information
Returns: ErrorMapping: Enhanced error mapping """ try: # Create a copy of the mapping to avoid modifying the original enhanced_mapping = ErrorMapping( user_message=mapping.user_message, error_code=mapping.error_code, severity=mapping.severity, category=mapping.category, recovery_suggestions=mapping.recovery_suggestions.copy(), technical_details=mapping.technical_details )
# Add context-specific enhancements if 'file_name' in context: enhanced_mapping.user_message += f" (File: {context['file_name']})"
if 'operation' in context: enhanced_mapping.technical_details = f"Failed during {context['operation']}: {str(exception)}"
if 'correlation_id' in context: enhanced_mapping.technical_details = ( f"{enhanced_mapping.technical_details or str(exception)} " f"[ID: {context['correlation_id']}]" )
# Add provider-specific suggestions if 'provider' in context: provider = context['provider'] if isinstance(exception, (SpeechRecognitionException, SpeechSynthesisException, TranslationFailedException)): enhanced_mapping.recovery_suggestions.append(f"Try switching from {provider} to an alternative provider")
# Add file size specific suggestions if 'file_size' in context and context['file_size'] > 50 * 1024 * 1024: # 50MB enhanced_mapping.recovery_suggestions.insert(0, "Try with a smaller file (under 50MB)")
return enhanced_mapping
except Exception as e: logger.error(f"Error enhancing mapping with context: {e}") return mapping
def get_error_code_from_exception(self, exception: Exception) -> str: """ Get error code from exception.
Args: exception: Exception to get code for
Returns: str: Error code """ mapping = self.map_exception(exception) return mapping.error_code
def get_user_message_from_exception(self, exception: Exception, context: Optional[Dict[str, Any]] = None) -> str: """ Get user-friendly message from exception.
Args: exception: Exception to get message for context: Optional context information
Returns: str: User-friendly error message """ mapping = self.map_exception(exception, context) return mapping.user_message
def get_recovery_suggestions(self, exception: Exception, context: Optional[Dict[str, Any]] = None) -> list: """ Get recovery suggestions for an exception.
Args: exception: Exception to get suggestions for context: Optional context information
Returns: list: List of recovery suggestions """ mapping = self.map_exception(exception, context) return mapping.recovery_suggestions
def add_custom_mapping(self, exception_type: type, mapping: ErrorMapping) -> None: """ Add a custom error mapping.
Args: exception_type: Exception type to map mapping: Error mapping configuration """ self._mappings[exception_type] = mapping logger.info(f"Added custom mapping for {exception_type.__name__}")
def get_all_error_codes(self) -> list: """ Get all available error codes.
Returns: list: List of all error codes """ codes = [mapping.error_code for mapping in self._mappings.values()] codes.append(self._default_mapping.error_code) return list(set(codes))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508"""Error recovery and fallback mechanisms."""
import loggingimport timefrom typing import Dict, List, Optional, Any, Callable, TypeVar, Unionfrom dataclasses import dataclassfrom enum import Enumfrom functools import wraps
from .structured_logger import StructuredLogger, LogContext, get_structured_loggerfrom ...domain.exceptions import ( DomainException, SpeechRecognitionException, TranslationFailedException, SpeechSynthesisException, AudioProcessingException)
logger = get_structured_logger(__name__)
T = TypeVar('T')
class RecoveryStrategy(Enum): """Recovery strategy types.""" RETRY = "retry" FALLBACK = "fallback" CIRCUIT_BREAKER = "circuit_breaker" GRACEFUL_DEGRADATION = "graceful_degradation"
class CircuitBreakerState(Enum): """Circuit breaker states.""" CLOSED = "closed" OPEN = "open" HALF_OPEN = "half_open"
@dataclassclass RetryConfig: """Retry configuration.""" max_attempts: int = 3 base_delay: float = 1.0 max_delay: float = 60.0 exponential_backoff: bool = True jitter: bool = True retryable_exceptions: Optional[List[type]] = None
@dataclassclass CircuitBreakerConfig: """Circuit breaker configuration.""" failure_threshold: int = 5 recovery_timeout: float = 60.0 success_threshold: int = 2 timeout: float = 30.0
@dataclassclass FallbackConfig: """Fallback configuration.""" fallback_providers: List[str] fallback_function: Optional[Callable] = None enable_graceful_degradation: bool = True
class CircuitBreaker: """Circuit breaker implementation."""
def __init__(self, config: CircuitBreakerConfig, name: str = "default"): """ Initialize circuit breaker.
Args: config: Circuit breaker configuration name: Circuit breaker name """ self.config = config self.name = name self.state = CircuitBreakerState.CLOSED self.failure_count = 0 self.success_count = 0 self.last_failure_time = 0.0 self.logger = get_structured_logger(f"{__name__}.CircuitBreaker.{name}")
def call(self, func: Callable[..., T], *args, **kwargs) -> T: """ Call function through circuit breaker.
Args: func: Function to call *args: Function arguments **kwargs: Function keyword arguments
Returns: T: Function result
Raises: Exception: If circuit is open or function fails """ context = LogContext( correlation_id=kwargs.get('correlation_id', 'unknown'), component=f"circuit_breaker_{self.name}", operation=func.__name__ )
if self.state == CircuitBreakerState.OPEN: if time.time() - self.last_failure_time < self.config.recovery_timeout: self.logger.warning( f"Circuit breaker {self.name} is OPEN, rejecting call", context=context ) raise AudioProcessingException(f"Circuit breaker {self.name} is open") else: self.state = CircuitBreakerState.HALF_OPEN self.success_count = 0 self.logger.info( f"Circuit breaker {self.name} transitioning to HALF_OPEN", context=context )
try: result = func(*args, **kwargs) self._on_success(context) return result
except Exception as e: self._on_failure(e, context) raise
def _on_success(self, context: LogContext) -> None: """Handle successful call.""" if self.state == CircuitBreakerState.HALF_OPEN: self.success_count += 1 if self.success_count >= self.config.success_threshold: self.state = CircuitBreakerState.CLOSED self.failure_count = 0 self.logger.info( f"Circuit breaker {self.name} transitioning to CLOSED", context=context ) elif self.state == CircuitBreakerState.CLOSED: self.failure_count = 0
def _on_failure(self, exception: Exception, context: LogContext) -> None: """Handle failed call.""" self.failure_count += 1 self.last_failure_time = time.time()
if self.state == CircuitBreakerState.HALF_OPEN: self.state = CircuitBreakerState.OPEN self.logger.warning( f"Circuit breaker {self.name} transitioning to OPEN after failure in HALF_OPEN", context=context, exception=exception ) elif (self.state == CircuitBreakerState.CLOSED and self.failure_count >= self.config.failure_threshold): self.state = CircuitBreakerState.OPEN self.logger.warning( f"Circuit breaker {self.name} transitioning to OPEN after {self.failure_count} failures", context=context, exception=exception )
class RecoveryManager: """Manages error recovery and fallback mechanisms."""
def __init__(self): """Initialize recovery manager.""" self.circuit_breakers: Dict[str, CircuitBreaker] = {} self.logger = get_structured_logger(__name__)
# Default retry configurations for different exception types self.default_retry_configs = { SpeechRecognitionException: RetryConfig( max_attempts=2, base_delay=2.0, retryable_exceptions=[SpeechRecognitionException] ), TranslationFailedException: RetryConfig( max_attempts=3, base_delay=1.0, retryable_exceptions=[TranslationFailedException] ), SpeechSynthesisException: RetryConfig( max_attempts=2, base_delay=1.5, retryable_exceptions=[SpeechSynthesisException] ), ConnectionError: RetryConfig( max_attempts=3, base_delay=2.0, exponential_backoff=True, retryable_exceptions=[ConnectionError, TimeoutError] ) }
def get_circuit_breaker(self, name: str, config: Optional[CircuitBreakerConfig] = None) -> CircuitBreaker: """ Get or create circuit breaker.
Args: name: Circuit breaker name config: Optional configuration
Returns: CircuitBreaker: Circuit breaker instance """ if name not in self.circuit_breakers: if config is None: config = CircuitBreakerConfig() self.circuit_breakers[name] = CircuitBreaker(config, name)
return self.circuit_breakers[name]
def retry_with_backoff(self, func: Callable[..., T], config: Optional[RetryConfig] = None, correlation_id: Optional[str] = None, *args, **kwargs) -> T: """ Execute function with retry and exponential backoff.
Args: func: Function to execute config: Retry configuration correlation_id: Correlation ID for logging *args: Function arguments **kwargs: Function keyword arguments
Returns: T: Function result
Raises: Exception: If all retry attempts fail """ if config is None: config = RetryConfig()
context = LogContext( correlation_id=correlation_id or 'unknown', component='retry_manager', operation=func.__name__ )
last_exception = None
for attempt in range(config.max_attempts): try: if attempt > 0: delay = self._calculate_delay(attempt, config) self.logger.info( f"Retrying {func.__name__} (attempt {attempt + 1}/{config.max_attempts}) after {delay:.2f}s delay", context=context ) time.sleep(delay)
result = func(*args, **kwargs)
if attempt > 0: self.logger.info( f"Retry successful for {func.__name__} on attempt {attempt + 1}", context=context )
return result
except Exception as e: last_exception = e
# Check if exception is retryable if not self._is_retryable_exception(e, config): self.logger.error( f"Non-retryable exception in {func.__name__}: {type(e).__name__}", context=context, exception=e ) raise
self.logger.warning( f"Attempt {attempt + 1}/{config.max_attempts} failed for {func.__name__}: {e}", context=context, exception=e )
# All attempts failed self.logger.error( f"All {config.max_attempts} retry attempts failed for {func.__name__}", context=context, exception=last_exception ) raise last_exception
def execute_with_fallback(self, primary_func: Callable[..., T], fallback_funcs: List[Callable[..., T]], correlation_id: Optional[str] = None, *args, **kwargs) -> T: """ Execute function with fallback options.
Args: primary_func: Primary function to execute fallback_funcs: List of fallback functions correlation_id: Correlation ID for logging *args: Function arguments **kwargs: Function keyword arguments
Returns: T: Function result
Raises: Exception: If all functions fail """ context = LogContext( correlation_id=correlation_id or 'unknown', component='fallback_manager', operation=primary_func.__name__ )
# Try primary function first try: result = primary_func(*args, **kwargs) return result
except Exception as e: self.logger.warning( f"Primary function {primary_func.__name__} failed, trying fallbacks", context=context, exception=e )
last_exception = e
# Try fallback functions for i, fallback_func in enumerate(fallback_funcs): try: self.logger.info( f"Trying fallback {i + 1}/{len(fallback_funcs)}: {fallback_func.__name__}", context=context )
result = fallback_func(*args, **kwargs)
self.logger.info( f"Fallback {fallback_func.__name__} succeeded", context=context )
return result
except Exception as fallback_e: last_exception = fallback_e self.logger.warning( f"Fallback {fallback_func.__name__} failed: {fallback_e}", context=context, exception=fallback_e )
# All functions failed self.logger.error( f"All functions failed (primary + {len(fallback_funcs)} fallbacks)", context=context, exception=last_exception ) raise last_exception
def execute_with_circuit_breaker(self, func: Callable[..., T], circuit_breaker_name: str, config: Optional[CircuitBreakerConfig] = None, correlation_id: Optional[str] = None, *args, **kwargs) -> T: """ Execute function with circuit breaker protection.
Args: func: Function to execute circuit_breaker_name: Circuit breaker name config: Optional circuit breaker configuration correlation_id: Correlation ID for logging *args: Function arguments **kwargs: Function keyword arguments
Returns: T: Function result
Raises: Exception: If circuit is open or function fails """ circuit_breaker = self.get_circuit_breaker(circuit_breaker_name, config)
# Add correlation ID to kwargs for circuit breaker logging if correlation_id: kwargs['correlation_id'] = correlation_id
return circuit_breaker.call(func, *args, **kwargs)
def _calculate_delay(self, attempt: int, config: RetryConfig) -> float: """ Calculate retry delay with exponential backoff and jitter.
Args: attempt: Attempt number (0-based) config: Retry configuration
Returns: float: Delay in seconds """ if config.exponential_backoff: delay = config.base_delay * (2 ** attempt) else: delay = config.base_delay
# Apply maximum delay limit delay = min(delay, config.max_delay)
# Add jitter to prevent thundering herd if config.jitter: import random delay *= (0.5 + random.random() * 0.5)
return delay
def _is_retryable_exception(self, exception: Exception, config: RetryConfig) -> bool: """ Check if exception is retryable.
Args: exception: Exception to check config: Retry configuration
Returns: bool: True if exception is retryable """ if config.retryable_exceptions is None: # Default retryable exceptions retryable_types = ( ConnectionError, TimeoutError, SpeechRecognitionException, TranslationFailedException, SpeechSynthesisException ) return isinstance(exception, retryable_types)
return any(isinstance(exception, exc_type) for exc_type in config.retryable_exceptions)
def get_retry_config_for_exception(self, exception: Exception) -> RetryConfig: """ Get appropriate retry configuration for exception type.
Args: exception: Exception to get config for
Returns: RetryConfig: Retry configuration """ for exc_type, config in self.default_retry_configs.items(): if isinstance(exception, exc_type): return config
# Return default config return RetryConfig()
def with_retry(config: Optional[RetryConfig] = None): """ Decorator for automatic retry with backoff.
Args: config: Optional retry configuration
Returns: Decorated function """ def decorator(func: Callable[..., T]) -> Callable[..., T]: @wraps(func) def wrapper(*args, **kwargs) -> T: recovery_manager = RecoveryManager() correlation_id = kwargs.get('correlation_id') return recovery_manager.retry_with_backoff( func, config, correlation_id, *args, **kwargs ) return wrapper return decorator
def with_circuit_breaker(name: str, config: Optional[CircuitBreakerConfig] = None): """ Decorator for circuit breaker protection.
Args: name: Circuit breaker name config: Optional circuit breaker configuration
Returns: Decorated function """ def decorator(func: Callable[..., T]) -> Callable[..., T]: @wraps(func) def wrapper(*args, **kwargs) -> T: recovery_manager = RecoveryManager() correlation_id = kwargs.get('correlation_id') return recovery_manager.execute_with_circuit_breaker( func, name, config, correlation_id, *args, **kwargs ) return wrapper return decorator123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362"""Structured logging with correlation IDs and context management."""
import loggingimport jsonimport uuidimport timefrom typing import Dict, Any, Optional, Unionfrom datetime import datetimefrom contextvars import ContextVarfrom dataclasses import dataclass, asdictfrom enum import Enum
# Context variable for correlation IDcorrelation_id_context: ContextVar[Optional[str]] = ContextVar('correlation_id', default=None)
class LogLevel(Enum): """Log levels.""" DEBUG = "DEBUG" INFO = "INFO" WARNING = "WARNING" ERROR = "ERROR" CRITICAL = "CRITICAL"
@dataclassclass LogContext: """Structured log context.""" correlation_id: str operation: Optional[str] = None component: Optional[str] = None user_id: Optional[str] = None session_id: Optional[str] = None request_id: Optional[str] = None metadata: Optional[Dict[str, Any]] = None
def to_dict(self) -> Dict[str, Any]: """Convert to dictionary.""" return {k: v for k, v in asdict(self).items() if v is not None}
class StructuredLogger: """Structured logger with correlation ID support."""
def __init__(self, name: str, enable_json_logging: bool = True): """ Initialize structured logger.
Args: name: Logger name enable_json_logging: Whether to use JSON format """ self.logger = logging.getLogger(name) self.enable_json_logging = enable_json_logging self._setup_formatter()
def _setup_formatter(self) -> None: """Setup log formatter.""" if self.enable_json_logging: formatter = JsonFormatter() else: formatter = ContextFormatter()
# Apply formatter to all handlers for handler in self.logger.handlers: handler.setFormatter(formatter)
def _get_log_data(self, message: str, level: str, context: Optional[LogContext] = None, extra: Optional[Dict[str, Any]] = None, exception: Optional[Exception] = None) -> Dict[str, Any]: """ Prepare log data structure.
Args: message: Log message level: Log level context: Log context extra: Extra data exception: Exception if any
Returns: Dict[str, Any]: Structured log data """ # Get correlation ID from context or generate new one correlation_id = correlation_id_context.get() if not correlation_id and context: correlation_id = context.correlation_id if not correlation_id: correlation_id = str(uuid.uuid4())
log_data = { 'timestamp': datetime.utcnow().isoformat() + 'Z', 'level': level, 'message': message, 'correlation_id': correlation_id, 'logger_name': self.logger.name }
# Add context information if context: log_data.update(context.to_dict())
# Add extra data if extra: log_data['extra'] = extra
# Add exception information if exception: log_data['exception'] = { 'type': type(exception).__name__, 'message': str(exception), 'module': getattr(exception, '__module__', None) }
# Add stack trace for debugging import traceback log_data['exception']['traceback'] = traceback.format_exc()
return log_data
def debug(self, message: str, context: Optional[LogContext] = None, extra: Optional[Dict[str, Any]] = None) -> None: """Log debug message.""" if self.logger.isEnabledFor(logging.DEBUG): log_data = self._get_log_data(message, LogLevel.DEBUG.value, context, extra) self.logger.debug(message, extra=log_data)
def info(self, message: str, context: Optional[LogContext] = None, extra: Optional[Dict[str, Any]] = None) -> None: """Log info message.""" if self.logger.isEnabledFor(logging.INFO): log_data = self._get_log_data(message, LogLevel.INFO.value, context, extra) self.logger.info(message, extra=log_data)
def warning(self, message: str, context: Optional[LogContext] = None, extra: Optional[Dict[str, Any]] = None) -> None: """Log warning message.""" if self.logger.isEnabledFor(logging.WARNING): log_data = self._get_log_data(message, LogLevel.WARNING.value, context, extra) self.logger.warning(message, extra=log_data)
def error(self, message: str, context: Optional[LogContext] = None, extra: Optional[Dict[str, Any]] = None, exception: Optional[Exception] = None) -> None: """Log error message.""" if self.logger.isEnabledFor(logging.ERROR): log_data = self._get_log_data(message, LogLevel.ERROR.value, context, extra, exception) self.logger.error(message, extra=log_data)
def critical(self, message: str, context: Optional[LogContext] = None, extra: Optional[Dict[str, Any]] = None, exception: Optional[Exception] = None) -> None: """Log critical message.""" if self.logger.isEnabledFor(logging.CRITICAL): log_data = self._get_log_data(message, LogLevel.CRITICAL.value, context, extra, exception) self.logger.critical(message, extra=log_data)
def log_operation_start(self, operation: str, context: Optional[LogContext] = None, extra: Optional[Dict[str, Any]] = None) -> str: """ Log operation start and return correlation ID.
Args: operation: Operation name context: Log context extra: Extra data
Returns: str: Correlation ID for the operation """ correlation_id = str(uuid.uuid4())
if context: context.correlation_id = correlation_id context.operation = operation else: context = LogContext(correlation_id=correlation_id, operation=operation)
# Set correlation ID in context correlation_id_context.set(correlation_id)
self.info(f"Operation started: {operation}", context, extra) return correlation_id
def log_operation_end(self, operation: str, correlation_id: str, success: bool = True, duration: Optional[float] = None, context: Optional[LogContext] = None, extra: Optional[Dict[str, Any]] = None) -> None: """ Log operation end.
Args: operation: Operation name correlation_id: Correlation ID success: Whether operation succeeded duration: Operation duration in seconds context: Log context extra: Extra data """ if context: context.correlation_id = correlation_id context.operation = operation else: context = LogContext(correlation_id=correlation_id, operation=operation)
# Add performance data if extra is None: extra = {} extra['success'] = success if duration is not None: extra['duration_seconds'] = duration
status = "completed successfully" if success else "failed" message = f"Operation {status}: {operation}"
if success: self.info(message, context, extra) else: self.error(message, context, extra)
def log_performance_metric(self, metric_name: str, value: Union[int, float], unit: str = None, context: Optional[LogContext] = None, extra: Optional[Dict[str, Any]] = None) -> None: """ Log performance metric.
Args: metric_name: Name of the metric value: Metric value unit: Unit of measurement context: Log context extra: Extra data """ if extra is None: extra = {}
extra['metric'] = { 'name': metric_name, 'value': value, 'unit': unit, 'timestamp': time.time() }
message = f"Performance metric: {metric_name}={value}" if unit: message += f" {unit}"
self.info(message, context, extra)
class JsonFormatter(logging.Formatter): """JSON log formatter."""
def format(self, record: logging.LogRecord) -> str: """Format log record as JSON.""" try: # Get structured data from extra log_data = getattr(record, 'extra', {})
# Ensure basic fields are present if 'timestamp' not in log_data: log_data['timestamp'] = datetime.utcnow().isoformat() + 'Z' if 'level' not in log_data: log_data['level'] = record.levelname if 'message' not in log_data: log_data['message'] = record.getMessage() if 'logger_name' not in log_data: log_data['logger_name'] = record.name
# Add standard log record fields log_data.update({ 'module': record.module, 'function': record.funcName, 'line': record.lineno, 'thread': record.thread, 'process': record.process })
return json.dumps(log_data, default=str, ensure_ascii=False)
except Exception as e: # Fallback to standard formatting return f"JSON formatting error: {e} | Original: {record.getMessage()}"
class ContextFormatter(logging.Formatter): """Context-aware log formatter."""
def __init__(self): """Initialize formatter.""" super().__init__( fmt='%(asctime)s - %(name)s - %(levelname)s - [%(correlation_id)s] - %(message)s', datefmt='%Y-%m-%d %H:%M:%S' )
def format(self, record: logging.LogRecord) -> str: """Format log record with context.""" try: # Get correlation ID from context or record correlation_id = correlation_id_context.get() if not correlation_id: extra_data = getattr(record, 'extra', {}) correlation_id = extra_data.get('correlation_id', 'unknown')
# Add correlation ID to record record.correlation_id = correlation_id
# Add context information if available extra_data = getattr(record, 'extra', {}) if 'operation' in extra_data: record.message = f"[{extra_data['operation']}] {record.getMessage()}"
return super().format(record)
except Exception as e: # Fallback formatting return f"Formatting error: {e} | Original: {record.getMessage()}"
def get_structured_logger(name: str, enable_json_logging: bool = True) -> StructuredLogger: """ Get a structured logger instance.
Args: name: Logger name enable_json_logging: Whether to use JSON format
Returns: StructuredLogger: Configured structured logger """ return StructuredLogger(name, enable_json_logging)
def set_correlation_id(correlation_id: str) -> None: """ Set correlation ID in context.
Args: correlation_id: Correlation ID to set """ correlation_id_context.set(correlation_id)
def get_correlation_id() -> Optional[str]: """ Get current correlation ID from context.
Returns: Optional[str]: Current correlation ID """ return correlation_id_context.get()
def generate_correlation_id() -> str: """ Generate a new correlation ID.
Returns: str: New correlation ID """ return str(uuid.uuid4())11 unmodified lines12131415161712 unmodified lines3031323334353614 unmodified lines5152535455565758596061626364656667686970717273747576777879807 unmodified lines8889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241 unmodified line1261271281291301311321331341359 unmodified lines14514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919010 unmodified lines2012022032042052062072082092101 unmodified line21221321421521621721816 unmodified lines2352362372382392402412422432442452462472482495 unmodified lines25525625725825926026126212 unmodified lines2752762772782792802812822832842852862872882892901 unmodified line29229329429529629729829930030130230330430530630730813 unmodified lines32232332432532632732832933033133233333433533633733833934034125 unmodified lines36736836937037137237337437537637737837938038138238338438538638738838939039139239329 unmodified lines42342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446572 unmodified lines5385395405415425435445455465472 unmodified lines55055155255311 unmodified linesfrom ..dtos.audio_upload_dto import AudioUploadDtofrom ..dtos.processing_request_dto import ProcessingRequestDtofrom ..dtos.processing_result_dto import ProcessingResultDtofrom ...domain.interfaces.speech_recognition import ISpeechRecognitionServicefrom ...domain.interfaces.translation import ITranslationServicefrom ...domain.interfaces.speech_synthesis import ISpeechSynthesisService12 unmodified linesfrom ...infrastructure.config.app_config import AppConfigfrom ...infrastructure.config.dependency_container import DependencyContainerlogger = logging.getLogger(__name__)class AudioProcessingApplicationService:14 unmodified linesself._container = containerself._config = config or container.resolve(AppConfig)self._temp_files: Dict[str, str] = {} # Track temporary files for cleanup# Setup loggingself._setup_logging()logger.info("AudioProcessingApplicationService initialized")def _setup_logging(self) -> None:"""Setup logging configuration."""try:log_config = self._config.get_logging_config()# Configure logger levellogger.setLevel(getattr(logging, log_config['level'].upper(), logging.INFO))# Add file handler if enabledif 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}")7 unmodified linesReturns: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 requestself._validate_request(request)# Create temporary working directorywith self._create_temp_directory(correlation_id) as temp_dir:# Step 1: Convert uploaded audio to domain modelaudio_content = self._convert_upload_to_audio_content(request.audio, temp_dir)# Step 2: Speech-to-Textoriginal_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-Speechoutput_audio_path = self._perform_speech_synthesis(translated_text,request.voice,request.speed,1 unmodified linetemp_dir,correlation_id)# Calculate processing timeprocessing_time = time.time() - start_time# Create successful resultresult = ProcessingResultDto.success_result(original_text=original_text.text,9 unmodified lines'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 resultexcept DomainException as e:processing_time = time.time() - start_timeerror_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_timelogger.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 filesself._cleanup_temp_files()10 unmodified lines"""if not isinstance(request, ProcessingRequestDto):raise ValueError("Request must be a ProcessingRequestDto instance")# Additional validation beyond DTO validationprocessing_config = self._config.get_processing_config()# Check file size limitsmax_size_bytes = processing_config['max_file_size_mb'] * 1024 * 1024if request.audio.size > max_size_bytes:1 unmodified linef"Audio file too large: {request.audio.size} bytes. "f"Maximum allowed: {max_size_bytes} bytes")# Check supported audio formatssupported_formats = processing_config['supported_audio_formats']file_ext = request.audio.file_extension.lstrip('.')16 unmodified lines"""processing_config = self._config.get_processing_config()base_temp_dir = processing_config['temp_dir']# Create unique temp directorytemp_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_dirfinally:# Cleanup temp directory if configuredif processing_config.get('cleanup_temp_files', True):5 unmodified lineslogger.warning(f"Failed to cleanup temp directory {temp_dir}: {e}")def _convert_upload_to_audio_content(self,upload: AudioUploadDto,temp_dir: str) -> AudioContent:"""12 unmodified linestry:# Save uploaded content to temporary filetemp_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 cleanupself._temp_files[temp_file_path] = temp_file_path# Determine audio format from file extensionaudio_format = upload.file_extension.lstrip('.').lower()# Create AudioContent (simplified - in real implementation would extract metadata)audio_content = AudioContent(data=upload.content,1 unmodified linesample_rate=16000, # Default, would be extracted from actual fileduration=0.0 # Would be calculated from actual file)logger.debug(f"Converted upload to AudioContent: {upload.filename}")return audio_contentexcept 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:13 unmodified lines"""try:logger.debug(f"Starting STT with model: {model} [correlation_id={correlation_id}]")# Get STT provider from containerstt_provider = self._container.get_stt_provider(model)# Perform transcriptiontext_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_contentexcept Exception as e:logger.error(f"STT failed: {e} [correlation_id={correlation_id}]")raise SpeechRecognitionException(f"Speech recognition failed: {str(e)}")25 unmodified linesf"Starting translation: {source_language or 'auto'} -> {target_language} "f"[correlation_id={correlation_id}]")# Get translation provider from containertranslation_provider = self._container.get_translation_provider()# Create translation requesttranslation_request = TranslationRequest(text=text.text,source_language=source_language or 'auto',target_language=target_language)# Perform translationtranslated_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_textexcept Exception as e:logger.error(f"Translation failed: {e} [correlation_id={correlation_id}]")raise TranslationFailedException(f"Translation failed: {str(e)}")29 unmodified linesf"Starting TTS with voice: {voice}, speed: {speed} "f"[correlation_id={correlation_id}]")# Get TTS provider from containertts_provider = self._container.get_tts_provider(voice)# Create voice settingsvoice_settings = VoiceSettings(voice_id=voice,speed=speed,language=language)# Create synthesis requestsynthesis_request = SpeechSynthesisRequest(text=text.text,voice_settings=voice_settings)# Perform synthesisaudio_content = tts_provider.synthesize(synthesis_request)# Save output to fileoutput_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 cleanupself._temp_files[output_path] = output_pathlogger.info(f"TTS completed successfully [correlation_id={correlation_id}, "f"output_file={output_path}]")return output_pathexcept Exception as e:logger.error(f"TTS failed: {e} [correlation_id={correlation_id}]")raise SpeechSynthesisException(f"Speech synthesis failed: {str(e)}")72 unmodified linesdef cleanup(self) -> None:"""Cleanup application service resources."""logger.info("Cleaning up AudioProcessingApplicationService")# Cleanup temporary filesself._cleanup_temp_files()logger.info("AudioProcessingApplicationService cleanup completed")def __enter__(self):2 unmodified linesdef __exit__(self, exc_type, exc_val, exc_tb):"""Context manager exit with cleanup."""self.cleanup()11 unmodified lines12131415161718192012 unmodified lines3334353637383914 unmodified lines545556575859606162636465666768697071727374757677787980818283848586877 unmodified lines95969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471 unmodified line1491501511521531541551561571589 unmodified lines16816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028110 unmodified lines2922932942952962972982993003011 unmodified line30330430530630730830916 unmodified lines3263273283293303313323333343353363373383393405 unmodified lines34634734834935035135235312 unmodified lines3663673683693703713723733743753763773783793803811 unmodified line38338438538638738838939039139239339439539639739839913 unmodified lines41341441541641741841942042142242342442542642742842943043143225 unmodified lines45845946046146246346446546646746846947047147247347447547647747847948048148248348429 unmodified lines51451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555672 unmodified lines6296306316326336346356366376382 unmodified lines64164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282311 unmodified linesfrom ..dtos.audio_upload_dto import AudioUploadDtofrom ..dtos.processing_request_dto import ProcessingRequestDtofrom ..dtos.processing_result_dto import ProcessingResultDtofrom ..error_handling.error_mapper import ErrorMapperfrom ..error_handling.structured_logger import StructuredLogger, LogContext, get_structured_loggerfrom ..error_handling.recovery_manager import RecoveryManager, RetryConfig, CircuitBreakerConfigfrom ...domain.interfaces.speech_recognition import ISpeechRecognitionServicefrom ...domain.interfaces.translation import ITranslationServicefrom ...domain.interfaces.speech_synthesis import ISpeechSynthesisService12 unmodified linesfrom ...infrastructure.config.app_config import AppConfigfrom ...infrastructure.config.dependency_container import DependencyContainerlogger = get_structured_logger(__name__)class AudioProcessingApplicationService:14 unmodified linesself._container = containerself._config = config or container.resolve(AppConfig)self._temp_files: Dict[str, str] = {} # Track temporary files for cleanup# Initialize error handling componentsself._error_mapper = ErrorMapper()self._recovery_manager = RecoveryManager()# Setup loggingself._setup_logging()logger.info("AudioProcessingApplicationService initialized")def _setup_logging(self) -> None:"""Setup logging configuration."""try:log_config = self._config.get_logging_config()# Configure logger levellogger.setLevel(getattr(logging, log_config['level'].upper(), logging.INFO))# Add file handler if enabledif 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}")7 unmodified linesReturns:ProcessingResultDto: Result of the complete processing pipeline"""# Generate correlation ID and start operation loggingcorrelation_id = logger.log_operation_start("audio_processing_pipeline",extra={'asr_model': request.asr_model,'target_language': request.target_language,'voice': request.voice,'file_name': request.audio.filename,'file_size': request.audio.size})start_time = time.time()context = LogContext(correlation_id=correlation_id,operation="audio_processing_pipeline",component="AudioProcessingApplicationService")try:# Validate requestself._validate_request(request)# Create temporary working directorywith self._create_temp_directory(correlation_id) as temp_dir:# Step 1: Convert uploaded audio to domain modelaudio_content = self._convert_upload_to_audio_content(request.audio, temp_dir)# Step 2: Speech-to-Text with retry and fallbackoriginal_text = self._perform_speech_recognition_with_recovery(audio_content,request.asr_model,correlation_id)# Step 3: Translation (if needed) with retrytranslated_text = original_textif request.requires_translation:translated_text = self._perform_translation_with_recovery(original_text,request.source_language,request.target_language,correlation_id)# Step 4: Text-to-Speech with fallback providersoutput_audio_path = self._perform_speech_synthesis_with_recovery(translated_text,request.voice,request.speed,1 unmodified linetemp_dir,correlation_id)# Calculate processing timeprocessing_time = time.time() - start_time# Create successful resultresult = ProcessingResultDto.success_result(original_text=original_text.text,9 unmodified lines'translation_required': request.requires_translation})# Log successful completionlogger.log_operation_end("audio_processing_pipeline",correlation_id,success=True,duration=processing_time,context=context,extra={'original_text_length': len(original_text.text),'translated_text_length': len(translated_text.text) if translated_text != original_text else 0,'output_file': output_audio_path})return resultexcept DomainException as e:processing_time = time.time() - start_time# Map exception to user-friendly errorerror_context = {'file_name': request.audio.filename,'file_size': request.audio.size,'operation': 'audio_processing_pipeline','correlation_id': correlation_id}error_mapping = self._error_mapper.map_exception(e, error_context)logger.error(f"Domain error in audio processing pipeline: {error_mapping.user_message}",context=context,exception=e,extra={'error_code': error_mapping.error_code,'error_category': error_mapping.category.value,'error_severity': error_mapping.severity.value,'recovery_suggestions': error_mapping.recovery_suggestions})# Log operation failurelogger.log_operation_end("audio_processing_pipeline",correlation_id,success=False,duration=processing_time,context=context)return ProcessingResultDto.error_result(error_message=error_mapping.user_message,error_code=error_mapping.error_code,processing_time=processing_time,metadata={'correlation_id': correlation_id,'error_category': error_mapping.category.value,'error_severity': error_mapping.severity.value,'recovery_suggestions': error_mapping.recovery_suggestions,'technical_details': error_mapping.technical_details})except Exception as e:processing_time = time.time() - start_time# Map unexpected exceptionerror_context = {'file_name': request.audio.filename,'operation': 'audio_processing_pipeline','correlation_id': correlation_id}error_mapping = self._error_mapper.map_exception(e, error_context)logger.critical(f"Unexpected error in audio processing pipeline: {error_mapping.user_message}",context=context,exception=e,extra={'error_code': error_mapping.error_code,'error_category': error_mapping.category.value,'error_severity': error_mapping.severity.value})# Log operation failurelogger.log_operation_end("audio_processing_pipeline",correlation_id,success=False,duration=processing_time,context=context)return ProcessingResultDto.error_result(error_message=error_mapping.user_message,error_code=error_mapping.error_code,processing_time=processing_time,metadata={'correlation_id': correlation_id,'error_category': error_mapping.category.value,'error_severity': error_mapping.severity.value,'technical_details': error_mapping.technical_details})finally:# Cleanup temporary filesself._cleanup_temp_files()10 unmodified lines"""if not isinstance(request, ProcessingRequestDto):raise ValueError("Request must be a ProcessingRequestDto instance")# Additional validation beyond DTO validationprocessing_config = self._config.get_processing_config()# Check file size limitsmax_size_bytes = processing_config['max_file_size_mb'] * 1024 * 1024if request.audio.size > max_size_bytes:1 unmodified linef"Audio file too large: {request.audio.size} bytes. "f"Maximum allowed: {max_size_bytes} bytes")# Check supported audio formatssupported_formats = processing_config['supported_audio_formats']file_ext = request.audio.file_extension.lstrip('.')16 unmodified lines"""processing_config = self._config.get_processing_config()base_temp_dir = processing_config['temp_dir']# Create unique temp directorytemp_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_dirfinally:# Cleanup temp directory if configuredif processing_config.get('cleanup_temp_files', True):5 unmodified lineslogger.warning(f"Failed to cleanup temp directory {temp_dir}: {e}")def _convert_upload_to_audio_content(self,upload: AudioUploadDto,temp_dir: str) -> AudioContent:"""12 unmodified linestry:# Save uploaded content to temporary filetemp_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 cleanupself._temp_files[temp_file_path] = temp_file_path# Determine audio format from file extensionaudio_format = upload.file_extension.lstrip('.').lower()# Create AudioContent (simplified - in real implementation would extract metadata)audio_content = AudioContent(data=upload.content,1 unmodified linesample_rate=16000, # Default, would be extracted from actual fileduration=0.0 # Would be calculated from actual file)logger.debug(f"Converted upload to AudioContent: {upload.filename}")return audio_contentexcept 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:13 unmodified lines"""try:logger.debug(f"Starting STT with model: {model} [correlation_id={correlation_id}]")# Get STT provider from containerstt_provider = self._container.get_stt_provider(model)# Perform transcriptiontext_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_contentexcept Exception as e:logger.error(f"STT failed: {e} [correlation_id={correlation_id}]")raise SpeechRecognitionException(f"Speech recognition failed: {str(e)}")25 unmodified linesf"Starting translation: {source_language or 'auto'} -> {target_language} "f"[correlation_id={correlation_id}]")# Get translation provider from containertranslation_provider = self._container.get_translation_provider()# Create translation requesttranslation_request = TranslationRequest(text=text.text,source_language=source_language or 'auto',target_language=target_language)# Perform translationtranslated_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_textexcept Exception as e:logger.error(f"Translation failed: {e} [correlation_id={correlation_id}]")raise TranslationFailedException(f"Translation failed: {str(e)}")29 unmodified linesf"Starting TTS with voice: {voice}, speed: {speed} "f"[correlation_id={correlation_id}]")# Get TTS provider from containertts_provider = self._container.get_tts_provider(voice)# Create voice settingsvoice_settings = VoiceSettings(voice_id=voice,speed=speed,language=language)# Create synthesis requestsynthesis_request = SpeechSynthesisRequest(text=text.text,voice_settings=voice_settings)# Perform synthesisaudio_content = tts_provider.synthesize(synthesis_request)# Save output to fileoutput_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 cleanupself._temp_files[output_path] = output_pathlogger.info(f"TTS completed successfully [correlation_id={correlation_id}, "f"output_file={output_path}]")return output_pathexcept Exception as e:logger.error(f"TTS failed: {e} [correlation_id={correlation_id}]")raise SpeechSynthesisException(f"Speech synthesis failed: {str(e)}")72 unmodified linesdef cleanup(self) -> None:"""Cleanup application service resources."""logger.info("Cleaning up AudioProcessingApplicationService")# Cleanup temporary filesself._cleanup_temp_files()logger.info("AudioProcessingApplicationService cleanup completed")def __enter__(self):2 unmodified linesdef __exit__(self, exc_type, exc_val, exc_tb):"""Context manager exit with cleanup."""self.cleanup()def _perform_speech_recognition_with_recovery(self,audio: AudioContent,model: str,correlation_id: str) -> TextContent:"""Perform speech-to-text recognition with retry and fallback.Args:audio: Audio content to transcribemodel: STT model to usecorrelation_id: Correlation ID for trackingReturns:TextContent: Transcribed textRaises:SpeechRecognitionException: If all attempts fail"""context = LogContext(correlation_id=correlation_id,operation="speech_recognition",component="AudioProcessingApplicationService")# Configure retry for STTretry_config = RetryConfig(max_attempts=2,base_delay=1.0,retryable_exceptions=[SpeechRecognitionException, ConnectionError, TimeoutError])def stt_operation():return self._perform_speech_recognition(audio, model, correlation_id)try:# Try with retryreturn self._recovery_manager.retry_with_backoff(stt_operation,retry_config,correlation_id)except Exception as e:# Try fallback models if primary failsstt_config = self._config.get_stt_config()fallback_models = [m for m in stt_config['preferred_providers'] if m != model]if fallback_models:logger.warning(f"STT model {model} failed, trying fallbacks: {fallback_models}",context=context,exception=e)fallback_funcs = [lambda m=fallback_model: self._perform_speech_recognition(audio, m, correlation_id)for fallback_model in fallback_models]return self._recovery_manager.execute_with_fallback(stt_operation,fallback_funcs,correlation_id)else:raisedef _perform_translation_with_recovery(self,text: TextContent,source_language: Optional[str],target_language: str,correlation_id: str) -> TextContent:"""Perform text translation with retry.Args:text: Text to translatesource_language: Source language (optional, auto-detect if None)target_language: Target languagecorrelation_id: Correlation ID for trackingReturns:TextContent: Translated textRaises:TranslationFailedException: If all attempts fail"""# Configure retry for translationretry_config = RetryConfig(max_attempts=3,base_delay=1.0,exponential_backoff=True,retryable_exceptions=[TranslationFailedException, ConnectionError, TimeoutError])def translation_operation():return self._perform_translation(text, source_language, target_language, correlation_id)return self._recovery_manager.retry_with_backoff(translation_operation,retry_config,correlation_id)def _perform_speech_synthesis_with_recovery(self,text: TextContent,voice: str,speed: float,language: str,temp_dir: str,correlation_id: str) -> str:"""Perform text-to-speech synthesis with fallback providers.Args:text: Text to synthesizevoice: Voice to usespeed: Speech speedlanguage: Target languagetemp_dir: Temporary directory for outputcorrelation_id: Correlation ID for trackingReturns:str: Path to generated audio fileRaises:SpeechSynthesisException: If all providers fail"""context = LogContext(correlation_id=correlation_id,operation="speech_synthesis",component="AudioProcessingApplicationService")def tts_operation():return self._perform_speech_synthesis(text, voice, speed, language, temp_dir, correlation_id)try:# Try with circuit breaker protectionreturn self._recovery_manager.execute_with_circuit_breaker(tts_operation,f"tts_{voice}",CircuitBreakerConfig(failure_threshold=3, recovery_timeout=30.0),correlation_id)except Exception as e:# Try fallback TTS providerstts_config = self._config.get_tts_config()fallback_voices = [v for v in tts_config['preferred_providers'] if v != voice]if fallback_voices:logger.warning(f"TTS voice {voice} failed, trying fallbacks: {fallback_voices}",context=context,exception=e)fallback_funcs = [lambda v=fallback_voice: self._perform_speech_synthesis(text, v, speed, language, temp_dir, correlation_id)for fallback_voice in fallback_voices]return self._recovery_manager.execute_with_fallback(tts_operation,fallback_funcs,correlation_id)else:raise
6 unmodified lines789101112131415161718 unmodified lines3637383940414296 unmodified lines1391401411421431441451461471482 unmodified lines15115215315415515615715815916016116216314 unmodified lines1781791801811821831841851861872 unmodified lines19019119219319419519619719819920020120214 unmodified lines2172182192202212222232242252262 unmodified lines22923023123223323423523623723823924024114 unmodified lines2562572582592602612622632642652 unmodified lines26826927027127227327427527627727827928010 unmodified lines2912922932942952962971 unmodified line2993003013023033043053063073083093103113123133143153163179 unmodified lines3273283293303313323331 unmodified line33533633733833934034134234334434534634734834935035135235312 unmodified lines36636736836937037137237337437537637737837938038138238338417 unmodified lines4024034044054064074084094104114124134144154161 unmodified line41841942042142242342431 unmodified lines45645745845946046146246346446546646746846947047147247347447511 unmodified lines48748848949049149249349449511 unmodified lines5075085095105115125132 unmodified lines5165175185195205215222 unmodified lines5255265275285295305311 unmodified line53353453553653753853954054137 unmodified lines5795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186199 unmodified lines6296306316326336346356366376386396406416426436446456 unmodified linesfrom pathlib import Pathfrom dataclasses import asdictfrom ...infrastructure.config.app_config import AppConfig, TTSConfig, STTConfig, TranslationConfig, ProcessingConfig, LoggingConfigfrom ...infrastructure.config.dependency_container import DependencyContainerfrom ...domain.exceptions import DomainExceptionlogger = logging.getLogger(__name__)class ConfigurationException(DomainException):18 unmodified lines"""self._container = containerself._config = config or container.resolve(AppConfig)logger.info("ConfigurationApplicationService initialized")def get_current_configuration(self) -> Dict[str, Any]:96 unmodified linestry:# Validate updatesself._validate_tts_updates(updates)# Apply updates to current configcurrent_config = self._config.get_tts_config()for key, value in updates.items():if key in current_config:# Update the actual config object2 unmodified lineslogger.debug(f"Updated TTS config: {key} = {value}")else:logger.warning(f"Unknown TTS configuration key: {key}")# Return updated configurationupdated_config = self._config.get_tts_config()logger.info(f"TTS configuration updated: {list(updates.keys())}")return updated_configexcept Exception as e:logger.error(f"Failed to update TTS configuration: {e}")raise ConfigurationException(f"Failed to update TTS configuration: {str(e)}")14 unmodified linestry:# Validate updatesself._validate_stt_updates(updates)# Apply updates to current configcurrent_config = self._config.get_stt_config()for key, value in updates.items():if key in current_config:# Update the actual config object2 unmodified lineslogger.debug(f"Updated STT config: {key} = {value}")else:logger.warning(f"Unknown STT configuration key: {key}")# Return updated configurationupdated_config = self._config.get_stt_config()logger.info(f"STT configuration updated: {list(updates.keys())}")return updated_configexcept Exception as e:logger.error(f"Failed to update STT configuration: {e}")raise ConfigurationException(f"Failed to update STT configuration: {str(e)}")14 unmodified linestry:# Validate updatesself._validate_translation_updates(updates)# Apply updates to current configcurrent_config = self._config.get_translation_config()for key, value in updates.items():if key in current_config:# Update the actual config object2 unmodified lineslogger.debug(f"Updated translation config: {key} = {value}")else:logger.warning(f"Unknown translation configuration key: {key}")# Return updated configurationupdated_config = self._config.get_translation_config()logger.info(f"Translation configuration updated: {list(updates.keys())}")return updated_configexcept Exception as e:logger.error(f"Failed to update translation configuration: {e}")raise ConfigurationException(f"Failed to update translation configuration: {str(e)}")14 unmodified linestry:# Validate updatesself._validate_processing_updates(updates)# Apply updates to current configcurrent_config = self._config.get_processing_config()for key, value in updates.items():if key in current_config:# Update the actual config object2 unmodified lineslogger.debug(f"Updated processing config: {key} = {value}")else:logger.warning(f"Unknown processing configuration key: {key}")# Return updated configurationupdated_config = self._config.get_processing_config()logger.info(f"Processing configuration updated: {list(updates.keys())}")return updated_configexcept Exception as e:logger.error(f"Failed to update processing configuration: {e}")raise ConfigurationException(f"Failed to update processing configuration: {str(e)}")10 unmodified lines"""valid_providers = ['kokoro', 'dia', 'cosyvoice2', 'dummy']valid_languages = ['en', 'es', 'fr', 'de', 'it', 'pt', 'ru', 'ja', 'ko', 'zh']for key, value in updates.items():if key == 'preferred_providers':if not isinstance(value, list):1 unmodified linefor provider in value:if provider not in valid_providers:raise ConfigurationException(f"Invalid TTS provider: {provider}")elif key == 'default_speed':if not isinstance(value, (int, float)) or not (0.1 <= value <= 3.0):raise ConfigurationException("default_speed must be between 0.1 and 3.0")elif key == 'default_language':if value not in valid_languages:raise ConfigurationException(f"Invalid language: {value}")elif key == 'enable_streaming':if not isinstance(value, bool):raise ConfigurationException("enable_streaming must be a boolean")elif key == 'max_text_length':if not isinstance(value, int) or value <= 0:raise ConfigurationException("max_text_length must be a positive integer")9 unmodified linesConfigurationException: If validation fails"""valid_providers = ['whisper', 'parakeet']for key, value in updates.items():if key == 'preferred_providers':if not isinstance(value, list):1 unmodified linefor provider in value:if provider not in valid_providers:raise ConfigurationException(f"Invalid STT provider: {provider}")elif key == 'default_model':if value not in valid_providers:raise ConfigurationException(f"Invalid STT model: {value}")elif key == 'chunk_length_s':if not isinstance(value, int) or value <= 0:raise ConfigurationException("chunk_length_s must be a positive integer")elif key == 'batch_size':if not isinstance(value, int) or value <= 0:raise ConfigurationException("batch_size must be a positive integer")elif key == 'enable_vad':if not isinstance(value, bool):raise ConfigurationException("enable_vad must be a boolean")12 unmodified linesif key == 'default_provider':if not isinstance(value, str) or not value:raise ConfigurationException("default_provider must be a non-empty string")elif key == 'model_name':if not isinstance(value, str) or not value:raise ConfigurationException("model_name must be a non-empty string")elif key == 'max_chunk_length':if not isinstance(value, int) or value <= 0:raise ConfigurationException("max_chunk_length must be a positive integer")elif key == 'batch_size':if not isinstance(value, int) or value <= 0:raise ConfigurationException("batch_size must be a positive integer")elif key == 'cache_translations':if not isinstance(value, bool):raise ConfigurationException("cache_translations must be a boolean")17 unmodified linesPath(value).mkdir(parents=True, exist_ok=True)except Exception as e:raise ConfigurationException(f"Invalid temp_dir path: {e}")elif key == 'cleanup_temp_files':if not isinstance(value, bool):raise ConfigurationException("cleanup_temp_files must be a boolean")elif key == 'max_file_size_mb':if not isinstance(value, int) or value <= 0:raise ConfigurationException("max_file_size_mb must be a positive integer")elif key == 'supported_audio_formats':if not isinstance(value, list):raise ConfigurationException("supported_audio_formats must be a list")1 unmodified linefor fmt in value:if fmt not in valid_formats:raise ConfigurationException(f"Invalid audio format: {fmt}")elif key == 'processing_timeout_seconds':if not isinstance(value, int) or value <= 0:raise ConfigurationException("processing_timeout_seconds must be a positive integer")31 unmodified linestry:if not os.path.exists(file_path):raise ConfigurationException(f"Configuration file not found: {file_path}")# Create new config instance with the filenew_config = AppConfig(config_file=file_path)# Update current configself._config = new_config# Update container with new configself._container.register_singleton(AppConfig, new_config)logger.info(f"Configuration loaded from {file_path}")return self.get_current_configuration()except Exception as e:logger.error(f"Failed to load configuration from {file_path}: {e}")raise ConfigurationException(f"Failed to load configuration: {str(e)}")11 unmodified linestry:self._config.reload_configuration()logger.info("Configuration reloaded successfully")return self.get_current_configuration()except Exception as e:logger.error(f"Failed to reload configuration: {e}")raise ConfigurationException(f"Failed to reload configuration: {str(e)}")11 unmodified lines'stt': {},'translation': {}}# Check TTS providerstts_factory = self._container.resolve(type(self._container._get_tts_factory()))for provider in ['kokoro', 'dia', 'cosyvoice2', 'dummy']:2 unmodified linesavailability['tts'][provider] = Trueexcept Exception:availability['tts'][provider] = False# Check STT providersstt_factory = self._container.resolve(type(self._container._get_stt_factory()))for provider in ['whisper', 'parakeet']:2 unmodified linesavailability['stt'][provider] = Trueexcept Exception:availability['stt'][provider] = False# Check translation providerstranslation_factory = self._container.resolve(type(self._container._get_translation_factory()))try:1 unmodified lineavailability['translation']['nllb'] = Trueexcept Exception:availability['translation']['nllb'] = Falsereturn availabilityexcept Exception as e:logger.error(f"Failed to check provider availability: {e}")raise ConfigurationException(f"Failed to check provider availability: {str(e)}")37 unmodified lines'processing': [],'logging': []}try:# Validate TTS configurationtts_config = self._config.get_tts_config()if not (0.1 <= tts_config['default_speed'] <= 3.0):issues['tts'].append(f"Invalid default_speed: {tts_config['default_speed']}")if tts_config['max_text_length'] <= 0:issues['tts'].append(f"Invalid max_text_length: {tts_config['max_text_length']}")# Validate STT configurationstt_config = self._config.get_stt_config()if stt_config['chunk_length_s'] <= 0:issues['stt'].append(f"Invalid chunk_length_s: {stt_config['chunk_length_s']}")if stt_config['batch_size'] <= 0:issues['stt'].append(f"Invalid batch_size: {stt_config['batch_size']}")# Validate processing configurationprocessing_config = self._config.get_processing_config()if not os.path.exists(processing_config['temp_dir']):issues['processing'].append(f"Temp directory does not exist: {processing_config['temp_dir']}")if processing_config['max_file_size_mb'] <= 0:issues['processing'].append(f"Invalid max_file_size_mb: {processing_config['max_file_size_mb']}")# Validate logging configurationlogging_config = self._config.get_logging_config()valid_levels = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']if logging_config['level'].upper() not in valid_levels:issues['logging'].append(f"Invalid log level: {logging_config['level']}")except Exception as e:issues['general'] = [f"Configuration validation error: {str(e)}"]return issuesdef reset_to_defaults(self) -> Dict[str, Any]:9 unmodified linestry:# Create new config with defaultsdefault_config = AppConfig()# Update current configself._config = default_config# Update container with new configself._container.register_singleton(AppConfig, default_config)logger.info("Configuration reset to defaults")return self.get_current_configuration()except Exception as e:logger.error(f"Failed to reset configuration: {e}")raise ConfigurationException(f"Failed to reset configuration: {str(e)}")6 unmodified lines7891011121314151617181918 unmodified lines3839404142434445464796 unmodified lines1441451461471481491501511521532 unmodified lines15615715815916016116216316416516616716814 unmodified lines1831841851861871881891901911922 unmodified lines19519619719819920020120220320420520620714 unmodified lines2222232242252262272282292302312 unmodified lines23423523623723823924024124224324424524614 unmodified lines2612622632642652662672682692702 unmodified lines27327427527627727827928028128228328428510 unmodified lines2962972982993003013021 unmodified line3043053063073083093103113123133143153163173183193203213229 unmodified lines3323333343353363373381 unmodified line34034134234334434534634734834935035135235335435535635735812 unmodified lines37137237337437537637737837938038138238338438538638738838917 unmodified lines4074084094104114124134144154164174184194204211 unmodified line42342442542642742842931 unmodified lines46146246346446546646746846947047147247347447547647747847948011 unmodified lines49249349449549649749849950011 unmodified lines5125135145155165175182 unmodified lines5215225235245255265272 unmodified lines5305315325335345355361 unmodified line53853954054154254354454554637 unmodified lines5845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236249 unmodified lines6346356366376386396406416426436446456466476486496506 unmodified linesfrom pathlib import Pathfrom dataclasses import asdictfrom ..error_handling.error_mapper import ErrorMapperfrom ..error_handling.structured_logger import StructuredLogger, LogContext, get_structured_loggerfrom ...infrastructure.config.app_config import AppConfig, TTSConfig, STTConfig, TranslationConfig, ProcessingConfig, LoggingConfigfrom ...infrastructure.config.dependency_container import DependencyContainerfrom ...domain.exceptions import DomainExceptionlogger = get_structured_logger(__name__)class ConfigurationException(DomainException):18 unmodified lines"""self._container = containerself._config = config or container.resolve(AppConfig)# Initialize error handlingself._error_mapper = ErrorMapper()logger.info("ConfigurationApplicationService initialized")def get_current_configuration(self) -> Dict[str, Any]:96 unmodified linestry:# Validate updatesself._validate_tts_updates(updates)# Apply updates to current configcurrent_config = self._config.get_tts_config()for key, value in updates.items():if key in current_config:# Update the actual config object2 unmodified lineslogger.debug(f"Updated TTS config: {key} = {value}")else:logger.warning(f"Unknown TTS configuration key: {key}")# Return updated configurationupdated_config = self._config.get_tts_config()logger.info(f"TTS configuration updated: {list(updates.keys())}")return updated_configexcept Exception as e:logger.error(f"Failed to update TTS configuration: {e}")raise ConfigurationException(f"Failed to update TTS configuration: {str(e)}")14 unmodified linestry:# Validate updatesself._validate_stt_updates(updates)# Apply updates to current configcurrent_config = self._config.get_stt_config()for key, value in updates.items():if key in current_config:# Update the actual config object2 unmodified lineslogger.debug(f"Updated STT config: {key} = {value}")else:logger.warning(f"Unknown STT configuration key: {key}")# Return updated configurationupdated_config = self._config.get_stt_config()logger.info(f"STT configuration updated: {list(updates.keys())}")return updated_configexcept Exception as e:logger.error(f"Failed to update STT configuration: {e}")raise ConfigurationException(f"Failed to update STT configuration: {str(e)}")14 unmodified linestry:# Validate updatesself._validate_translation_updates(updates)# Apply updates to current configcurrent_config = self._config.get_translation_config()for key, value in updates.items():if key in current_config:# Update the actual config object2 unmodified lineslogger.debug(f"Updated translation config: {key} = {value}")else:logger.warning(f"Unknown translation configuration key: {key}")# Return updated configurationupdated_config = self._config.get_translation_config()logger.info(f"Translation configuration updated: {list(updates.keys())}")return updated_configexcept Exception as e:logger.error(f"Failed to update translation configuration: {e}")raise ConfigurationException(f"Failed to update translation configuration: {str(e)}")14 unmodified linestry:# Validate updatesself._validate_processing_updates(updates)# Apply updates to current configcurrent_config = self._config.get_processing_config()for key, value in updates.items():if key in current_config:# Update the actual config object2 unmodified lineslogger.debug(f"Updated processing config: {key} = {value}")else:logger.warning(f"Unknown processing configuration key: {key}")# Return updated configurationupdated_config = self._config.get_processing_config()logger.info(f"Processing configuration updated: {list(updates.keys())}")return updated_configexcept Exception as e:logger.error(f"Failed to update processing configuration: {e}")raise ConfigurationException(f"Failed to update processing configuration: {str(e)}")10 unmodified lines"""valid_providers = ['kokoro', 'dia', 'cosyvoice2', 'dummy']valid_languages = ['en', 'es', 'fr', 'de', 'it', 'pt', 'ru', 'ja', 'ko', 'zh']for key, value in updates.items():if key == 'preferred_providers':if not isinstance(value, list):1 unmodified linefor provider in value:if provider not in valid_providers:raise ConfigurationException(f"Invalid TTS provider: {provider}")elif key == 'default_speed':if not isinstance(value, (int, float)) or not (0.1 <= value <= 3.0):raise ConfigurationException("default_speed must be between 0.1 and 3.0")elif key == 'default_language':if value not in valid_languages:raise ConfigurationException(f"Invalid language: {value}")elif key == 'enable_streaming':if not isinstance(value, bool):raise ConfigurationException("enable_streaming must be a boolean")elif key == 'max_text_length':if not isinstance(value, int) or value <= 0:raise ConfigurationException("max_text_length must be a positive integer")9 unmodified linesConfigurationException: If validation fails"""valid_providers = ['whisper', 'parakeet']for key, value in updates.items():if key == 'preferred_providers':if not isinstance(value, list):1 unmodified linefor provider in value:if provider not in valid_providers:raise ConfigurationException(f"Invalid STT provider: {provider}")elif key == 'default_model':if value not in valid_providers:raise ConfigurationException(f"Invalid STT model: {value}")elif key == 'chunk_length_s':if not isinstance(value, int) or value <= 0:raise ConfigurationException("chunk_length_s must be a positive integer")elif key == 'batch_size':if not isinstance(value, int) or value <= 0:raise ConfigurationException("batch_size must be a positive integer")elif key == 'enable_vad':if not isinstance(value, bool):raise ConfigurationException("enable_vad must be a boolean")12 unmodified linesif key == 'default_provider':if not isinstance(value, str) or not value:raise ConfigurationException("default_provider must be a non-empty string")elif key == 'model_name':if not isinstance(value, str) or not value:raise ConfigurationException("model_name must be a non-empty string")elif key == 'max_chunk_length':if not isinstance(value, int) or value <= 0:raise ConfigurationException("max_chunk_length must be a positive integer")elif key == 'batch_size':if not isinstance(value, int) or value <= 0:raise ConfigurationException("batch_size must be a positive integer")elif key == 'cache_translations':if not isinstance(value, bool):raise ConfigurationException("cache_translations must be a boolean")17 unmodified linesPath(value).mkdir(parents=True, exist_ok=True)except Exception as e:raise ConfigurationException(f"Invalid temp_dir path: {e}")elif key == 'cleanup_temp_files':if not isinstance(value, bool):raise ConfigurationException("cleanup_temp_files must be a boolean")elif key == 'max_file_size_mb':if not isinstance(value, int) or value <= 0:raise ConfigurationException("max_file_size_mb must be a positive integer")elif key == 'supported_audio_formats':if not isinstance(value, list):raise ConfigurationException("supported_audio_formats must be a list")1 unmodified linefor fmt in value:if fmt not in valid_formats:raise ConfigurationException(f"Invalid audio format: {fmt}")elif key == 'processing_timeout_seconds':if not isinstance(value, int) or value <= 0:raise ConfigurationException("processing_timeout_seconds must be a positive integer")31 unmodified linestry:if not os.path.exists(file_path):raise ConfigurationException(f"Configuration file not found: {file_path}")# Create new config instance with the filenew_config = AppConfig(config_file=file_path)# Update current configself._config = new_config# Update container with new configself._container.register_singleton(AppConfig, new_config)logger.info(f"Configuration loaded from {file_path}")return self.get_current_configuration()except Exception as e:logger.error(f"Failed to load configuration from {file_path}: {e}")raise ConfigurationException(f"Failed to load configuration: {str(e)}")11 unmodified linestry:self._config.reload_configuration()logger.info("Configuration reloaded successfully")return self.get_current_configuration()except Exception as e:logger.error(f"Failed to reload configuration: {e}")raise ConfigurationException(f"Failed to reload configuration: {str(e)}")11 unmodified lines'stt': {},'translation': {}}# Check TTS providerstts_factory = self._container.resolve(type(self._container._get_tts_factory()))for provider in ['kokoro', 'dia', 'cosyvoice2', 'dummy']:2 unmodified linesavailability['tts'][provider] = Trueexcept Exception:availability['tts'][provider] = False# Check STT providersstt_factory = self._container.resolve(type(self._container._get_stt_factory()))for provider in ['whisper', 'parakeet']:2 unmodified linesavailability['stt'][provider] = Trueexcept Exception:availability['stt'][provider] = False# Check translation providerstranslation_factory = self._container.resolve(type(self._container._get_translation_factory()))try:1 unmodified lineavailability['translation']['nllb'] = Trueexcept Exception:availability['translation']['nllb'] = Falsereturn availabilityexcept Exception as e:logger.error(f"Failed to check provider availability: {e}")raise ConfigurationException(f"Failed to check provider availability: {str(e)}")37 unmodified lines'processing': [],'logging': []}try:# Validate TTS configurationtts_config = self._config.get_tts_config()if not (0.1 <= tts_config['default_speed'] <= 3.0):issues['tts'].append(f"Invalid default_speed: {tts_config['default_speed']}")if tts_config['max_text_length'] <= 0:issues['tts'].append(f"Invalid max_text_length: {tts_config['max_text_length']}")# Validate STT configurationstt_config = self._config.get_stt_config()if stt_config['chunk_length_s'] <= 0:issues['stt'].append(f"Invalid chunk_length_s: {stt_config['chunk_length_s']}")if stt_config['batch_size'] <= 0:issues['stt'].append(f"Invalid batch_size: {stt_config['batch_size']}")# Validate processing configurationprocessing_config = self._config.get_processing_config()if not os.path.exists(processing_config['temp_dir']):issues['processing'].append(f"Temp directory does not exist: {processing_config['temp_dir']}")if processing_config['max_file_size_mb'] <= 0:issues['processing'].append(f"Invalid max_file_size_mb: {processing_config['max_file_size_mb']}")# Validate logging configurationlogging_config = self._config.get_logging_config()valid_levels = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']if logging_config['level'].upper() not in valid_levels:issues['logging'].append(f"Invalid log level: {logging_config['level']}")except Exception as e:issues['general'] = [f"Configuration validation error: {str(e)}"]return issuesdef reset_to_defaults(self) -> Dict[str, Any]:9 unmodified linestry:# Create new config with defaultsdefault_config = AppConfig()# Update current configself._config = default_config# Update container with new configself._container.register_singleton(AppConfig, default_config)logger.info("Configuration reset to defaults")return self.get_current_configuration()except Exception as e:logger.error(f"Failed to reset configuration: {e}")raise ConfigurationException(f"Failed to reset configuration: {str(e)}")
1"""Tests for application error handling."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155"""Tests for error mapper functionality."""
import pytestfrom unittest.mock import Mock
from src.application.error_handling.error_mapper import ( ErrorMapper, ErrorMapping, ErrorSeverity, ErrorCategory)from src.domain.exceptions import ( InvalidAudioFormatException, TranslationFailedException, SpeechRecognitionException, SpeechSynthesisException)
class TestErrorMapper: """Test cases for ErrorMapper."""
def setup_method(self): """Set up test fixtures.""" self.error_mapper = ErrorMapper()
def test_map_domain_exception(self): """Test mapping of domain exceptions.""" exception = InvalidAudioFormatException("Unsupported format: xyz") context = { 'file_name': 'test.xyz', 'correlation_id': 'test-123' }
mapping = self.error_mapper.map_exception(exception, context)
assert mapping.error_code == "INVALID_AUDIO_FORMAT" assert mapping.severity == ErrorSeverity.MEDIUM assert mapping.category == ErrorCategory.VALIDATION assert "supported format" in mapping.user_message.lower() assert len(mapping.recovery_suggestions) > 0
def test_map_translation_exception(self): """Test mapping of translation exceptions.""" exception = TranslationFailedException("Translation service unavailable")
mapping = self.error_mapper.map_exception(exception)
assert mapping.error_code == "TRANSLATION_FAILED" assert mapping.severity == ErrorSeverity.HIGH assert mapping.category == ErrorCategory.PROCESSING assert "translation failed" in mapping.user_message.lower()
def test_map_speech_recognition_exception(self): """Test mapping of speech recognition exceptions.""" exception = SpeechRecognitionException("Audio quality too poor") context = {'provider': 'whisper'}
mapping = self.error_mapper.map_exception(exception, context)
assert mapping.error_code == "SPEECH_RECOGNITION_FAILED" assert mapping.severity == ErrorSeverity.HIGH assert mapping.category == ErrorCategory.PROCESSING assert any("whisper" in suggestion for suggestion in mapping.recovery_suggestions)
def test_map_speech_synthesis_exception(self): """Test mapping of speech synthesis exceptions.""" exception = SpeechSynthesisException("Voice not available")
mapping = self.error_mapper.map_exception(exception)
assert mapping.error_code == "SPEECH_SYNTHESIS_FAILED" assert mapping.severity == ErrorSeverity.HIGH assert mapping.category == ErrorCategory.PROCESSING
def test_map_unknown_exception(self): """Test mapping of unknown exceptions.""" exception = RuntimeError("Unknown error")
mapping = self.error_mapper.map_exception(exception)
assert mapping.error_code == "UNKNOWN_ERROR" assert mapping.severity == ErrorSeverity.CRITICAL assert mapping.category == ErrorCategory.SYSTEM
def test_context_enhancement(self): """Test context enhancement of error mappings.""" exception = ValueError("Invalid parameter") context = { 'file_name': 'large_file.wav', 'file_size': 100 * 1024 * 1024, # 100MB 'correlation_id': 'test-456', 'operation': 'audio_processing' }
mapping = self.error_mapper.map_exception(exception, context)
assert 'large_file.wav' in mapping.user_message assert 'test-456' in mapping.technical_details assert any("smaller file" in suggestion for suggestion in mapping.recovery_suggestions)
def test_get_error_code_from_exception(self): """Test getting error code from exception.""" exception = TranslationFailedException("Test error")
error_code = self.error_mapper.get_error_code_from_exception(exception)
assert error_code == "TRANSLATION_FAILED"
def test_get_user_message_from_exception(self): """Test getting user message from exception.""" exception = InvalidAudioFormatException("Test error")
message = self.error_mapper.get_user_message_from_exception(exception)
assert "supported" in message.lower() assert "format" in message.lower()
def test_get_recovery_suggestions(self): """Test getting recovery suggestions.""" exception = SpeechRecognitionException("Test error")
suggestions = self.error_mapper.get_recovery_suggestions(exception)
assert len(suggestions) > 0 assert any("audio quality" in suggestion.lower() for suggestion in suggestions)
def test_add_custom_mapping(self): """Test adding custom error mapping.""" custom_mapping = ErrorMapping( user_message="Custom error message", error_code="CUSTOM_ERROR", severity=ErrorSeverity.LOW, category=ErrorCategory.VALIDATION )
self.error_mapper.add_custom_mapping(CustomException, custom_mapping)
exception = CustomException("Test") mapping = self.error_mapper.map_exception(exception)
assert mapping.error_code == "CUSTOM_ERROR" assert mapping.user_message == "Custom error message"
def test_get_all_error_codes(self): """Test getting all error codes.""" error_codes = self.error_mapper.get_all_error_codes()
assert "INVALID_AUDIO_FORMAT" in error_codes assert "TRANSLATION_FAILED" in error_codes assert "SPEECH_RECOGNITION_FAILED" in error_codes assert "SPEECH_SYNTHESIS_FAILED" in error_codes assert "UNKNOWN_ERROR" in error_codes
class CustomException(Exception): """Custom exception for testing.""" pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298"""Tests for structured logger functionality."""
import pytestimport jsonimport loggingfrom unittest.mock import Mock, patch
from src.application.error_handling.structured_logger import ( StructuredLogger, LogContext, JsonFormatter, ContextFormatter, get_structured_logger, set_correlation_id, get_correlation_id, generate_correlation_id)
class TestLogContext: """Test cases for LogContext."""
def test_log_context_creation(self): """Test creating log context.""" context = LogContext( correlation_id="test-123", operation="test_operation", component="test_component" )
assert context.correlation_id == "test-123" assert context.operation == "test_operation" assert context.component == "test_component"
def test_log_context_to_dict(self): """Test converting log context to dictionary.""" context = LogContext( correlation_id="test-123", operation="test_operation", metadata={"key": "value"} )
context_dict = context.to_dict()
assert context_dict["correlation_id"] == "test-123" assert context_dict["operation"] == "test_operation" assert context_dict["metadata"] == {"key": "value"} assert "user_id" not in context_dict # None values should be excluded
class TestStructuredLogger: """Test cases for StructuredLogger."""
def setup_method(self): """Set up test fixtures.""" self.logger = StructuredLogger("test_logger", enable_json_logging=False)
def test_logger_creation(self): """Test creating structured logger.""" assert self.logger.logger.name == "test_logger" assert not self.logger.enable_json_logging
def test_debug_logging(self): """Test debug logging.""" context = LogContext(correlation_id="test-123", operation="test_op")
with patch.object(self.logger.logger, 'debug') as mock_debug: self.logger.debug("Test debug message", context=context)
mock_debug.assert_called_once() args, kwargs = mock_debug.call_args assert "Test debug message" in args[0] assert "extra" in kwargs
def test_info_logging(self): """Test info logging.""" context = LogContext(correlation_id="test-123") extra = {"key": "value"}
with patch.object(self.logger.logger, 'info') as mock_info: self.logger.info("Test info message", context=context, extra=extra)
mock_info.assert_called_once() args, kwargs = mock_info.call_args assert "Test info message" in args[0] assert kwargs["extra"]["extra"] == extra
def test_error_logging_with_exception(self): """Test error logging with exception.""" context = LogContext(correlation_id="test-123") exception = ValueError("Test error")
with patch.object(self.logger.logger, 'error') as mock_error: self.logger.error("Test error message", context=context, exception=exception)
mock_error.assert_called_once() args, kwargs = mock_error.call_args assert "Test error message" in args[0] assert kwargs["extra"]["exception"]["type"] == "ValueError" assert kwargs["extra"]["exception"]["message"] == "Test error"
def test_log_operation_start(self): """Test logging operation start.""" extra = {"param": "value"}
with patch.object(self.logger.logger, 'info') as mock_info: correlation_id = self.logger.log_operation_start("test_operation", extra=extra)
assert correlation_id is not None mock_info.assert_called_once() args, kwargs = mock_info.call_args assert "Operation started: test_operation" in args[0]
def test_log_operation_end_success(self): """Test logging successful operation end.""" correlation_id = "test-123"
with patch.object(self.logger.logger, 'info') as mock_info: self.logger.log_operation_end( "test_operation", correlation_id, success=True, duration=1.5 )
mock_info.assert_called_once() args, kwargs = mock_info.call_args assert "completed successfully" in args[0] assert kwargs["extra"]["extra"]["success"] is True assert kwargs["extra"]["extra"]["duration_seconds"] == 1.5
def test_log_operation_end_failure(self): """Test logging failed operation end.""" correlation_id = "test-123"
with patch.object(self.logger.logger, 'error') as mock_error: self.logger.log_operation_end( "test_operation", correlation_id, success=False )
mock_error.assert_called_once() args, kwargs = mock_error.call_args assert "failed" in args[0] assert kwargs["extra"]["extra"]["success"] is False
def test_log_performance_metric(self): """Test logging performance metric.""" context = LogContext(correlation_id="test-123")
with patch.object(self.logger.logger, 'info') as mock_info: self.logger.log_performance_metric( "response_time", 150.5, "ms", context=context )
mock_info.assert_called_once() args, kwargs = mock_info.call_args assert "Performance metric: response_time=150.5 ms" in args[0] assert kwargs["extra"]["extra"]["metric"]["name"] == "response_time" assert kwargs["extra"]["extra"]["metric"]["value"] == 150.5 assert kwargs["extra"]["extra"]["metric"]["unit"] == "ms"
class TestJsonFormatter: """Test cases for JsonFormatter."""
def setup_method(self): """Set up test fixtures.""" self.formatter = JsonFormatter()
def test_format_log_record(self): """Test formatting log record as JSON.""" record = logging.LogRecord( name="test_logger", level=logging.INFO, pathname="test.py", lineno=10, msg="Test message", args=(), exc_info=None )
# Add extra data record.extra = { "correlation_id": "test-123", "operation": "test_op" }
formatted = self.formatter.format(record)
# Should be valid JSON log_data = json.loads(formatted) assert log_data["message"] == "Test message" assert log_data["level"] == "INFO" assert log_data["correlation_id"] == "test-123" assert log_data["operation"] == "test_op"
def test_format_error_handling(self): """Test formatter error handling.""" record = logging.LogRecord( name="test_logger", level=logging.INFO, pathname="test.py", lineno=10, msg="Test message", args=(), exc_info=None )
# Add problematic extra data that can't be JSON serialized record.extra = { "correlation_id": "test-123", "problematic_data": object() # Can't be JSON serialized }
formatted = self.formatter.format(record)
# Should still work and include error message assert "Test message" in formatted
class TestContextFormatter: """Test cases for ContextFormatter."""
def setup_method(self): """Set up test fixtures.""" self.formatter = ContextFormatter()
def test_format_with_correlation_id(self): """Test formatting with correlation ID.""" record = logging.LogRecord( name="test_logger", level=logging.INFO, pathname="test.py", lineno=10, msg="Test message", args=(), exc_info=None )
record.extra = {"correlation_id": "test-123"}
formatted = self.formatter.format(record)
assert "[test-123]" in formatted assert "Test message" in formatted
def test_format_with_operation(self): """Test formatting with operation context.""" record = logging.LogRecord( name="test_logger", level=logging.INFO, pathname="test.py", lineno=10, msg="Test message", args=(), exc_info=None )
record.extra = { "correlation_id": "test-123", "operation": "test_operation" }
formatted = self.formatter.format(record)
assert "[test_operation]" in formatted assert "Test message" in formatted
class TestUtilityFunctions: """Test cases for utility functions."""
def test_get_structured_logger(self): """Test getting structured logger.""" logger = get_structured_logger("test_logger")
assert isinstance(logger, StructuredLogger) assert logger.logger.name == "test_logger"
def test_correlation_id_context(self): """Test correlation ID context management.""" # Initially should be None assert get_correlation_id() is None
# Set correlation ID set_correlation_id("test-123") assert get_correlation_id() == "test-123"
def test_generate_correlation_id(self): """Test generating correlation ID.""" correlation_id = generate_correlation_id()
assert correlation_id is not None assert len(correlation_id) > 0
# Should generate different IDs another_id = generate_correlation_id() assert correlation_id != another_idsrc/application/error_handling/__init__.pyAdded+1
src/application/error_handling/error_mapper.pyAdded+375
src/application/error_handling/recovery_manager.pyAdded+508
src/application/error_handling/structured_logger.pyAdded+362
src/application/services/audio_processing_service.py+365-95
src/application/services/configuration_service.py+72-67
tests/unit/application/error_handling/__init__.pyAdded+1
tests/unit/application/error_handling/test_error_mapper.pyAdded+155
tests/unit/application/error_handling/test_structured_logger.pyAdded+298