Spaces:
Runtime error
Runtime error
Download voice_control/tests/conftest.py from nifty-coder/stemsplit-backend: direct link, hf CLI and curl.
- Browser
- Download file 8.39 kB
-
https://huggingface.co/spaces/nifty-coder/stemsplit-backend/resolve/main/voice_control/tests/conftest.py
- Command line
-
hf download hf://spaces/nifty-coder/stemsplit-backend/voice_control/tests/conftest.py
-
curl -L -o conftest.py https://huggingface.co/spaces/nifty-coder/stemsplit-backend/resolve/main/voice_control/tests/conftest.py
8.39 kB
| """ | |
| Pytest configuration and fixtures for voice control tests. | |
| This module provides common fixtures and configuration for all tests | |
| in the voice control optimization system. | |
| """ | |
| import pytest | |
| import asyncio | |
| import tempfile | |
| import os | |
| from typing import Dict, Any | |
| from unittest.mock import Mock, AsyncMock | |
| from datetime import datetime, timedelta | |
| from hypothesis import settings, Verbosity | |
| from hypothesis.strategies import composite, integers, floats, text, booleans, lists, dictionaries | |
| from voice_control.models import ( | |
| ProviderConfig, ProviderType, TranscriptionResult, UsageStats, | |
| ProviderStatus, ProcessedAudio, QuotaStatus, QuotaType | |
| ) | |
| from voice_control.interfaces import STTProvider | |
| # Configure Hypothesis for property-based testing | |
| settings.register_profile("default", max_examples=100, verbosity=Verbosity.normal) | |
| settings.register_profile("ci", max_examples=1000, verbosity=Verbosity.verbose) | |
| settings.register_profile("dev", max_examples=10, verbosity=Verbosity.verbose) | |
| # Use CI profile in CI environment, dev profile for local development | |
| profile = os.environ.get("HYPOTHESIS_PROFILE", "default") | |
| settings.load_profile(profile) | |
| def event_loop(): | |
| """Create an instance of the default event loop for the test session.""" | |
| loop = asyncio.get_event_loop_policy().new_event_loop() | |
| yield loop | |
| loop.close() | |
| def temp_dir(): | |
| """Create a temporary directory for test files.""" | |
| with tempfile.TemporaryDirectory() as tmpdir: | |
| yield tmpdir | |
| def sample_audio_data(): | |
| """Generate sample audio data for testing.""" | |
| # Generate 1 second of silence at 44.1kHz, 16-bit, mono | |
| import numpy as np | |
| sample_rate = 44100 | |
| duration = 1.0 | |
| samples = int(sample_rate * duration) | |
| audio_array = np.zeros(samples, dtype=np.int16) | |
| return audio_array.tobytes() | |
| def sample_provider_config(): | |
| """Create a sample provider configuration for testing.""" | |
| return ProviderConfig( | |
| name="test_provider", | |
| provider_type=ProviderType.WEB_SPEECH_API, | |
| enabled=True, | |
| priority=1, | |
| free_tier_limits={"requests_per_day": 1000, "audio_minutes_per_month": 60}, | |
| rate_limits={"requests_per_minute": 10, "audio_minutes_per_hour": 5}, | |
| supported_formats=["webm", "wav", "mp3"], | |
| supported_languages=["en-US", "en-GB"], | |
| cost_per_minute=0.0, | |
| api_credentials={"api_key": "test_key"}, | |
| timeout_seconds=30, | |
| max_retries=3 | |
| ) | |
| def sample_transcription_result(): | |
| """Create a sample transcription result for testing.""" | |
| return TranscriptionResult( | |
| text="Hello world", | |
| confidence=0.95, | |
| provider="test_provider", | |
| processing_time=1.5, | |
| audio_duration=2.0, | |
| language="en-US", | |
| alternatives=["Hello world", "Hello word"], | |
| is_final=True, | |
| session_id="test_session_123" | |
| ) | |
| def sample_usage_stats(): | |
| """Create sample usage statistics for testing.""" | |
| now = datetime.utcnow() | |
| return UsageStats( | |
| provider="test_provider", | |
| requests_count=100, | |
| audio_minutes=50.5, | |
| estimated_cost=2.50, | |
| success_rate=0.98, | |
| average_latency=1.2, | |
| time_window="hour", | |
| window_start=now - timedelta(hours=1), | |
| window_end=now | |
| ) | |
| def sample_provider_status(): | |
| """Create sample provider status for testing.""" | |
| return ProviderStatus( | |
| name="test_provider", | |
| available=True, | |
| current_load=0.3, | |
| quota_remaining={"requests": 900.0, "audio_minutes": 45.5}, | |
| last_error=None, | |
| response_time_avg=1.1, | |
| circuit_breaker_state="CLOSED", | |
| consecutive_failures=0 | |
| ) | |
| def mock_stt_provider(sample_provider_config, sample_transcription_result): | |
| """Create a mock STT provider for testing.""" | |
| class MockSTTProvider(STTProvider): | |
| def __init__(self, config: ProviderConfig): | |
| super().__init__(config) | |
| self.health_status = True | |
| self.quota_status = { | |
| "requests_per_minute": QuotaStatus( | |
| provider=config.name, | |
| quota_type=QuotaType.REQUESTS_PER_MINUTE, | |
| current_usage=5, | |
| limit=10, | |
| remaining=5, | |
| reset_time=datetime.utcnow() + timedelta(minutes=1), | |
| percentage_used=0.5 | |
| ) | |
| } | |
| async def transcribe_audio(self, audio_data: bytes, format: str, language: str = "en-US", **kwargs): | |
| return sample_transcription_result | |
| async def transcribe_streaming(self, audio_stream, format: str, language: str = "en-US", **kwargs): | |
| async for chunk in audio_stream: | |
| yield sample_transcription_result | |
| async def check_health(self) -> bool: | |
| return self.health_status | |
| async def get_quota_status(self): | |
| return self.quota_status | |
| 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 | |
| return MockSTTProvider(sample_provider_config) | |
| # Hypothesis strategies for generating test data | |
| def provider_config_strategy(draw): | |
| """Strategy for generating valid ProviderConfig instances.""" | |
| return ProviderConfig( | |
| name=draw(text(min_size=1, max_size=50)), | |
| provider_type=draw(integers(min_value=0, max_value=4).map(lambda x: list(ProviderType)[x])), | |
| enabled=draw(booleans()), | |
| priority=draw(integers(min_value=0, max_value=100)), | |
| free_tier_limits=draw(dictionaries(text(), integers(min_value=0))), | |
| rate_limits=draw(dictionaries(text(), integers(min_value=1))), | |
| supported_formats=draw(lists(text(min_size=1), min_size=1)), | |
| supported_languages=draw(lists(text(min_size=2, max_size=5), min_size=1)), | |
| cost_per_minute=draw(floats(min_value=0.0, max_value=1.0)), | |
| api_credentials=draw(dictionaries(text(), text())), | |
| timeout_seconds=draw(integers(min_value=1, max_value=300)), | |
| max_retries=draw(integers(min_value=0, max_value=10)) | |
| ) | |
| def transcription_result_strategy(draw): | |
| """Strategy for generating valid TranscriptionResult instances.""" | |
| return TranscriptionResult( | |
| text=draw(text()), | |
| confidence=draw(floats(min_value=0.0, max_value=1.0)), | |
| provider=draw(text(min_size=1)), | |
| processing_time=draw(floats(min_value=0.0, max_value=60.0)), | |
| audio_duration=draw(floats(min_value=0.1, max_value=3600.0)), | |
| language=draw(text(min_size=2, max_size=10)), | |
| alternatives=draw(lists(text(), max_size=5)), | |
| is_final=draw(booleans()) | |
| ) | |
| def audio_data_strategy(draw): | |
| """Strategy for generating audio data bytes.""" | |
| size = draw(integers(min_value=1024, max_value=1024*1024)) # 1KB to 1MB | |
| return bytes(draw(integers(min_value=0, max_value=255)) for _ in range(size)) | |
| def quota_status_strategy(draw): | |
| """Strategy for generating valid QuotaStatus instances.""" | |
| limit = draw(floats(min_value=1.0, max_value=10000.0)) | |
| current_usage = draw(floats(min_value=0.0, max_value=limit * 1.1)) # Allow slight over-usage | |
| return QuotaStatus( | |
| provider=draw(text(min_size=1)), | |
| quota_type=draw(integers(min_value=0, max_value=4).map(lambda x: list(QuotaType)[x])), | |
| current_usage=current_usage, | |
| limit=limit, | |
| remaining=max(0, limit - current_usage), | |
| reset_time=datetime.utcnow() + timedelta(hours=draw(integers(min_value=1, max_value=24))), | |
| percentage_used=min(current_usage / limit, 1.0) if limit > 0 else 0.0 | |
| ) | |
| # Test data constants | |
| VALID_AUDIO_FORMATS = ["webm", "wav", "mp3", "ogg", "flac"] | |
| VALID_LANGUAGES = ["en-US", "en-GB", "es-ES", "fr-FR", "de-DE", "ja-JP", "zh-CN"] | |
| PROVIDER_NAMES = ["web_speech_api", "google_speech", "azure_speech", "assembly_ai", "deepgram"] |