Spaces:
Runtime error
Runtime error
File size: 35,357 Bytes
8cbe6eb | 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 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 | """
Provider Manager implementation for the voice control optimization system.
This module implements the ProviderManager class that orchestrates multiple
speech-to-text providers with intelligent selection, fallback, and health monitoring.
"""
import asyncio
import logging
from typing import Dict, List, Optional, AsyncIterator, Set
from datetime import datetime, timedelta
from collections import defaultdict
from .interfaces import ProviderManagerInterface, STTProvider, RateLimiterInterface, CacheManagerInterface
from .models import (
ProviderConfig, TranscriptionResult, ProviderStatus, QuotaStatus, QuotaType
)
from .exceptions import (
ProviderError, ProviderUnavailableError, NoProvidersAvailableError,
QuotaExceededError, RateLimitExceededError, UnsupportedFormatError,
UnsupportedLanguageError, CircuitBreakerError
)
logger = logging.getLogger(__name__)
class ProviderManager(ProviderManagerInterface):
"""
Manages multiple STT providers with intelligent selection and fallback.
The ProviderManager implements:
- Provider registration and discovery
- Priority-based provider ordering with free-tier prioritization
- Health checking and status tracking
- Automatic fallback on provider failures
- Circuit breaker pattern for failing providers
"""
def __init__(
self,
rate_limiter: Optional[RateLimiterInterface] = None,
cache_manager: Optional[CacheManagerInterface] = None
):
"""
Initialize the provider manager.
Args:
rate_limiter: Optional rate limiter for quota management
cache_manager: Optional cache manager for transcription caching
"""
self._providers: Dict[str, STTProvider] = {}
self._provider_status: Dict[str, ProviderStatus] = {}
self._rate_limiter = rate_limiter
self._cache_manager = cache_manager
# Health check configuration
self._health_check_interval = 60 # seconds
self._health_check_timeout = 10 # seconds
self._health_check_task: Optional[asyncio.Task] = None
# Circuit breaker configuration
self._circuit_breaker_threshold = 5 # consecutive failures
self._circuit_breaker_timeout = 300 # seconds (5 minutes)
# Provider metrics tracking
self._provider_metrics: Dict[str, Dict[str, float]] = defaultdict(dict)
# Lock for thread-safe operations
self._lock = asyncio.Lock()
logger.info("ProviderManager initialized")
async def register_provider(self, provider: STTProvider) -> None:
"""
Register a new STT provider.
Args:
provider: STTProvider instance to register
Raises:
ValueError: If provider name already exists
"""
async with self._lock:
if provider.name in self._providers:
raise ValueError(f"Provider '{provider.name}' is already registered")
self._providers[provider.name] = provider
# Initialize provider status
self._provider_status[provider.name] = ProviderStatus(
name=provider.name,
available=True,
current_load=0.0,
quota_remaining={},
last_error=None,
response_time_avg=0.0,
circuit_breaker_state="CLOSED",
consecutive_failures=0
)
# Initialize metrics
self._provider_metrics[provider.name] = {
"total_requests": 0,
"successful_requests": 0,
"failed_requests": 0,
"total_response_time": 0.0,
"last_request_time": 0.0
}
logger.info(f"Registered provider: {provider.name} (type: {provider.provider_type})")
# Start health checking if this is the first provider
if len(self._providers) == 1 and self._health_check_task is None:
self._health_check_task = asyncio.create_task(self._health_check_loop())
async def unregister_provider(self, provider_name: str) -> None:
"""
Unregister an STT provider.
Args:
provider_name: Name of provider to unregister
Raises:
KeyError: If provider is not registered
"""
async with self._lock:
if provider_name not in self._providers:
raise KeyError(f"Provider '{provider_name}' is not registered")
del self._providers[provider_name]
del self._provider_status[provider_name]
del self._provider_metrics[provider_name]
logger.info(f"Unregistered provider: {provider_name}")
# Stop health checking if no providers remain
if not self._providers and self._health_check_task:
self._health_check_task.cancel()
self._health_check_task = None
async def update_provider_config(
self,
provider_name: str,
config: ProviderConfig
) -> bool:
"""
Update configuration for a provider.
Args:
provider_name: Name of provider to update
config: New configuration
Returns:
True if update was successful, False otherwise
"""
async with self._lock:
if provider_name not in self._providers:
logger.warning(f"Cannot update config for unregistered provider: {provider_name}")
return False
try:
# Update provider configuration
provider = self._providers[provider_name]
provider.config = config
# Reset circuit breaker if provider was re-enabled
if config.enabled and self._provider_status[provider_name].circuit_breaker_state == "OPEN":
self._provider_status[provider_name].circuit_breaker_state = "CLOSED"
self._provider_status[provider_name].consecutive_failures = 0
logger.info(f"Reset circuit breaker for provider: {provider_name}")
logger.info(f"Updated configuration for provider: {provider_name}")
return True
except Exception as e:
logger.error(f"Failed to update config for provider {provider_name}: {e}")
return False
async def get_provider_status(self) -> Dict[str, ProviderStatus]:
"""
Get status of all registered providers.
Returns:
Dictionary mapping provider names to their status
"""
async with self._lock:
return self._provider_status.copy()
async def transcribe_audio(
self,
audio_data: bytes,
format: str,
language: str = "en-US",
preferred_provider: Optional[str] = None
) -> TranscriptionResult:
"""
Transcribe audio using the best available provider with cache optimization.
This method implements cache hit optimization by:
1. First checking the cache for existing transcription results
2. Only calling STT providers if no cached result is found
3. Caching successful transcription results for future use
Args:
audio_data: Raw audio bytes
format: Audio format
language: Language code
preferred_provider: Preferred provider name (optional)
Returns:
TranscriptionResult from cache or the selected provider
Raises:
NoProvidersAvailableError: If no providers are available
UnsupportedFormatError: If no provider supports the format
UnsupportedLanguageError: If no provider supports the language
"""
# Step 1: Check cache first to avoid API calls (Requirement 4.3)
audio_fingerprint = None
if self._cache_manager:
try:
audio_fingerprint = await self._cache_manager.generate_audio_fingerprint(audio_data)
cached_result = await self._cache_manager.get_cached_transcription(audio_fingerprint)
if cached_result is not None:
logger.info(f"Cache hit for audio fingerprint: {audio_fingerprint[:16]}... "
f"(provider: {cached_result.provider})")
return cached_result
logger.debug(f"Cache miss for audio fingerprint: {audio_fingerprint[:16]}...")
except Exception as e:
logger.warning(f"Cache lookup failed, proceeding with provider transcription: {e}")
# Step 2: No cached result found, proceed with provider transcription
# Estimate audio duration for quota checking
audio_duration = len(audio_data) / (44100 * 2) # Rough estimate
# Get ordered list of providers to try
providers_to_try = await self._get_ordered_providers(
format=format,
language=language,
preferred_provider=preferred_provider,
audio_duration=audio_duration
)
if not providers_to_try:
raise NoProvidersAvailableError()
last_error = None
attempted_providers = []
for provider_name in providers_to_try:
provider = self._providers[provider_name]
attempted_providers.append(provider_name)
try:
# Check if provider is available
if not await self._is_provider_available(provider_name, format, language):
continue
# Check rate limits if rate limiter is available
if self._rate_limiter:
# Check if we should switch away from this provider due to quota concerns
if await self._rate_limiter.should_switch_provider(provider_name, audio_duration):
logger.info(f"Switching away from provider {provider_name} due to quota concerns")
continue
quota_status = await self._rate_limiter.check_quota(provider_name, audio_duration)
if quota_status.is_exceeded:
logger.warning(f"Provider {provider_name} quota exceeded, trying next provider")
continue
# Attempt transcription
start_time = datetime.utcnow()
result = await provider.transcribe_audio(audio_data, format, language)
end_time = datetime.utcnow()
# Update metrics and status
processing_time = (end_time - start_time).total_seconds()
await self._update_provider_metrics(provider_name, True, processing_time)
# Consume quota if rate limiter is available
if self._rate_limiter:
await self._rate_limiter.consume_quota(provider_name, result.audio_duration)
# Step 3: Cache successful transcription result for future use
if self._cache_manager and audio_fingerprint:
try:
cache_success = await self._cache_manager.cache_transcription(
audio_fingerprint,
result
)
if cache_success:
logger.debug(f"Cached transcription result for fingerprint: {audio_fingerprint[:16]}...")
else:
logger.warning(f"Failed to cache transcription result for fingerprint: {audio_fingerprint[:16]}...")
except Exception as e:
logger.warning(f"Cache storage failed: {e}")
logger.info(f"Successfully transcribed audio using provider: {provider_name}")
return result
except (QuotaExceededError, RateLimitExceededError) as e:
logger.warning(f"Provider {provider_name} quota/rate limit exceeded: {e}")
await self._update_provider_metrics(provider_name, False, 0.0)
last_error = e
continue
except (ProviderUnavailableError, CircuitBreakerError) as e:
logger.warning(f"Provider {provider_name} unavailable: {e}")
await self._update_provider_metrics(provider_name, False, 0.0)
last_error = e
continue
except Exception as e:
logger.error(f"Provider {provider_name} failed: {e}")
await self._update_provider_metrics(provider_name, False, 0.0)
await self._handle_provider_failure(provider_name, str(e))
last_error = e
continue
# All providers failed
raise NoProvidersAvailableError(attempted_providers)
async def transcribe_streaming(
self,
audio_stream: AsyncIterator[bytes],
format: str,
language: str = "en-US",
preferred_provider: Optional[str] = None
) -> AsyncIterator[TranscriptionResult]:
"""
Transcribe streaming audio using the best available provider.
Args:
audio_stream: Async iterator of audio chunks
format: Audio format
language: Language code
preferred_provider: Preferred provider name (optional)
Yields:
TranscriptionResult for each processed chunk
Raises:
NoProvidersAvailableError: If no providers are available
"""
# Get the best provider for streaming
providers_to_try = await self._get_ordered_providers(
format=format,
language=language,
preferred_provider=preferred_provider
)
if not providers_to_try:
raise NoProvidersAvailableError()
# Try providers in order until one works
for provider_name in providers_to_try:
provider = self._providers[provider_name]
try:
if not await self._is_provider_available(provider_name, format, language):
continue
# Stream transcription
async for result in provider.transcribe_streaming(audio_stream, format, language):
await self._update_provider_metrics(provider_name, True, result.processing_time)
yield result
# If we get here, streaming was successful
return
except Exception as e:
logger.error(f"Streaming provider {provider_name} failed: {e}")
await self._update_provider_metrics(provider_name, False, 0.0)
await self._handle_provider_failure(provider_name, str(e))
continue
raise NoProvidersAvailableError(providers_to_try)
async def _get_ordered_providers(
self,
format: str,
language: str,
preferred_provider: Optional[str] = None,
audio_duration: float = 0.0
) -> List[str]:
"""
Get providers ordered by priority, availability, and free-tier preference.
Args:
format: Required audio format
language: Required language
preferred_provider: Preferred provider (gets highest priority)
audio_duration: Audio duration for quota checking
Returns:
List of provider names in order of preference
"""
available_providers = []
for name, provider in self._providers.items():
# Skip disabled providers
if not provider.config.enabled:
continue
# Check format and language support
if not provider.supports_format(format):
continue
if not provider.supports_language(language):
continue
# Check circuit breaker state
status = self._provider_status[name]
if status.circuit_breaker_state == "OPEN":
# Check if timeout has passed for half-open state
if datetime.utcnow() - status.last_health_check > timedelta(seconds=self._circuit_breaker_timeout):
status.circuit_breaker_state = "HALF_OPEN"
logger.info(f"Circuit breaker for {name} moved to HALF_OPEN state")
else:
continue
available_providers.append((name, provider))
if not available_providers:
return []
# Pre-calculate quota priorities for all providers
quota_priorities = {}
if self._rate_limiter:
for name, _ in available_providers:
try:
should_switch = await self._rate_limiter.should_switch_provider(name, audio_duration)
quota_priorities[name] = 1 if should_switch else 0
except:
# If quota check fails, treat as lower priority
quota_priorities[name] = 1
else:
for name, _ in available_providers:
quota_priorities[name] = 0
# Sort providers by priority criteria
def provider_sort_key(item):
name, provider = item
config = provider.config
status = self._provider_status[name]
# Preferred provider gets highest priority (lowest sort value)
if preferred_provider and name == preferred_provider:
return (0, 0, 0, 0, 0)
# Free tier providers get priority over paid ones
is_free = config.cost_per_minute == 0.0
free_priority = 0 if is_free else 1
# Use configured priority
configured_priority = config.priority
# Use pre-calculated quota priority
quota_priority = quota_priorities[name]
# Prefer providers with better availability and response times
availability_score = 1.0 - (status.current_load if status.available else 1.0)
response_time_score = status.response_time_avg
# If quota is a concern, prioritize it over free/paid preference
# This allows paid providers to be selected when free providers are approaching limits
if quota_priority == 1: # Provider should be switched away from
return (1, configured_priority, quota_priority, -availability_score, response_time_score)
else:
return (0, free_priority, configured_priority, -availability_score, response_time_score)
# Sort and return provider names
sorted_providers = sorted(available_providers, key=provider_sort_key)
provider_names = [name for name, _ in sorted_providers]
logger.debug(f"Provider order for format={format}, language={language}: {provider_names}")
return provider_names
async def _is_provider_available(
self,
provider_name: str,
format: str,
language: str
) -> bool:
"""
Check if a provider is available for the given format and language.
Args:
provider_name: Name of the provider
format: Audio format
language: Language code
Returns:
True if provider is available, False otherwise
"""
if provider_name not in self._providers:
return False
provider = self._providers[provider_name]
status = self._provider_status[provider_name]
# Check basic availability
if not status.available or not provider.config.enabled:
return False
# Check circuit breaker
if status.circuit_breaker_state == "OPEN":
return False
# Check format and language support
if not provider.supports_format(format) or not provider.supports_language(language):
return False
return True
async def _update_provider_metrics(
self,
provider_name: str,
success: bool,
response_time: float
) -> None:
"""
Update metrics for a provider after a request.
Args:
provider_name: Name of the provider
success: Whether the request was successful
response_time: Response time in seconds
"""
if provider_name not in self._provider_metrics:
return
metrics = self._provider_metrics[provider_name]
status = self._provider_status[provider_name]
# Update request counts
metrics["total_requests"] += 1
if success:
metrics["successful_requests"] += 1
status.consecutive_failures = 0
else:
metrics["failed_requests"] += 1
status.consecutive_failures += 1
# Update response time
if response_time > 0:
metrics["total_response_time"] += response_time
metrics["last_request_time"] = response_time
# Calculate moving average of response time
successful_requests = metrics["successful_requests"]
if successful_requests > 0:
status.response_time_avg = metrics["total_response_time"] / successful_requests
# Update current load (simple metric based on recent activity)
total_requests = metrics["total_requests"]
if total_requests > 0:
success_rate = metrics["successful_requests"] / total_requests
status.current_load = 1.0 - success_rate
logger.debug(f"Updated metrics for {provider_name}: success={success}, response_time={response_time}")
async def _handle_provider_failure(self, provider_name: str, error_message: str) -> None:
"""
Handle a provider failure and update circuit breaker state.
Args:
provider_name: Name of the failed provider
error_message: Error message from the failure
"""
if provider_name not in self._provider_status:
return
status = self._provider_status[provider_name]
status.last_error = error_message
status.last_health_check = datetime.utcnow()
# Check if circuit breaker should be opened
if status.consecutive_failures >= self._circuit_breaker_threshold:
if status.circuit_breaker_state != "OPEN":
status.circuit_breaker_state = "OPEN"
logger.warning(f"Circuit breaker OPENED for provider {provider_name} after {status.consecutive_failures} failures")
async def _health_check_loop(self) -> None:
"""Background task for periodic health checks of all providers."""
while True:
try:
await asyncio.sleep(self._health_check_interval)
await self._perform_health_checks()
except asyncio.CancelledError:
logger.info("Health check loop cancelled")
break
except Exception as e:
logger.error(f"Error in health check loop: {e}")
async def _perform_health_checks(self) -> None:
"""Perform health checks on all registered providers."""
if not self._providers:
return
logger.debug("Performing health checks on all providers")
# Create health check tasks for all providers
health_check_tasks = []
for provider_name, provider in self._providers.items():
task = asyncio.create_task(self._check_provider_health(provider_name, provider))
health_check_tasks.append(task)
# Wait for all health checks to complete (with timeout)
try:
await asyncio.wait_for(
asyncio.gather(*health_check_tasks, return_exceptions=True),
timeout=self._health_check_timeout
)
except asyncio.TimeoutError:
logger.warning("Health check timeout exceeded")
async def _check_provider_health(self, provider_name: str, provider: STTProvider) -> None:
"""
Check the health of a single provider.
Args:
provider_name: Name of the provider
provider: Provider instance
"""
try:
# Perform health check
is_healthy = await provider.check_health()
# Update provider status
status = self._provider_status[provider_name]
status.available = is_healthy
status.last_health_check = datetime.utcnow()
if is_healthy:
# If provider is healthy and circuit breaker is half-open, close it
if status.circuit_breaker_state == "HALF_OPEN":
status.circuit_breaker_state = "CLOSED"
status.consecutive_failures = 0
logger.info(f"Circuit breaker CLOSED for provider {provider_name}")
# Update quota information
try:
quota_status = await provider.get_quota_status()
status.quota_remaining = {
quota_type.value: quota.remaining
for quota_type, quota in quota_status.items()
}
except Exception as e:
logger.debug(f"Failed to get quota status for {provider_name}: {e}")
else:
logger.warning(f"Provider {provider_name} failed health check")
await self._handle_provider_failure(provider_name, "Health check failed")
except Exception as e:
logger.error(f"Health check error for provider {provider_name}: {e}")
await self._handle_provider_failure(provider_name, f"Health check error: {e}")
async def get_provider_metrics(self) -> Dict[str, Dict[str, float]]:
"""
Get performance metrics for all providers.
Returns:
Dictionary mapping provider names to their metrics
"""
return {
name: metrics.copy()
for name, metrics in self._provider_metrics.items()
}
async def get_cache_stats(self) -> Optional[Dict[str, Any]]:
"""
Get cache performance statistics if cache manager is available.
Returns:
Cache statistics dictionary or None if no cache manager
"""
if not self._cache_manager:
return None
try:
cache_stats = await self._cache_manager.get_cache_stats()
return {
"total_requests": cache_stats.total_requests,
"cache_hits": cache_stats.cache_hits,
"cache_misses": cache_stats.cache_misses,
"hit_rate": cache_stats.hit_rate,
"total_size_bytes": cache_stats.total_size_bytes,
"entry_count": cache_stats.entry_count,
"evictions": cache_stats.evictions
}
except Exception as e:
logger.error(f"Failed to get cache statistics: {e}")
return None
async def get_system_stats(self) -> Dict[str, Any]:
"""
Get comprehensive system statistics including providers and cache.
Returns:
Dictionary with provider metrics, cache stats, and system overview
"""
stats = {
"providers": await self.get_provider_metrics(),
"provider_status": await self.get_provider_status(),
"cache": await self.get_cache_stats(),
"system_overview": {
"total_providers": len(self._providers),
"available_providers": sum(
1 for status in self._provider_status.values()
if status.available and status.circuit_breaker_state != "OPEN"
),
"cache_enabled": self._cache_manager is not None,
"rate_limiting_enabled": self._rate_limiter is not None
}
}
# Calculate aggregate metrics
total_requests = sum(
metrics.get("total_requests", 0)
for metrics in stats["providers"].values()
)
total_successful = sum(
metrics.get("successful_requests", 0)
for metrics in stats["providers"].values()
)
if total_requests > 0:
stats["system_overview"]["overall_success_rate"] = total_successful / total_requests
else:
stats["system_overview"]["overall_success_rate"] = 0.0
return stats
async def reset_provider_circuit_breaker(self, provider_name: str) -> bool:
"""
Manually reset a provider's circuit breaker.
Args:
provider_name: Name of the provider
Returns:
True if reset was successful, False otherwise
"""
if provider_name not in self._provider_status:
return False
status = self._provider_status[provider_name]
status.circuit_breaker_state = "CLOSED"
status.consecutive_failures = 0
status.last_error = None
logger.info(f"Manually reset circuit breaker for provider: {provider_name}")
return True
async def get_alternative_provider(
self,
current_provider: str,
format: str,
language: str = "en-US",
audio_duration: float = 0.0
) -> Optional[str]:
"""
Get the best alternative provider when the current one is approaching limits.
Args:
current_provider: Current provider that should be avoided
format: Required audio format
language: Required language
audio_duration: Audio duration for quota checking
Returns:
Name of best alternative provider, or None if no alternatives available
"""
# Get ordered providers excluding the current one
all_providers = await self._get_ordered_providers(format, language, audio_duration=audio_duration)
# Filter out the current provider
alternative_providers = [p for p in all_providers if p != current_provider]
if not alternative_providers:
return None
# Return the best alternative (first in the ordered list)
best_alternative = alternative_providers[0]
# Verify the alternative is actually available
if await self._is_provider_available(best_alternative, format, language):
if self._rate_limiter:
# Check if alternative has quota available
if not await self._rate_limiter.should_switch_provider(best_alternative, audio_duration):
return best_alternative
else:
return best_alternative
# If best alternative is not available, try the next ones
for provider_name in alternative_providers[1:]:
if await self._is_provider_available(provider_name, format, language):
if self._rate_limiter:
if not await self._rate_limiter.should_switch_provider(provider_name, audio_duration):
return provider_name
else:
return provider_name
return None
async def recommend_provider_switch(
self,
current_provider: str,
format: str,
language: str = "en-US",
audio_duration: float = 0.0
) -> Optional[Dict[str, Any]]:
"""
Recommend a provider switch if the current provider is approaching limits.
Args:
current_provider: Current provider name
format: Required audio format
language: Required language
audio_duration: Audio duration for quota checking
Returns:
Dictionary with switch recommendation, or None if no switch needed
"""
if not self._rate_limiter:
return None
# Check if current provider should be switched
should_switch = await self._rate_limiter.should_switch_provider(current_provider, audio_duration)
if not should_switch:
return None
# Get alternative provider
alternative = await self.get_alternative_provider(current_provider, format, language, audio_duration)
if alternative is None:
return {
"should_switch": True,
"reason": "Current provider approaching limits",
"alternative_provider": None,
"recommendation": "Wait for quota reset or reduce usage"
}
# Get quota status for both providers
current_quota = await self._rate_limiter.check_quota(current_provider, audio_duration)
alternative_quota = await self._rate_limiter.check_quota(alternative, audio_duration)
return {
"should_switch": True,
"reason": f"Current provider {current_provider} at {current_quota.percentage_used:.1%} of quota",
"alternative_provider": alternative,
"current_quota_status": current_quota,
"alternative_quota_status": alternative_quota,
"recommendation": f"Switch to {alternative} for better quota availability"
}
async def shutdown(self) -> None:
"""Shutdown the provider manager and cleanup resources."""
logger.info("Shutting down ProviderManager")
# Cancel health check task
if self._health_check_task:
self._health_check_task.cancel()
try:
await self._health_check_task
except asyncio.CancelledError:
pass
# Clear all providers and status
async with self._lock:
self._providers.clear()
self._provider_status.clear()
self._provider_metrics.clear()
logger.info("ProviderManager shutdown complete") |