Spaces:
Sleeping
Sleeping
Michael Hu
commited on
Commit
·
1d177ae
1
Parent(s):
0c2d9e7
attempt fix
Browse files
src/application/dtos/processing_result_dto.py
CHANGED
|
@@ -8,7 +8,7 @@ from datetime import datetime
|
|
| 8 |
@dataclass
|
| 9 |
class ProcessingResultDto:
|
| 10 |
"""DTO for pipeline output data
|
| 11 |
-
|
| 12 |
Contains the results of processing audio through the
|
| 13 |
STT -> Translation -> TTS pipeline.
|
| 14 |
"""
|
|
@@ -21,7 +21,7 @@ class ProcessingResultDto:
|
|
| 21 |
error_code: Optional[str] = None
|
| 22 |
metadata: Optional[Dict[str, Any]] = None
|
| 23 |
timestamp: Optional[datetime] = None
|
| 24 |
-
|
| 25 |
def __post_init__(self):
|
| 26 |
"""Validate and set defaults after initialization"""
|
| 27 |
self._validate()
|
|
@@ -29,15 +29,15 @@ class ProcessingResultDto:
|
|
| 29 |
self.metadata = {}
|
| 30 |
if self.timestamp is None:
|
| 31 |
self.timestamp = datetime.utcnow()
|
| 32 |
-
|
| 33 |
def _validate(self):
|
| 34 |
"""Validate processing result data"""
|
| 35 |
if not isinstance(self.success, bool):
|
| 36 |
raise ValueError("Success must be a boolean value")
|
| 37 |
-
|
| 38 |
if self.processing_time < 0:
|
| 39 |
raise ValueError("Processing time cannot be negative")
|
| 40 |
-
|
| 41 |
if self.success:
|
| 42 |
# For successful processing, we should have some output
|
| 43 |
if not self.original_text and not self.translated_text and not self.audio_path:
|
|
@@ -46,48 +46,49 @@ class ProcessingResultDto:
|
|
| 46 |
# For failed processing, we should have an error message
|
| 47 |
if not self.error_message:
|
| 48 |
raise ValueError("Failed processing must include an error message")
|
| 49 |
-
|
| 50 |
# Validate error code format if provided
|
| 51 |
if self.error_code:
|
| 52 |
valid_error_codes = [
|
| 53 |
'STT_ERROR', 'TRANSLATION_ERROR', 'TTS_ERROR',
|
| 54 |
'AUDIO_FORMAT_ERROR', 'VALIDATION_ERROR', 'SYSTEM_ERROR',
|
|
|
|
| 55 |
'UNKNOWN_ERROR' # Add missing error code for unexpected errors
|
| 56 |
]
|
| 57 |
if self.error_code not in valid_error_codes:
|
| 58 |
raise ValueError(f"Invalid error code: {self.error_code}. Valid codes: {valid_error_codes}")
|
| 59 |
-
|
| 60 |
# Validate metadata if provided
|
| 61 |
if self.metadata and not isinstance(self.metadata, dict):
|
| 62 |
raise ValueError("Metadata must be a dictionary")
|
| 63 |
-
|
| 64 |
@property
|
| 65 |
def has_text_output(self) -> bool:
|
| 66 |
"""Check if result has text output"""
|
| 67 |
return bool(self.original_text or self.translated_text)
|
| 68 |
-
|
| 69 |
@property
|
| 70 |
def has_audio_output(self) -> bool:
|
| 71 |
"""Check if result has audio output"""
|
| 72 |
return bool(self.audio_path)
|
| 73 |
-
|
| 74 |
@property
|
| 75 |
def is_complete(self) -> bool:
|
| 76 |
"""Check if processing is complete (success or failure with error)"""
|
| 77 |
return self.success or bool(self.error_message)
|
| 78 |
-
|
| 79 |
def add_metadata(self, key: str, value: Any) -> None:
|
| 80 |
"""Add metadata entry"""
|
| 81 |
if self.metadata is None:
|
| 82 |
self.metadata = {}
|
| 83 |
self.metadata[key] = value
|
| 84 |
-
|
| 85 |
def get_metadata(self, key: str, default: Any = None) -> Any:
|
| 86 |
"""Get metadata value"""
|
| 87 |
if self.metadata is None:
|
| 88 |
return default
|
| 89 |
return self.metadata.get(key, default)
|
| 90 |
-
|
| 91 |
def to_dict(self) -> dict:
|
| 92 |
"""Convert to dictionary representation"""
|
| 93 |
return {
|
|
@@ -104,9 +105,9 @@ class ProcessingResultDto:
|
|
| 104 |
'has_audio_output': self.has_audio_output,
|
| 105 |
'is_complete': self.is_complete
|
| 106 |
}
|
| 107 |
-
|
| 108 |
@classmethod
|
| 109 |
-
def success_result(cls, original_text: str = None, translated_text: str = None,
|
| 110 |
audio_path: str = None, processing_time: float = 0.0,
|
| 111 |
metadata: Dict[str, Any] = None) -> 'ProcessingResultDto':
|
| 112 |
"""Create a successful processing result"""
|
|
@@ -118,7 +119,7 @@ class ProcessingResultDto:
|
|
| 118 |
processing_time=processing_time,
|
| 119 |
metadata=metadata
|
| 120 |
)
|
| 121 |
-
|
| 122 |
@classmethod
|
| 123 |
def error_result(cls, error_message: str, error_code: str = None,
|
| 124 |
processing_time: float = 0.0, metadata: Dict[str, Any] = None) -> 'ProcessingResultDto':
|
|
@@ -130,14 +131,14 @@ class ProcessingResultDto:
|
|
| 130 |
processing_time=processing_time,
|
| 131 |
metadata=metadata
|
| 132 |
)
|
| 133 |
-
|
| 134 |
@classmethod
|
| 135 |
def from_dict(cls, data: dict) -> 'ProcessingResultDto':
|
| 136 |
"""Create instance from dictionary"""
|
| 137 |
timestamp = None
|
| 138 |
if data.get('timestamp'):
|
| 139 |
timestamp = datetime.fromisoformat(data['timestamp'].replace('Z', '+00:00'))
|
| 140 |
-
|
| 141 |
return cls(
|
| 142 |
success=data['success'],
|
| 143 |
original_text=data.get('original_text'),
|
|
|
|
| 8 |
@dataclass
|
| 9 |
class ProcessingResultDto:
|
| 10 |
"""DTO for pipeline output data
|
| 11 |
+
|
| 12 |
Contains the results of processing audio through the
|
| 13 |
STT -> Translation -> TTS pipeline.
|
| 14 |
"""
|
|
|
|
| 21 |
error_code: Optional[str] = None
|
| 22 |
metadata: Optional[Dict[str, Any]] = None
|
| 23 |
timestamp: Optional[datetime] = None
|
| 24 |
+
|
| 25 |
def __post_init__(self):
|
| 26 |
"""Validate and set defaults after initialization"""
|
| 27 |
self._validate()
|
|
|
|
| 29 |
self.metadata = {}
|
| 30 |
if self.timestamp is None:
|
| 31 |
self.timestamp = datetime.utcnow()
|
| 32 |
+
|
| 33 |
def _validate(self):
|
| 34 |
"""Validate processing result data"""
|
| 35 |
if not isinstance(self.success, bool):
|
| 36 |
raise ValueError("Success must be a boolean value")
|
| 37 |
+
|
| 38 |
if self.processing_time < 0:
|
| 39 |
raise ValueError("Processing time cannot be negative")
|
| 40 |
+
|
| 41 |
if self.success:
|
| 42 |
# For successful processing, we should have some output
|
| 43 |
if not self.original_text and not self.translated_text and not self.audio_path:
|
|
|
|
| 46 |
# For failed processing, we should have an error message
|
| 47 |
if not self.error_message:
|
| 48 |
raise ValueError("Failed processing must include an error message")
|
| 49 |
+
|
| 50 |
# Validate error code format if provided
|
| 51 |
if self.error_code:
|
| 52 |
valid_error_codes = [
|
| 53 |
'STT_ERROR', 'TRANSLATION_ERROR', 'TTS_ERROR',
|
| 54 |
'AUDIO_FORMAT_ERROR', 'VALIDATION_ERROR', 'SYSTEM_ERROR',
|
| 55 |
+
'TYPE_ERROR', 'TIMEOUT_ERROR', 'PERMISSION_ERROR', 'MEMORY_ERROR',
|
| 56 |
'UNKNOWN_ERROR' # Add missing error code for unexpected errors
|
| 57 |
]
|
| 58 |
if self.error_code not in valid_error_codes:
|
| 59 |
raise ValueError(f"Invalid error code: {self.error_code}. Valid codes: {valid_error_codes}")
|
| 60 |
+
|
| 61 |
# Validate metadata if provided
|
| 62 |
if self.metadata and not isinstance(self.metadata, dict):
|
| 63 |
raise ValueError("Metadata must be a dictionary")
|
| 64 |
+
|
| 65 |
@property
|
| 66 |
def has_text_output(self) -> bool:
|
| 67 |
"""Check if result has text output"""
|
| 68 |
return bool(self.original_text or self.translated_text)
|
| 69 |
+
|
| 70 |
@property
|
| 71 |
def has_audio_output(self) -> bool:
|
| 72 |
"""Check if result has audio output"""
|
| 73 |
return bool(self.audio_path)
|
| 74 |
+
|
| 75 |
@property
|
| 76 |
def is_complete(self) -> bool:
|
| 77 |
"""Check if processing is complete (success or failure with error)"""
|
| 78 |
return self.success or bool(self.error_message)
|
| 79 |
+
|
| 80 |
def add_metadata(self, key: str, value: Any) -> None:
|
| 81 |
"""Add metadata entry"""
|
| 82 |
if self.metadata is None:
|
| 83 |
self.metadata = {}
|
| 84 |
self.metadata[key] = value
|
| 85 |
+
|
| 86 |
def get_metadata(self, key: str, default: Any = None) -> Any:
|
| 87 |
"""Get metadata value"""
|
| 88 |
if self.metadata is None:
|
| 89 |
return default
|
| 90 |
return self.metadata.get(key, default)
|
| 91 |
+
|
| 92 |
def to_dict(self) -> dict:
|
| 93 |
"""Convert to dictionary representation"""
|
| 94 |
return {
|
|
|
|
| 105 |
'has_audio_output': self.has_audio_output,
|
| 106 |
'is_complete': self.is_complete
|
| 107 |
}
|
| 108 |
+
|
| 109 |
@classmethod
|
| 110 |
+
def success_result(cls, original_text: str = None, translated_text: str = None,
|
| 111 |
audio_path: str = None, processing_time: float = 0.0,
|
| 112 |
metadata: Dict[str, Any] = None) -> 'ProcessingResultDto':
|
| 113 |
"""Create a successful processing result"""
|
|
|
|
| 119 |
processing_time=processing_time,
|
| 120 |
metadata=metadata
|
| 121 |
)
|
| 122 |
+
|
| 123 |
@classmethod
|
| 124 |
def error_result(cls, error_message: str, error_code: str = None,
|
| 125 |
processing_time: float = 0.0, metadata: Dict[str, Any] = None) -> 'ProcessingResultDto':
|
|
|
|
| 131 |
processing_time=processing_time,
|
| 132 |
metadata=metadata
|
| 133 |
)
|
| 134 |
+
|
| 135 |
@classmethod
|
| 136 |
def from_dict(cls, data: dict) -> 'ProcessingResultDto':
|
| 137 |
"""Create instance from dictionary"""
|
| 138 |
timestamp = None
|
| 139 |
if data.get('timestamp'):
|
| 140 |
timestamp = datetime.fromisoformat(data['timestamp'].replace('Z', '+00:00'))
|
| 141 |
+
|
| 142 |
return cls(
|
| 143 |
success=data['success'],
|
| 144 |
original_text=data.get('original_text'),
|
src/application/services/audio_processing_service.py
CHANGED
|
@@ -695,7 +695,7 @@ class AudioProcessingApplicationService:
|
|
| 695 |
retryable_exceptions=[SpeechRecognitionException, ConnectionError, TimeoutError]
|
| 696 |
)
|
| 697 |
|
| 698 |
-
def stt_operation():
|
| 699 |
return self._perform_speech_recognition(audio, model, correlation_id)
|
| 700 |
|
| 701 |
try:
|
|
@@ -719,7 +719,7 @@ class AudioProcessingApplicationService:
|
|
| 719 |
)
|
| 720 |
|
| 721 |
fallback_funcs = [
|
| 722 |
-
lambda m=fallback_model: self._perform_speech_recognition(audio, m, correlation_id)
|
| 723 |
for fallback_model in fallback_models
|
| 724 |
]
|
| 725 |
|
|
@@ -761,7 +761,7 @@ class AudioProcessingApplicationService:
|
|
| 761 |
retryable_exceptions=[TranslationFailedException, ConnectionError, TimeoutError]
|
| 762 |
)
|
| 763 |
|
| 764 |
-
def translation_operation():
|
| 765 |
return self._perform_translation(text, source_language, target_language, correlation_id)
|
| 766 |
|
| 767 |
return self._recovery_manager.retry_with_backoff(
|
|
@@ -806,14 +806,14 @@ class AudioProcessingApplicationService:
|
|
| 806 |
logger.info(f"Parameters: voice={voice}, speed={speed}, language={language}")
|
| 807 |
logger.info(f"Text type: {type(text)}, Text content type: {type(text.text) if hasattr(text, 'text') else 'N/A'}")
|
| 808 |
|
| 809 |
-
def tts_operation():
|
| 810 |
logger.info(f"Executing TTS operation [correlation_id={correlation_id}]")
|
| 811 |
try:
|
| 812 |
result = self._perform_speech_synthesis(text, voice, speed, language, temp_dir, correlation_id)
|
| 813 |
logger.info(f"TTS operation completed successfully [correlation_id={correlation_id}]")
|
| 814 |
return result
|
| 815 |
except Exception as e:
|
| 816 |
-
logger.error(f"TTS operation failed: {str(e)} [correlation_id={correlation_id}]"
|
| 817 |
raise
|
| 818 |
|
| 819 |
try:
|
|
@@ -827,7 +827,7 @@ class AudioProcessingApplicationService:
|
|
| 827 |
)
|
| 828 |
|
| 829 |
except Exception as e:
|
| 830 |
-
logger.error(f"Primary TTS failed, trying fallbacks: {str(e)} [correlation_id={correlation_id}]",
|
| 831 |
|
| 832 |
# Try fallback TTS providers
|
| 833 |
tts_config = self._config.get_tts_config()
|
|
@@ -841,7 +841,7 @@ class AudioProcessingApplicationService:
|
|
| 841 |
)
|
| 842 |
|
| 843 |
fallback_funcs = [
|
| 844 |
-
lambda v=fallback_voice: self._perform_speech_synthesis(
|
| 845 |
text, v, speed, language, temp_dir, correlation_id
|
| 846 |
)
|
| 847 |
for fallback_voice in fallback_voices
|
|
|
|
| 695 |
retryable_exceptions=[SpeechRecognitionException, ConnectionError, TimeoutError]
|
| 696 |
)
|
| 697 |
|
| 698 |
+
def stt_operation(*args, **kwargs):
|
| 699 |
return self._perform_speech_recognition(audio, model, correlation_id)
|
| 700 |
|
| 701 |
try:
|
|
|
|
| 719 |
)
|
| 720 |
|
| 721 |
fallback_funcs = [
|
| 722 |
+
lambda *args, m=fallback_model, **kwargs: self._perform_speech_recognition(audio, m, correlation_id)
|
| 723 |
for fallback_model in fallback_models
|
| 724 |
]
|
| 725 |
|
|
|
|
| 761 |
retryable_exceptions=[TranslationFailedException, ConnectionError, TimeoutError]
|
| 762 |
)
|
| 763 |
|
| 764 |
+
def translation_operation(*args, **kwargs):
|
| 765 |
return self._perform_translation(text, source_language, target_language, correlation_id)
|
| 766 |
|
| 767 |
return self._recovery_manager.retry_with_backoff(
|
|
|
|
| 806 |
logger.info(f"Parameters: voice={voice}, speed={speed}, language={language}")
|
| 807 |
logger.info(f"Text type: {type(text)}, Text content type: {type(text.text) if hasattr(text, 'text') else 'N/A'}")
|
| 808 |
|
| 809 |
+
def tts_operation(*args, **kwargs):
|
| 810 |
logger.info(f"Executing TTS operation [correlation_id={correlation_id}]")
|
| 811 |
try:
|
| 812 |
result = self._perform_speech_synthesis(text, voice, speed, language, temp_dir, correlation_id)
|
| 813 |
logger.info(f"TTS operation completed successfully [correlation_id={correlation_id}]")
|
| 814 |
return result
|
| 815 |
except Exception as e:
|
| 816 |
+
logger.error(f"TTS operation failed: {str(e)} [correlation_id={correlation_id}]")
|
| 817 |
raise
|
| 818 |
|
| 819 |
try:
|
|
|
|
| 827 |
)
|
| 828 |
|
| 829 |
except Exception as e:
|
| 830 |
+
logger.error(f"Primary TTS failed, trying fallbacks: {str(e)} [correlation_id={correlation_id}]", context=context, exception=e)
|
| 831 |
|
| 832 |
# Try fallback TTS providers
|
| 833 |
tts_config = self._config.get_tts_config()
|
|
|
|
| 841 |
)
|
| 842 |
|
| 843 |
fallback_funcs = [
|
| 844 |
+
lambda *args, v=fallback_voice, **kwargs: self._perform_speech_synthesis(
|
| 845 |
text, v, speed, language, temp_dir, correlation_id
|
| 846 |
)
|
| 847 |
for fallback_voice in fallback_voices
|