Spaces:
Runtime error
Runtime error
Download voice_control/tests/test_simple_integration.py from nifty-coder/stemsplit-backend: direct link, hf CLI and curl.
- Browser
- Download file 13.1 kB
-
https://huggingface.co/spaces/nifty-coder/stemsplit-backend/resolve/main/voice_control/tests/test_simple_integration.py
- Command line
-
hf download hf://spaces/nifty-coder/stemsplit-backend/voice_control/tests/test_simple_integration.py
-
curl -L -o test_simple_integration.py https://huggingface.co/spaces/nifty-coder/stemsplit-backend/resolve/main/voice_control/tests/test_simple_integration.py
13.1 kB
| """ | |
| Simple integration test for core components. | |
| This test validates that all core components (ProviderManager, RateLimiter, | |
| AudioProcessor, CacheManager) work together for Task 6. | |
| """ | |
| import pytest | |
| import asyncio | |
| import struct | |
| import math | |
| from unittest.mock import patch | |
| from voice_control.provider_manager import ProviderManager | |
| from voice_control.rate_limiter import RateLimiter | |
| from voice_control.audio_processor import AudioProcessor | |
| from voice_control.cache_manager import CacheManager | |
| from voice_control.models import ( | |
| ProviderConfig, ProviderType, TranscriptionResult | |
| ) | |
| from voice_control.interfaces import STTProvider | |
| class SimpleSTTProvider(STTProvider): | |
| """Simple mock STT provider for integration testing.""" | |
| def __init__(self, config: ProviderConfig): | |
| super().__init__(config) | |
| self.call_count = 0 | |
| async def transcribe_audio(self, audio_data: bytes, format: str, language: str = "en-US", **kwargs): | |
| self.call_count += 1 | |
| return TranscriptionResult( | |
| text=f"test transcription from {self.config.name}", | |
| confidence=0.95, | |
| provider=self.config.name, | |
| processing_time=1.0, | |
| audio_duration=2.0, | |
| language=language | |
| ) | |
| async def transcribe_streaming(self, audio_stream, format: str, language: str = "en-US", **kwargs): | |
| async for chunk in audio_stream: | |
| yield await self.transcribe_audio(chunk, format, language) | |
| async def check_health(self) -> bool: | |
| return True | |
| async def get_quota_status(self): | |
| return {} | |
| def supports_format(self, format: str) -> bool: | |
| return format in self.config.supported_formats | |
| def supports_language(self, language: str) -> bool: | |
| return language in self.config.supported_languages | |
| async def estimate_cost(self, audio_duration: float) -> float: | |
| return audio_duration * self.config.cost_per_minute / 60.0 | |
| def create_sample_audio(): | |
| """Create sample WAV audio data.""" | |
| sample_rate = 16000 | |
| channels = 1 | |
| bit_depth = 16 | |
| duration = 1.0 # 1 second | |
| # Generate sine wave samples | |
| samples = [] | |
| for i in range(int(sample_rate * duration)): | |
| sample = int(32767 * 0.3 * math.sin(2 * math.pi * 440 * i / sample_rate)) | |
| samples.append(sample) | |
| # Create WAV header | |
| data_size = len(samples) * 2 | |
| file_size = 36 + data_size | |
| header = struct.pack('<4sI4s4sIHHIIHH4sI', | |
| b'RIFF', file_size, b'WAVE', b'fmt ', 16, 1, channels, | |
| sample_rate, sample_rate * channels * 2, channels * 2, bit_depth, | |
| b'data', data_size | |
| ) | |
| sample_data = struct.pack(f'<{len(samples)}h', *samples) | |
| return header + sample_data | |
| async def test_core_components_integration(): | |
| """ | |
| Test that all core components work together properly. | |
| This is the main integration test for Task 6: Checkpoint - Core components integration test. | |
| """ | |
| # Create sample audio | |
| sample_audio = create_sample_audio() | |
| # Mock audio processor config | |
| with patch('voice_control.audio_processor.get_config') as mock_config: | |
| mock_config.return_value.audio_processing = { | |
| "silence_threshold": 0.01, | |
| "min_silence_duration": 0.5, | |
| "min_speech_duration": 0.1, | |
| "silence_window_size_ms": 50, | |
| "noise_reduction_strength": 0.5, | |
| "noise_reduction_enabled": True, | |
| "silence_removal_enabled": True, | |
| "supported_formats": ["webm", "wav", "mp3", "ogg"], | |
| "default_chunk_duration": 30.0, | |
| "default_chunk_overlap": 0.0, | |
| "chunk_at_silence_boundaries": True, | |
| "min_chunk_duration": 1.0, | |
| "max_chunk_duration": 60.0, | |
| "noise_reduction_algorithm": "spectral_subtraction", | |
| "noise_reduction_adaptive": True, | |
| "noise_reduction_preserve_speech": True | |
| } | |
| # Initialize components | |
| rate_limiter = RateLimiter(cleanup_interval=60) | |
| await rate_limiter.initialize() | |
| cache_manager = CacheManager(max_size_mb=10, default_ttl=3600, cleanup_interval=60) | |
| await cache_manager.start() | |
| audio_processor = AudioProcessor() | |
| provider_manager = ProviderManager( | |
| rate_limiter=rate_limiter, | |
| cache_manager=cache_manager | |
| ) | |
| try: | |
| # Create and configure provider | |
| provider_config = ProviderConfig( | |
| name="test_provider", | |
| provider_type=ProviderType.WEB_SPEECH_API, | |
| enabled=True, | |
| priority=1, | |
| free_tier_limits={"audio_minutes_per_day": 60}, | |
| rate_limits={"requests_per_minute": 10}, | |
| supported_formats=["wav", "webm"], | |
| supported_languages=["en-US"], | |
| cost_per_minute=0.0, | |
| api_credentials={"api_key": "test_key"} | |
| ) | |
| # Configure rate limiter | |
| await rate_limiter.configure_provider(provider_config) | |
| # Register provider | |
| provider = SimpleSTTProvider(provider_config) | |
| await provider_manager.register_provider(provider) | |
| # Test 1: Audio Processing | |
| processed_audio = await audio_processor.optimize_for_provider( | |
| sample_audio, | |
| "test_provider" | |
| ) | |
| assert processed_audio.provider == "test_provider" | |
| assert processed_audio.duration > 0 | |
| assert len(processed_audio.data) > 0 | |
| # Test 2: First transcription (should call provider and cache result) | |
| result1 = await provider_manager.transcribe_audio( | |
| processed_audio.data, | |
| processed_audio.format, | |
| "en-US" | |
| ) | |
| assert result1.text == "test transcription from test_provider" | |
| assert result1.provider == "test_provider" | |
| assert provider.call_count == 1 | |
| # Test 3: Second transcription with same audio (should hit cache) | |
| result2 = await provider_manager.transcribe_audio( | |
| processed_audio.data, | |
| processed_audio.format, | |
| "en-US" | |
| ) | |
| assert result2.text == result1.text | |
| assert result2.provider == result1.provider | |
| # Provider should not be called again (cache hit) | |
| assert provider.call_count == 1 | |
| # Test 4: Verify cache statistics | |
| cache_stats = await cache_manager.get_cache_stats() | |
| assert cache_stats.cache_hits >= 1 | |
| assert cache_stats.total_requests >= 2 | |
| # Test 5: Verify rate limiting works | |
| quota_status = await rate_limiter.check_quota("test_provider", 30.0) | |
| assert not quota_status.is_exceeded | |
| # Test 6: Verify provider status | |
| provider_status = await provider_manager.get_provider_status() | |
| assert "test_provider" in provider_status | |
| assert provider_status["test_provider"].available is True | |
| # Test 7: Verify system statistics | |
| system_stats = await provider_manager.get_system_stats() | |
| assert system_stats["system_overview"]["total_providers"] >= 1 | |
| assert system_stats["system_overview"]["available_providers"] >= 1 | |
| assert system_stats["system_overview"]["cache_enabled"] is True | |
| assert system_stats["system_overview"]["rate_limiting_enabled"] is True | |
| print("β All core components integration tests passed!") | |
| print(f" - Audio processing: β ") | |
| print(f" - Provider management: β ") | |
| print(f" - Rate limiting: β ") | |
| print(f" - Caching: β (hits: {cache_stats.cache_hits}, total: {cache_stats.total_requests})") | |
| print(f" - System statistics: β ") | |
| finally: | |
| # Cleanup | |
| await provider_manager.shutdown() | |
| await rate_limiter.shutdown() | |
| await cache_manager.stop() | |
| async def test_provider_fallback_integration(): | |
| """ | |
| Test provider fallback functionality with rate limiting. | |
| """ | |
| sample_audio = create_sample_audio() | |
| with patch('voice_control.audio_processor.get_config') as mock_config: | |
| mock_config.return_value.audio_processing = { | |
| "silence_threshold": 0.01, | |
| "min_silence_duration": 0.5, | |
| "min_speech_duration": 0.1, | |
| "silence_window_size_ms": 50, | |
| "noise_reduction_strength": 0.5, | |
| "noise_reduction_enabled": True, | |
| "silence_removal_enabled": True, | |
| "supported_formats": ["webm", "wav", "mp3", "ogg"], | |
| "default_chunk_duration": 30.0, | |
| "default_chunk_overlap": 0.0, | |
| "chunk_at_silence_boundaries": True, | |
| "min_chunk_duration": 1.0, | |
| "max_chunk_duration": 60.0, | |
| "noise_reduction_algorithm": "spectral_subtraction", | |
| "noise_reduction_adaptive": True, | |
| "noise_reduction_preserve_speech": True | |
| } | |
| # Initialize components | |
| rate_limiter = RateLimiter(cleanup_interval=60) | |
| await rate_limiter.initialize() | |
| cache_manager = CacheManager(max_size_mb=10, default_ttl=3600, cleanup_interval=60) | |
| await cache_manager.start() | |
| audio_processor = AudioProcessor() | |
| provider_manager = ProviderManager( | |
| rate_limiter=rate_limiter, | |
| cache_manager=cache_manager | |
| ) | |
| try: | |
| # Create two providers with different priorities | |
| free_config = ProviderConfig( | |
| name="free_provider", | |
| provider_type=ProviderType.WEB_SPEECH_API, | |
| enabled=True, | |
| priority=1, # Higher priority (lower number) | |
| free_tier_limits={"audio_minutes_per_day": 1}, # Very small limit | |
| rate_limits={"requests_per_minute": 2}, # Very small limit | |
| supported_formats=["wav", "webm"], | |
| supported_languages=["en-US"], | |
| cost_per_minute=0.0, | |
| api_credentials={"api_key": "free_key"} | |
| ) | |
| paid_config = ProviderConfig( | |
| name="paid_provider", | |
| provider_type=ProviderType.DEEPGRAM, | |
| enabled=True, | |
| priority=2, # Lower priority (higher number) | |
| free_tier_limits={"audio_minutes_per_day": 300}, | |
| rate_limits={"requests_per_minute": 100}, | |
| supported_formats=["wav", "webm"], | |
| supported_languages=["en-US"], | |
| cost_per_minute=0.05, | |
| api_credentials={"api_key": "paid_key"} | |
| ) | |
| # Configure rate limiter | |
| await rate_limiter.configure_provider(free_config) | |
| await rate_limiter.configure_provider(paid_config) | |
| # Register providers | |
| free_provider = SimpleSTTProvider(free_config) | |
| paid_provider = SimpleSTTProvider(paid_config) | |
| await provider_manager.register_provider(free_provider) | |
| await provider_manager.register_provider(paid_provider) | |
| # Exhaust free provider's quota | |
| for i in range(3): # Exceed the limit of 2 requests per minute | |
| try: | |
| await rate_limiter.consume_quota("free_provider", 30.0, 1) | |
| except: | |
| break | |
| # Process audio | |
| processed_audio = await audio_processor.optimize_for_provider( | |
| sample_audio, | |
| "free_provider" # Request free provider but should fallback | |
| ) | |
| # Transcription should automatically use paid provider due to rate limits | |
| result = await provider_manager.transcribe_audio( | |
| processed_audio.data, | |
| processed_audio.format, | |
| "en-US" | |
| ) | |
| # Should have used paid provider as fallback | |
| assert result.provider == "paid_provider" | |
| assert paid_provider.call_count >= 1 | |
| print("β Provider fallback integration test passed!") | |
| print(f" - Fallback to paid provider: β ") | |
| print(f" - Rate limiting triggered fallback: β ") | |
| finally: | |
| # Cleanup | |
| await provider_manager.shutdown() | |
| await rate_limiter.shutdown() | |
| await cache_manager.stop() | |
| if __name__ == "__main__": | |
| pytest.main([__file__, "-v", "-s"]) |