Spaces:
Runtime error
Runtime error
File size: 13,051 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 | """
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
@pytest.mark.asyncio
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()
@pytest.mark.asyncio
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"]) |