File size: 6,446 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
"""
Example usage of WebSpeechProvider.

This example demonstrates how to use the WebSpeechProvider for both
single transcription and streaming transcription scenarios.
"""

import asyncio
import logging
import sys
import os

# Add the parent directory to the path so we can import voice_control
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from voice_control.providers.web_speech_provider import create_web_speech_provider

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


async def example_single_transcription():
    """Example of single audio transcription."""
    print("\n=== Single Transcription Example ===")
    
    # Create provider with default configuration
    provider = create_web_speech_provider(
        name="example_web_speech",
        priority=1
    )
    
    # Simulate audio data (1 second of 16kHz, 16-bit audio)
    sample_audio = b'\x00' * (16000 * 2)
    
    try:
        # Check provider health
        is_healthy = await provider.check_health()
        print(f"Provider health: {'OK' if is_healthy else 'FAILED'}")
        
        if not is_healthy:
            print("Provider is not healthy, skipping transcription")
            return
        
        # Get quota status
        quota_status = await provider.get_quota_status()
        print(f"Daily requests used: {quota_status['requests_per_day'].current_usage}")
        print(f"Daily audio minutes used: {quota_status['audio_minutes_per_day'].current_usage:.2f}")
        
        # Perform transcription
        print("Performing transcription...")
        result = await provider.transcribe_audio(
            audio_data=sample_audio,
            format="webm",
            language="en-US",
            audio_duration=1.0
        )
        
        # Display results
        print(f"Transcribed text: '{result.text}'")
        print(f"Confidence: {result.confidence:.2f}")
        print(f"Processing time: {result.processing_time:.3f}s")
        print(f"Audio duration: {result.audio_duration:.2f}s")
        print(f"Provider: {result.provider}")
        print(f"Language: {result.language}")
        
    except Exception as e:
        print(f"Transcription failed: {e}")


async def example_streaming_transcription():
    """Example of streaming audio transcription."""
    print("\n=== Streaming Transcription Example ===")
    
    # Create provider
    provider = create_web_speech_provider(
        name="streaming_web_speech",
        priority=1
    )
    
    async def simulate_audio_stream():
        """Simulate streaming audio chunks."""
        print("Generating audio stream...")
        for i in range(5):
            # Simulate 0.5 seconds of audio per chunk
            chunk = b'\x00' * (16000 * 1)  # 0.5 seconds at 16kHz, 16-bit
            print(f"  Sending chunk {i+1}/5")
            yield chunk
            await asyncio.sleep(0.1)  # Simulate real-time streaming
    
    try:
        print("Starting streaming transcription...")
        
        result_count = 0
        async for result in provider.transcribe_streaming(
            audio_stream=simulate_audio_stream(),
            format="webm",
            language="en-US",
            interim_results=True
        ):
            result_count += 1
            print(f"Result {result_count}:")
            print(f"  Text: '{result.text}'")
            print(f"  Confidence: {result.confidence:.2f}")
            print(f"  Is final: {result.is_final}")
            print(f"  Session ID: {result.session_id}")
            print(f"  Processing time: {result.processing_time:.3f}s")
        
        print(f"Streaming completed. Total results: {result_count}")
        
    except Exception as e:
        print(f"Streaming transcription failed: {e}")


async def example_provider_capabilities():
    """Example of checking provider capabilities."""
    print("\n=== Provider Capabilities Example ===")
    
    provider = create_web_speech_provider()
    
    # Check supported formats
    print("Supported audio formats:")
    test_formats = ["webm", "wav", "mp3", "ogg", "flac", "aac"]
    for fmt in test_formats:
        supported = provider.supports_format(fmt)
        print(f"  {fmt}: {'✓' if supported else '✗'}")
    
    # Check supported languages
    print("\nSupported languages (sample):")
    test_languages = ["en-US", "es-ES", "fr-FR", "de-DE", "ja-JP", "zh-CN", "ar-SA", "unknown-XX"]
    for lang in test_languages:
        supported = provider.supports_language(lang)
        print(f"  {lang}: {'✓' if supported else '✗'}")
    
    # Check cost estimation
    print("\nCost estimation:")
    durations = [60, 300, 3600]  # 1 minute, 5 minutes, 1 hour
    for duration in durations:
        cost = await provider.estimate_cost(duration)
        print(f"  {duration}s ({duration/60:.1f} min): ${cost:.4f}")


async def example_error_handling():
    """Example of error handling scenarios."""
    print("\n=== Error Handling Example ===")
    
    provider = create_web_speech_provider()
    sample_audio = b'\x00' * 1000
    
    # Test unsupported format
    try:
        await provider.transcribe_audio(sample_audio, "unsupported_format", "en-US")
    except Exception as e:
        print(f"Unsupported format error: {type(e).__name__}: {e}")
    
    # Test unsupported language
    try:
        await provider.transcribe_audio(sample_audio, "webm", "unsupported-LANG")
    except Exception as e:
        print(f"Unsupported language error: {type(e).__name__}: {e}")
    
    # Test quota limits (simulate exceeded quota)
    provider.config.free_tier_limits["max_daily_requests"] = 0
    try:
        await provider.transcribe_audio(sample_audio, "webm", "en-US", audio_duration=1.0)
    except Exception as e:
        print(f"Quota exceeded error: {type(e).__name__}: {e}")


async def main():
    """Run all examples."""
    print("WebSpeechProvider Examples")
    print("=" * 50)
    
    try:
        await example_provider_capabilities()
        await example_single_transcription()
        await example_streaming_transcription()
        await example_error_handling()
        
        print("\n" + "=" * 50)
        print("All examples completed successfully!")
        
    except Exception as e:
        print(f"Example execution failed: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    asyncio.run(main())