Spaces:
Build error
Build error
File size: 25,324 Bytes
8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 fdc056d 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 fdc056d 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 fdc056d 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 fdc056d 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6825e46 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6825e46 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 6613cd9 8a0c4b0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 |
"""Configuration Application Service for settings management."""
import logging
import os
import json
from typing import Dict, List, Any, Optional, Union
from pathlib import Path
from dataclasses import asdict
from ..error_handling.error_mapper import ErrorMapper
from ..error_handling.structured_logger import StructuredLogger, LogContext, get_structured_logger
from ...infrastructure.config.app_config import AppConfig, TTSConfig, STTConfig, TranslationConfig, ProcessingConfig, LoggingConfig
from ...infrastructure.config.dependency_container import DependencyContainer
from ...domain.exceptions import DomainException
logger = get_structured_logger(__name__)
class ConfigurationException(DomainException):
"""Exception raised for configuration-related errors."""
pass
class ConfigurationApplicationService:
"""Application service for managing application configuration and settings."""
def __init__(
self,
container: DependencyContainer,
config: Optional[AppConfig] = None
):
"""
Initialize the configuration application service.
Args:
container: Dependency injection container
config: Application configuration (optional, will be resolved from container)
"""
self._container = container
self._config = config or container.resolve(AppConfig)
# Initialize error handling
self._error_mapper = ErrorMapper()
logger.info("ConfigurationApplicationService initialized")
def get_current_configuration(self) -> Dict[str, Any]:
"""
Get the current application configuration.
Returns:
Dict[str, Any]: Current configuration as dictionary
"""
try:
return {
'tts': self._config.get_tts_config(),
'stt': self._config.get_stt_config(),
'translation': self._config.get_translation_config(),
'processing': self._config.get_processing_config(),
'logging': self._config.get_logging_config()
}
except Exception as e:
logger.error(f"Failed to get current configuration: {e}")
raise ConfigurationException(f"Failed to retrieve configuration: {str(e)}")
def get_tts_configuration(self) -> Dict[str, Any]:
"""
Get TTS-specific configuration.
Returns:
Dict[str, Any]: TTS configuration
"""
try:
return self._config.get_tts_config()
except Exception as e:
logger.error(f"Failed to get TTS configuration: {e}")
raise ConfigurationException(f"Failed to retrieve TTS configuration: {str(e)}")
def get_stt_configuration(self) -> Dict[str, Any]:
"""
Get STT-specific configuration.
Returns:
Dict[str, Any]: STT configuration
"""
try:
return self._config.get_stt_config()
except Exception as e:
logger.error(f"Failed to get STT configuration: {e}")
raise ConfigurationException(f"Failed to retrieve STT configuration: {str(e)}")
def get_translation_configuration(self) -> Dict[str, Any]:
"""
Get translation-specific configuration.
Returns:
Dict[str, Any]: Translation configuration
"""
try:
return self._config.get_translation_config()
except Exception as e:
logger.error(f"Failed to get translation configuration: {e}")
raise ConfigurationException(f"Failed to retrieve translation configuration: {str(e)}")
def get_processing_configuration(self) -> Dict[str, Any]:
"""
Get processing-specific configuration.
Returns:
Dict[str, Any]: Processing configuration
"""
try:
return self._config.get_processing_config()
except Exception as e:
logger.error(f"Failed to get processing configuration: {e}")
raise ConfigurationException(f"Failed to retrieve processing configuration: {str(e)}")
def get_logging_configuration(self) -> Dict[str, Any]:
"""
Get logging-specific configuration.
Returns:
Dict[str, Any]: Logging configuration
"""
try:
return self._config.get_logging_config()
except Exception as e:
logger.error(f"Failed to get logging configuration: {e}")
raise ConfigurationException(f"Failed to retrieve logging configuration: {str(e)}")
def update_tts_configuration(self, updates: Dict[str, Any]) -> Dict[str, Any]:
"""
Update TTS configuration.
Args:
updates: Configuration updates to apply
Returns:
Dict[str, Any]: Updated TTS configuration
Raises:
ConfigurationException: If update fails or validation fails
"""
try:
# Validate updates
self._validate_tts_updates(updates)
# Apply updates to current config
current_config = self._config.get_tts_config()
for key, value in updates.items():
if key in current_config:
# Update the actual config object
if hasattr(self._config.tts, key):
setattr(self._config.tts, key, value)
logger.info(f"Updated TTS config: {key} = {value}")
else:
logger.warning(f"Unknown TTS configuration key: {key}")
# Return updated configuration
updated_config = self._config.get_tts_config()
logger.info(f"TTS configuration updated: {list(updates.keys())}")
return updated_config
except Exception as e:
logger.error(f"Failed to update TTS configuration: {e}")
raise ConfigurationException(f"Failed to update TTS configuration: {str(e)}")
def update_stt_configuration(self, updates: Dict[str, Any]) -> Dict[str, Any]:
"""
Update STT configuration.
Args:
updates: Configuration updates to apply
Returns:
Dict[str, Any]: Updated STT configuration
Raises:
ConfigurationException: If update fails or validation fails
"""
try:
# Validate updates
self._validate_stt_updates(updates)
# Apply updates to current config
current_config = self._config.get_stt_config()
for key, value in updates.items():
if key in current_config:
# Update the actual config object
if hasattr(self._config.stt, key):
setattr(self._config.stt, key, value)
logger.info(f"Updated STT config: {key} = {value}")
else:
logger.warning(f"Unknown STT configuration key: {key}")
# Return updated configuration
updated_config = self._config.get_stt_config()
logger.info(f"STT configuration updated: {list(updates.keys())}")
return updated_config
except Exception as e:
logger.error(f"Failed to update STT configuration: {e}")
raise ConfigurationException(f"Failed to update STT configuration: {str(e)}")
def update_translation_configuration(self, updates: Dict[str, Any]) -> Dict[str, Any]:
"""
Update translation configuration.
Args:
updates: Configuration updates to apply
Returns:
Dict[str, Any]: Updated translation configuration
Raises:
ConfigurationException: If update fails or validation fails
"""
try:
# Validate updates
self._validate_translation_updates(updates)
# Apply updates to current config
current_config = self._config.get_translation_config()
for key, value in updates.items():
if key in current_config:
# Update the actual config object
if hasattr(self._config.translation, key):
setattr(self._config.translation, key, value)
logger.info(f"Updated translation config: {key} = {value}")
else:
logger.warning(f"Unknown translation configuration key: {key}")
# Return updated configuration
updated_config = self._config.get_translation_config()
logger.info(f"Translation configuration updated: {list(updates.keys())}")
return updated_config
except Exception as e:
logger.error(f"Failed to update translation configuration: {e}")
raise ConfigurationException(f"Failed to update translation configuration: {str(e)}")
def update_processing_configuration(self, updates: Dict[str, Any]) -> Dict[str, Any]:
"""
Update processing configuration.
Args:
updates: Configuration updates to apply
Returns:
Dict[str, Any]: Updated processing configuration
Raises:
ConfigurationException: If update fails or validation fails
"""
try:
# Validate updates
self._validate_processing_updates(updates)
# Apply updates to current config
current_config = self._config.get_processing_config()
for key, value in updates.items():
if key in current_config:
# Update the actual config object
if hasattr(self._config.processing, key):
setattr(self._config.processing, key, value)
logger.info(f"Updated processing config: {key} = {value}")
else:
logger.warning(f"Unknown processing configuration key: {key}")
# Return updated configuration
updated_config = self._config.get_processing_config()
logger.info(f"Processing configuration updated: {list(updates.keys())}")
return updated_config
except Exception as e:
logger.error(f"Failed to update processing configuration: {e}")
raise ConfigurationException(f"Failed to update processing configuration: {str(e)}")
def _validate_tts_updates(self, updates: Dict[str, Any]) -> None:
"""
Validate TTS configuration updates.
Args:
updates: Updates to validate
Raises:
ConfigurationException: If validation fails
"""
valid_providers = ['chatterbox', '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):
raise ConfigurationException("preferred_providers must be a list")
for 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")
def _validate_stt_updates(self, updates: Dict[str, Any]) -> None:
"""
Validate STT configuration updates.
Args:
updates: Updates to validate
Raises:
ConfigurationException: If validation fails
"""
valid_providers = ['whisper', 'parakeet']
for key, value in updates.items():
if key == 'preferred_providers':
if not isinstance(value, list):
raise ConfigurationException("preferred_providers must be a list")
for 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")
def _validate_translation_updates(self, updates: Dict[str, Any]) -> None:
"""
Validate translation configuration updates.
Args:
updates: Updates to validate
Raises:
ConfigurationException: If validation fails
"""
for key, value in updates.items():
if 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")
def _validate_processing_updates(self, updates: Dict[str, Any]) -> None:
"""
Validate processing configuration updates.
Args:
updates: Updates to validate
Raises:
ConfigurationException: If validation fails
"""
for key, value in updates.items():
if key == 'temp_dir':
if not isinstance(value, str) or not value:
raise ConfigurationException("temp_dir must be a non-empty string")
# Try to create directory to validate path
try:
Path(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")
valid_formats = ['wav', 'mp3', 'flac', 'ogg', 'm4a']
for 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")
def save_configuration_to_file(self, file_path: str) -> None:
"""
Save current configuration to file.
Args:
file_path: Path to save configuration file
Raises:
ConfigurationException: If save fails
"""
try:
self._config.save_configuration(file_path)
logger.info(f"Configuration saved to {file_path}")
except Exception as e:
logger.error(f"Failed to save configuration to {file_path}: {e}")
raise ConfigurationException(f"Failed to save configuration: {str(e)}")
def load_configuration_from_file(self, file_path: str) -> Dict[str, Any]:
"""
Load configuration from file.
Args:
file_path: Path to configuration file
Returns:
Dict[str, Any]: Loaded configuration
Raises:
ConfigurationException: If load fails
"""
try:
if not os.path.exists(file_path):
raise ConfigurationException(f"Configuration file not found: {file_path}")
# Create new config instance with the file
new_config = AppConfig(config_file=file_path)
# Update current config
self._config = new_config
# Update container with new config
self._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)}")
def reload_configuration(self) -> Dict[str, Any]:
"""
Reload configuration from original sources.
Returns:
Dict[str, Any]: Reloaded configuration
Raises:
ConfigurationException: If reload fails
"""
try:
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)}")
def get_provider_availability(self) -> Dict[str, Dict[str, bool]]:
"""
Get availability status of all providers.
Returns:
Dict[str, Dict[str, bool]]: Provider availability by category
"""
try:
availability = {
'tts': {},
'stt': {},
'translation': {}
}
# Check TTS providers
tts_factory = self._container.resolve(type(self._container._get_tts_factory()))
for provider in ['chatterbox', 'dummy']:
try:
tts_factory.create_provider(provider)
availability['tts'][provider] = True
except Exception:
availability['tts'][provider] = False
# Check STT providers
stt_factory = self._container.resolve(type(self._container._get_stt_factory()))
for provider in ['whisper', 'parakeet']:
try:
stt_factory.create_provider(provider)
availability['stt'][provider] = True
except Exception:
availability['stt'][provider] = False
# Check translation providers
translation_factory = self._container.resolve(type(self._container._get_translation_factory()))
try:
translation_factory.get_default_provider()
availability['translation']['nllb'] = True
except Exception:
availability['translation']['nllb'] = False
return availability
except Exception as e:
logger.error(f"Failed to check provider availability: {e}")
raise ConfigurationException(f"Failed to check provider availability: {str(e)}")
def get_system_info(self) -> Dict[str, Any]:
"""
Get system information and configuration summary.
Returns:
Dict[str, Any]: System information
"""
try:
return {
'config_file': self._config.config_file,
'temp_directory': self._config.processing.temp_dir,
'log_level': self._config.logging.level,
'provider_availability': self.get_provider_availability(),
'supported_languages': [
'en', 'es', 'fr', 'de', 'it', 'pt', 'ru', 'ja', 'ko', 'zh',
'ar', 'hi', 'tr', 'pl', 'nl', 'sv', 'da', 'no', 'fi'
],
'supported_audio_formats': self._config.processing.supported_audio_formats,
'max_file_size_mb': self._config.processing.max_file_size_mb,
'processing_timeout_seconds': self._config.processing.processing_timeout_seconds
}
except Exception as e:
logger.error(f"Failed to get system info: {e}")
raise ConfigurationException(f"Failed to get system info: {str(e)}")
def validate_configuration(self) -> Dict[str, List[str]]:
"""
Validate current configuration and return any issues.
Returns:
Dict[str, List[str]]: Validation issues by category
"""
issues = {
'tts': [],
'stt': [],
'translation': [],
'processing': [],
'logging': []
}
try:
# Validate TTS configuration
tts_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 configuration
stt_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 configuration
processing_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 configuration
logging_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 issues
def reset_to_defaults(self) -> Dict[str, Any]:
"""
Reset configuration to default values.
Returns:
Dict[str, Any]: Reset configuration
Raises:
ConfigurationException: If reset fails
"""
try:
# Create new config with defaults
default_config = AppConfig()
# Update current config
self._config = default_config
# Update container with new config
self._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)}")
def cleanup(self) -> None:
"""Cleanup configuration service resources."""
logger.info("Cleaning up ConfigurationApplicationService")
# No specific cleanup needed for configuration service
logger.info("ConfigurationApplicationService cleanup completed")
def __enter__(self):
"""Context manager entry."""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""Context manager exit with cleanup."""
self.cleanup() |