stemsplit-backend / voice_control /examples /web_speech_provider_example.py
nifty-coder
Voice control
8cbe6eb
Raw History Blame Contribute Delete
6.45 kB
"""
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())