Spaces:
Runtime error
Runtime error
Michael Hu commited on
Commit ·
1d177ae
1
Parent(s): 0c2d9e7
attempt fix
Browse filesFiles changed (2)
7 unmodified lines8910111213146 unmodified lines212223242526271 unmodified line2930313233343536373839404142432 unmodified lines46474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929310 unmodified lines1041051061071081091101111125 unmodified lines1181191201211221231245 unmodified lines1301311321331341351361371381391401411421437 unmodified lines@dataclassclass ProcessingResultDto:"""DTO for pipeline output dataContains the results of processing audio through theSTT -> Translation -> TTS pipeline."""6 unmodified lineserror_code: Optional[str] = Nonemetadata: Optional[Dict[str, Any]] = Nonetimestamp: Optional[datetime] = Nonedef __post_init__(self):"""Validate and set defaults after initialization"""self._validate()1 unmodified lineself.metadata = {}if self.timestamp is None:self.timestamp = datetime.utcnow()def _validate(self):"""Validate processing result data"""if not isinstance(self.success, bool):raise ValueError("Success must be a boolean value")if self.processing_time < 0:raise ValueError("Processing time cannot be negative")if self.success:# For successful processing, we should have some outputif not self.original_text and not self.translated_text and not self.audio_path:2 unmodified lines# For failed processing, we should have an error messageif not self.error_message:raise ValueError("Failed processing must include an error message")# Validate error code format if providedif self.error_code:valid_error_codes = ['STT_ERROR', 'TRANSLATION_ERROR', 'TTS_ERROR','AUDIO_FORMAT_ERROR', 'VALIDATION_ERROR', 'SYSTEM_ERROR','UNKNOWN_ERROR' # Add missing error code for unexpected errors]if self.error_code not in valid_error_codes:raise ValueError(f"Invalid error code: {self.error_code}. Valid codes: {valid_error_codes}")# Validate metadata if providedif self.metadata and not isinstance(self.metadata, dict):raise ValueError("Metadata must be a dictionary")@propertydef has_text_output(self) -> bool:"""Check if result has text output"""return bool(self.original_text or self.translated_text)@propertydef has_audio_output(self) -> bool:"""Check if result has audio output"""return bool(self.audio_path)@propertydef is_complete(self) -> bool:"""Check if processing is complete (success or failure with error)"""return self.success or bool(self.error_message)def add_metadata(self, key: str, value: Any) -> None:"""Add metadata entry"""if self.metadata is None:self.metadata = {}self.metadata[key] = valuedef get_metadata(self, key: str, default: Any = None) -> Any:"""Get metadata value"""if self.metadata is None:return defaultreturn self.metadata.get(key, default)def to_dict(self) -> dict:"""Convert to dictionary representation"""return {10 unmodified lines'has_audio_output': self.has_audio_output,'is_complete': self.is_complete}@classmethoddef success_result(cls, original_text: str = None, translated_text: str = None,audio_path: str = None, processing_time: float = 0.0,metadata: Dict[str, Any] = None) -> 'ProcessingResultDto':"""Create a successful processing result"""5 unmodified linesprocessing_time=processing_time,metadata=metadata)@classmethoddef error_result(cls, error_message: str, error_code: str = None,processing_time: float = 0.0, metadata: Dict[str, Any] = None) -> 'ProcessingResultDto':5 unmodified linesprocessing_time=processing_time,metadata=metadata)@classmethoddef from_dict(cls, data: dict) -> 'ProcessingResultDto':"""Create instance from dictionary"""timestamp = Noneif data.get('timestamp'):timestamp = datetime.fromisoformat(data['timestamp'].replace('Z', '+00:00'))return cls(success=data['success'],original_text=data.get('original_text'),7 unmodified lines8910111213146 unmodified lines212223242526271 unmodified line2930313233343536373839404142432 unmodified lines4647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939410 unmodified lines1051061071081091101111121135 unmodified lines1191201211221231241255 unmodified lines1311321331341351361371381391401411421431447 unmodified lines@dataclassclass ProcessingResultDto:"""DTO for pipeline output dataContains the results of processing audio through theSTT -> Translation -> TTS pipeline."""6 unmodified lineserror_code: Optional[str] = Nonemetadata: Optional[Dict[str, Any]] = Nonetimestamp: Optional[datetime] = Nonedef __post_init__(self):"""Validate and set defaults after initialization"""self._validate()1 unmodified lineself.metadata = {}if self.timestamp is None:self.timestamp = datetime.utcnow()def _validate(self):"""Validate processing result data"""if not isinstance(self.success, bool):raise ValueError("Success must be a boolean value")if self.processing_time < 0:raise ValueError("Processing time cannot be negative")if self.success:# For successful processing, we should have some outputif not self.original_text and not self.translated_text and not self.audio_path:2 unmodified lines# For failed processing, we should have an error messageif not self.error_message:raise ValueError("Failed processing must include an error message")# Validate error code format if providedif self.error_code:valid_error_codes = ['STT_ERROR', 'TRANSLATION_ERROR', 'TTS_ERROR','AUDIO_FORMAT_ERROR', 'VALIDATION_ERROR', 'SYSTEM_ERROR','TYPE_ERROR', 'TIMEOUT_ERROR', 'PERMISSION_ERROR', 'MEMORY_ERROR','UNKNOWN_ERROR' # Add missing error code for unexpected errors]if self.error_code not in valid_error_codes:raise ValueError(f"Invalid error code: {self.error_code}. Valid codes: {valid_error_codes}")# Validate metadata if providedif self.metadata and not isinstance(self.metadata, dict):raise ValueError("Metadata must be a dictionary")@propertydef has_text_output(self) -> bool:"""Check if result has text output"""return bool(self.original_text or self.translated_text)@propertydef has_audio_output(self) -> bool:"""Check if result has audio output"""return bool(self.audio_path)@propertydef is_complete(self) -> bool:"""Check if processing is complete (success or failure with error)"""return self.success or bool(self.error_message)def add_metadata(self, key: str, value: Any) -> None:"""Add metadata entry"""if self.metadata is None:self.metadata = {}self.metadata[key] = valuedef get_metadata(self, key: str, default: Any = None) -> Any:"""Get metadata value"""if self.metadata is None:return defaultreturn self.metadata.get(key, default)def to_dict(self) -> dict:"""Convert to dictionary representation"""return {10 unmodified lines'has_audio_output': self.has_audio_output,'is_complete': self.is_complete}@classmethoddef success_result(cls, original_text: str = None, translated_text: str = None,audio_path: str = None, processing_time: float = 0.0,metadata: Dict[str, Any] = None) -> 'ProcessingResultDto':"""Create a successful processing result"""5 unmodified linesprocessing_time=processing_time,metadata=metadata)@classmethoddef error_result(cls, error_message: str, error_code: str = None,processing_time: float = 0.0, metadata: Dict[str, Any] = None) -> 'ProcessingResultDto':5 unmodified linesprocessing_time=processing_time,metadata=metadata)@classmethoddef from_dict(cls, data: dict) -> 'ProcessingResultDto':"""Create instance from dictionary"""timestamp = Noneif data.get('timestamp'):timestamp = datetime.fromisoformat(data['timestamp'].replace('Z', '+00:00'))return cls(success=data['success'],original_text=data.get('original_text'),
694 unmodified lines69569669769869970070117 unmodified lines71972072172272372472535 unmodified lines76176276376476576676738 unmodified lines8068078088098108118128138148158168178188197 unmodified lines8278288298308318328337 unmodified lines841842843844845846847694 unmodified linesretryable_exceptions=[SpeechRecognitionException, ConnectionError, TimeoutError])def stt_operation():return self._perform_speech_recognition(audio, model, correlation_id)try:17 unmodified lines)fallback_funcs = [lambda m=fallback_model: self._perform_speech_recognition(audio, m, correlation_id)for fallback_model in fallback_models]35 unmodified linesretryable_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(38 unmodified lineslogger.info(f"Parameters: voice={voice}, speed={speed}, language={language}")logger.info(f"Text type: {type(text)}, Text content type: {type(text.text) if hasattr(text, 'text') else 'N/A'}")def tts_operation():logger.info(f"Executing TTS operation [correlation_id={correlation_id}]")try:result = self._perform_speech_synthesis(text, voice, speed, language, temp_dir, correlation_id)logger.info(f"TTS operation completed successfully [correlation_id={correlation_id}]")return resultexcept Exception as e:logger.error(f"TTS operation failed: {str(e)} [correlation_id={correlation_id}]", exc_info=True)raisetry:7 unmodified lines)except Exception as e:logger.error(f"Primary TTS failed, trying fallbacks: {str(e)} [correlation_id={correlation_id}]", exc_info=True)# Try fallback TTS providerstts_config = self._config.get_tts_config()7 unmodified lines)fallback_funcs = [lambda v=fallback_voice: self._perform_speech_synthesis(text, v, speed, language, temp_dir, correlation_id)for fallback_voice in fallback_voices694 unmodified lines69569669769869970070117 unmodified lines71972072172272372472535 unmodified lines76176276376476576676738 unmodified lines8068078088098108118128138148158168178188197 unmodified lines8278288298308318328337 unmodified lines841842843844845846847694 unmodified linesretryable_exceptions=[SpeechRecognitionException, ConnectionError, TimeoutError])def stt_operation(*args, **kwargs):return self._perform_speech_recognition(audio, model, correlation_id)try:17 unmodified lines)fallback_funcs = [lambda *args, m=fallback_model, **kwargs: self._perform_speech_recognition(audio, m, correlation_id)for fallback_model in fallback_models]35 unmodified linesretryable_exceptions=[TranslationFailedException, ConnectionError, TimeoutError])def translation_operation(*args, **kwargs):return self._perform_translation(text, source_language, target_language, correlation_id)return self._recovery_manager.retry_with_backoff(38 unmodified lineslogger.info(f"Parameters: voice={voice}, speed={speed}, language={language}")logger.info(f"Text type: {type(text)}, Text content type: {type(text.text) if hasattr(text, 'text') else 'N/A'}")def tts_operation(*args, **kwargs):logger.info(f"Executing TTS operation [correlation_id={correlation_id}]")try:result = self._perform_speech_synthesis(text, voice, speed, language, temp_dir, correlation_id)logger.info(f"TTS operation completed successfully [correlation_id={correlation_id}]")return resultexcept Exception as e:logger.error(f"TTS operation failed: {str(e)} [correlation_id={correlation_id}]")raisetry:7 unmodified lines)except Exception as e:logger.error(f"Primary TTS failed, trying fallbacks: {str(e)} [correlation_id={correlation_id}]", context=context, exception=e)# Try fallback TTS providerstts_config = self._config.get_tts_config()7 unmodified lines)fallback_funcs = [lambda *args, v=fallback_voice, **kwargs: self._perform_speech_synthesis(text, v, speed, language, temp_dir, correlation_id)for fallback_voice in fallback_voices
src/application/dtos/processing_result_dto.py+19-18
src/application/services/audio_processing_service.py+7-7