stemsplit-backend / voice_control /audio_processor.py
nifty-coder
Voice control
8cbe6eb
Raw History Blame Contribute Delete
61.2 kB
""" Audio processing and optimization for the voice control system. This module provides audio format conversion, compression, noise reduction, and provider-specific optimization for speech-to-text processing. """ import asyncio import logging import io import struct import wave from typing import List, Optional, Dict, Any, Tuple from dataclasses import dataclass from .interfaces import AudioProcessorInterface from .models import ProcessedAudio, AudioSegment, ProviderType from .exceptions import AudioProcessingError, UnsupportedFormatError from .utils import generate_fingerprint, clamp from .config import get_config logger = logging.getLogger(__name__) @dataclass class AudioFormat: """Audio format specification.""" format: str sample_rate: int channels: int bit_depth: int codec: Optional[str] = None class AudioProcessor(AudioProcessorInterface): """ Audio processor for optimizing audio data for different STT providers. Handles format conversion, compression, noise reduction, and provider-specific audio optimization to improve transcription accuracy and reduce bandwidth usage. """ def __init__(self): """Initialize the audio processor.""" self.config = get_config() self._provider_formats = self._load_provider_formats() self._format_converters = self._initialize_converters() def _load_provider_formats(self) -> Dict[str, AudioFormat]: """Load optimal audio formats for each provider type.""" return { ProviderType.WEB_SPEECH_API.value: AudioFormat( format="webm", sample_rate=16000, channels=1, bit_depth=16, codec="opus" ), ProviderType.GOOGLE_SPEECH.value: AudioFormat( format="wav", sample_rate=16000, channels=1, bit_depth=16 ), ProviderType.AZURE_SPEECH.value: AudioFormat( format="wav", sample_rate=16000, channels=1, bit_depth=16 ), ProviderType.ASSEMBLY_AI.value: AudioFormat( format="wav", sample_rate=16000, channels=1, bit_depth=16 ), ProviderType.DEEPGRAM.value: AudioFormat( format="webm", sample_rate=16000, channels=1, bit_depth=16, codec="opus" ) } def _initialize_converters(self) -> Dict[str, Any]: """Initialize format converters (placeholder for actual audio libraries).""" # In a real implementation, this would initialize audio processing libraries # like pydub, librosa, or ffmpeg-python return {} async def optimize_for_provider( self, audio_data: bytes, provider: str, target_format: Optional[str] = None ) -> ProcessedAudio: """ Optimize audio for a specific provider. Args: audio_data: Raw audio bytes provider: Target provider name target_format: Desired output format (optional) Returns: ProcessedAudio optimized for the provider Raises: AudioProcessingError: If optimization fails UnsupportedFormatError: If format is not supported """ try: logger.debug(f"Optimizing audio for provider: {provider}") # Get provider's optimal format provider_format = self._get_provider_format(provider) if target_format: provider_format.format = target_format # Detect input audio format input_format = await self._detect_audio_format(audio_data) # Convert to optimal format if needed if self._needs_conversion(input_format, provider_format): audio_data = await self.convert_format( audio_data, input_format.format, provider_format.format, sample_rate=provider_format.sample_rate, channels=provider_format.channels, bit_depth=provider_format.bit_depth ) # Apply noise reduction if self.config.audio_processing.get("noise_reduction_enabled", True): strength = self.config.audio_processing.get("noise_reduction_strength", 0.5) audio_data = await self.apply_noise_reduction(audio_data, strength) # Remove silence if enabled silence_removed = False if self.config.audio_processing.get("silence_removal_enabled", True): segments = await self.detect_silence(audio_data) if len(segments) > 1: # Only process if silence was detected audio_data = await self._remove_silence_segments(audio_data, segments) silence_removed = True # Apply compression compression_ratio = await self._apply_compression( audio_data, provider_format, provider ) # Calculate duration duration = await self._calculate_duration(audio_data, provider_format) return ProcessedAudio( data=audio_data, format=provider_format.format, sample_rate=provider_format.sample_rate, channels=provider_format.channels, duration=duration, provider=provider, compression_ratio=compression_ratio, noise_reduced=True, silence_removed=silence_removed ) except Exception as e: logger.error(f"Audio optimization failed for provider {provider}: {e}") raise AudioProcessingError("optimization", f"Failed to optimize audio: {e}") def _get_provider_format(self, provider: str) -> AudioFormat: """Get the optimal audio format for a provider.""" # Try to match by provider type first for provider_type in ProviderType: if provider_type.value in provider.lower(): return self._provider_formats.get(provider_type.value, self._get_default_format()) # Fallback to default format return self._get_default_format() def _get_default_format(self) -> AudioFormat: """Get the default audio format.""" return AudioFormat( format="wav", sample_rate=16000, channels=1, bit_depth=16 ) async def _detect_audio_format(self, audio_data: bytes) -> AudioFormat: """ Detect the format of audio data. This is a simplified implementation. In production, you would use libraries like python-magic or analyze audio headers. """ # Check for WAV header if audio_data.startswith(b'RIFF') and b'WAVE' in audio_data[:12]: return await self._parse_wav_header(audio_data) # Check for WebM header if audio_data.startswith(b'\x1a\x45\xdf\xa3'): return AudioFormat(format="webm", sample_rate=16000, channels=1, bit_depth=16, codec="opus") # Check for MP3 header if audio_data.startswith(b'ID3') or audio_data.startswith(b'\xff\xfb'): return AudioFormat(format="mp3", sample_rate=44100, channels=2, bit_depth=16) # Default assumption for unknown formats logger.warning("Could not detect audio format, assuming WAV 16kHz mono") return AudioFormat(format="wav", sample_rate=16000, channels=1, bit_depth=16) async def _parse_wav_header(self, audio_data: bytes) -> AudioFormat: """Parse WAV file header to extract format information.""" try: # WAV header parsing (simplified) if len(audio_data) < 44: raise AudioProcessingError("format_detection", "WAV file too small") # Extract format information from WAV header channels = struct.unpack('<H', audio_data[22:24])[0] sample_rate = struct.unpack('<I', audio_data[24:28])[0] bits_per_sample = struct.unpack('<H', audio_data[34:36])[0] return AudioFormat( format="wav", sample_rate=sample_rate, channels=channels, bit_depth=bits_per_sample ) except Exception as e: logger.warning(f"Failed to parse WAV header: {e}") return self._get_default_format() def _needs_conversion(self, input_format: AudioFormat, target_format: AudioFormat) -> bool: """Check if audio format conversion is needed.""" return ( input_format.format != target_format.format or input_format.sample_rate != target_format.sample_rate or input_format.channels != target_format.channels or input_format.bit_depth != target_format.bit_depth ) async def convert_format( self, audio_data: bytes, source_format: str, target_format: str, **kwargs ) -> bytes: """ Convert audio from one format to another. Args: audio_data: Raw audio bytes source_format: Current audio format target_format: Desired audio format **kwargs: Format-specific options (sample_rate, channels, bit_depth) Returns: Converted audio bytes Raises: UnsupportedFormatError: If format conversion is not supported AudioProcessingError: If conversion fails """ try: logger.debug(f"Converting audio from {source_format} to {target_format}") # Validate formats if not self._is_format_supported(source_format): raise UnsupportedFormatError("audio_processor", source_format, self.config.audio_processing.get("supported_formats", [])) if not self._is_format_supported(target_format): raise UnsupportedFormatError("audio_processor", target_format, self.config.audio_processing.get("supported_formats", [])) # If formats are the same, just resample/rechannelize if needed if source_format == target_format: return await self._resample_audio(audio_data, **kwargs) # Convert between different formats if source_format == "webm" and target_format == "wav": return await self._webm_to_wav(audio_data, **kwargs) elif source_format == "wav" and target_format == "webm": return await self._wav_to_webm(audio_data, **kwargs) elif source_format == "mp3" and target_format == "wav": return await self._mp3_to_wav(audio_data, **kwargs) elif source_format == "wav" and target_format == "mp3": return await self._wav_to_mp3(audio_data, **kwargs) else: # For unsupported conversions, use WAV as intermediate format if source_format != "wav": audio_data = await self.convert_format(audio_data, source_format, "wav", **kwargs) if target_format != "wav": audio_data = await self.convert_format(audio_data, "wav", target_format, **kwargs) return audio_data except UnsupportedFormatError: # Re-raise UnsupportedFormatError without wrapping raise except Exception as e: logger.error(f"Format conversion failed: {e}") raise AudioProcessingError("format_conversion", f"Failed to convert {source_format} to {target_format}: {e}") def _is_format_supported(self, format_str: str) -> bool: """Check if an audio format is supported.""" supported_formats = self.config.audio_processing.get("supported_formats", ["webm", "wav", "mp3", "ogg"]) return format_str.lower() in supported_formats async def _resample_audio(self, audio_data: bytes, **kwargs) -> bytes: """ Resample audio to different sample rate/channels/bit depth. This is a placeholder implementation. In production, you would use libraries like librosa, scipy, or pydub for actual resampling. """ # Extract parameters target_sample_rate = kwargs.get("sample_rate", 16000) target_channels = kwargs.get("channels", 1) target_bit_depth = kwargs.get("bit_depth", 16) logger.debug(f"Resampling audio to {target_sample_rate}Hz, {target_channels} channels, {target_bit_depth}-bit") # For now, return the original data # In a real implementation, this would perform actual resampling return audio_data async def _webm_to_wav(self, audio_data: bytes, **kwargs) -> bytes: """Convert WebM audio to WAV format.""" # Placeholder implementation # In production, use ffmpeg-python or similar library logger.debug("Converting WebM to WAV (placeholder)") # Create a simple WAV header for the converted audio sample_rate = kwargs.get("sample_rate", 16000) channels = kwargs.get("channels", 1) bit_depth = kwargs.get("bit_depth", 16) # This is a simplified conversion - in reality you'd decode WebM/Opus return await self._create_wav_with_header(audio_data, sample_rate, channels, bit_depth) async def _wav_to_webm(self, audio_data: bytes, **kwargs) -> bytes: """Convert WAV audio to WebM format.""" # Placeholder implementation logger.debug("Converting WAV to WebM (placeholder)") # In production, use ffmpeg-python to encode to WebM/Opus return audio_data async def _mp3_to_wav(self, audio_data: bytes, **kwargs) -> bytes: """Convert MP3 audio to WAV format.""" # Placeholder implementation logger.debug("Converting MP3 to WAV (placeholder)") # In production, use pydub or similar library return audio_data async def _wav_to_mp3(self, audio_data: bytes, **kwargs) -> bytes: """Convert WAV audio to MP3 format.""" # Placeholder implementation logger.debug("Converting WAV to MP3 (placeholder)") # In production, use pydub or similar library return audio_data async def _create_wav_with_header( self, audio_data: bytes, sample_rate: int, channels: int, bit_depth: int ) -> bytes: """Create WAV file with proper header.""" # Calculate sizes byte_rate = sample_rate * channels * bit_depth // 8 block_align = channels * bit_depth // 8 data_size = len(audio_data) file_size = 36 + data_size # Create WAV header header = struct.pack('<4sI4s4sIHHIIHH4sI', b'RIFF', # Chunk ID file_size, # Chunk size b'WAVE', # Format b'fmt ', # Subchunk1 ID 16, # Subchunk1 size 1, # Audio format (PCM) channels, # Number of channels sample_rate, # Sample rate byte_rate, # Byte rate block_align, # Block align bit_depth, # Bits per sample b'data', # Subchunk2 ID data_size # Subchunk2 size ) return header + audio_data async def detect_silence( self, audio_data: bytes, threshold: float = None ) -> List[AudioSegment]: """ Detect silence in audio and return non-silent segments. Enhanced implementation that: - Uses configurable silence detection parameters - Applies minimum segment duration filtering - Handles edge cases and audio format variations - Provides detailed segment timing information Args: audio_data: Raw audio bytes threshold: Silence detection threshold (0.0 to 1.0), uses config default if None Returns: List of AudioSegment objects for non-silent parts """ try: # Use configured threshold if not provided if threshold is None: threshold = self.config.audio_processing.get("silence_threshold", 0.01) # Get additional silence detection parameters from config min_silence_duration = self.config.audio_processing.get("min_silence_duration", 0.5) # seconds min_speech_duration = self.config.audio_processing.get("min_speech_duration", 0.1) # seconds window_size_ms = self.config.audio_processing.get("silence_window_size_ms", 50) # milliseconds logger.debug(f"Detecting silence with threshold {threshold}, min_silence={min_silence_duration}s, min_speech={min_speech_duration}s") # Parse audio format to get sample information audio_format = await self._detect_audio_format(audio_data) # Extract audio samples samples = await self._extract_audio_samples(audio_data, audio_format) if not samples or len(samples) == 0: logger.warning("No audio samples found, returning empty segments") return [] # Detect silence segments with enhanced algorithm segments = await self._analyze_silence_enhanced( samples, audio_format, threshold, min_silence_duration, min_speech_duration, window_size_ms ) # Filter out segments that are too short filtered_segments = [] for segment in segments: if segment.duration >= min_speech_duration: filtered_segments.append(segment) else: logger.debug(f"Filtered out short segment: {segment.duration:.3f}s < {min_speech_duration}s") logger.debug(f"Detected {len(filtered_segments)} non-silent segments (filtered from {len(segments)})") # If no valid segments found, return entire audio as fallback if not filtered_segments: logger.info("No valid speech segments found, returning entire audio") duration = len(samples) / audio_format.sample_rate return [AudioSegment( data=audio_data, start_time=0.0, end_time=duration, sample_rate=audio_format.sample_rate, channels=audio_format.channels, format=audio_format.format )] return filtered_segments except Exception as e: logger.error(f"Silence detection failed: {e}") # Return single segment containing all audio as fallback duration = await self._estimate_audio_duration(audio_data) return [AudioSegment( data=audio_data, start_time=0.0, end_time=duration, sample_rate=16000, channels=1, format="wav" )] async def _extract_audio_samples(self, audio_data: bytes, audio_format: AudioFormat) -> List[float]: """Extract normalized audio samples from raw audio data.""" # This is a simplified implementation for WAV files if audio_format.format == "wav" and len(audio_data) > 44: # Skip WAV header (44 bytes) sample_data = audio_data[44:] # Convert bytes to samples based on bit depth if audio_format.bit_depth == 16: # 16-bit signed integers sample_count = len(sample_data) // 2 samples = struct.unpack(f'<{sample_count}h', sample_data[:sample_count * 2]) # Normalize to [-1.0, 1.0] return [sample / 32768.0 for sample in samples] elif audio_format.bit_depth == 8: # 8-bit unsigned integers samples = struct.unpack(f'{len(sample_data)}B', sample_data) # Normalize to [-1.0, 1.0] return [(sample - 128) / 128.0 for sample in samples] # Fallback: return zeros return [0.0] * 1000 async def _analyze_silence_enhanced( self, samples: List[float], audio_format: AudioFormat, threshold: float, min_silence_duration: float, min_speech_duration: float, window_size_ms: float ) -> List[AudioSegment]: """ Enhanced silence analysis with configurable parameters. Uses a more sophisticated algorithm that: - Applies smoothing to reduce false positives - Considers minimum durations for both silence and speech - Uses energy-based detection with RMS calculation - Handles edge cases at audio boundaries """ if not samples: return [] # Calculate window parameters window_size_samples = int(audio_format.sample_rate * window_size_ms / 1000) window_size_samples = max(1, window_size_samples) # Ensure at least 1 sample min_silence_samples = int(audio_format.sample_rate * min_silence_duration) min_speech_samples = int(audio_format.sample_rate * min_speech_duration) # Calculate energy for each window energy_values = [] for i in range(0, len(samples), window_size_samples): window = samples[i:i + window_size_samples] if window: # Calculate RMS energy rms = (sum(sample ** 2 for sample in window) / len(window)) ** 0.5 energy_values.append(rms) else: energy_values.append(0.0) # Apply smoothing to reduce noise in energy detection smoothed_energy = await self._smooth_energy_values(energy_values) # Classify windows as speech or silence is_speech = [energy > threshold for energy in smoothed_energy] # Find speech segments with minimum duration requirements segments = [] current_segment_start = None for i, speech_detected in enumerate(is_speech): window_start_time = i * window_size_ms / 1000 if speech_detected and current_segment_start is None: # Potential start of speech segment current_segment_start = window_start_time elif not speech_detected and current_segment_start is not None: # Potential end of speech segment segment_duration = window_start_time - current_segment_start # Check if segment meets minimum duration if segment_duration >= min_speech_duration: # Extract actual audio data for this segment start_sample = int(current_segment_start * audio_format.sample_rate) end_sample = int(window_start_time * audio_format.sample_rate) segment_data = await self._extract_segment_data( samples[start_sample:end_sample], audio_format ) segments.append(AudioSegment( data=segment_data, start_time=current_segment_start, end_time=window_start_time, sample_rate=audio_format.sample_rate, channels=audio_format.channels, format=audio_format.format )) current_segment_start = None # Handle case where audio ends during speech if current_segment_start is not None: final_end_time = len(samples) / audio_format.sample_rate segment_duration = final_end_time - current_segment_start if segment_duration >= min_speech_duration: start_sample = int(current_segment_start * audio_format.sample_rate) segment_data = await self._extract_segment_data( samples[start_sample:], audio_format ) segments.append(AudioSegment( data=segment_data, start_time=current_segment_start, end_time=final_end_time, sample_rate=audio_format.sample_rate, channels=audio_format.channels, format=audio_format.format )) return segments async def _smooth_energy_values(self, energy_values: List[float]) -> List[float]: """Apply smoothing to energy values to reduce false positives.""" if len(energy_values) < 3: return energy_values # Simple moving average smoothing smoothed = [] window_size = 3 for i in range(len(energy_values)): start_idx = max(0, i - window_size // 2) end_idx = min(len(energy_values), i + window_size // 2 + 1) window_values = energy_values[start_idx:end_idx] smoothed.append(sum(window_values) / len(window_values)) return smoothed async def _extract_segment_data(self, segment_samples: List[float], audio_format: AudioFormat) -> bytes: """Extract audio data for a specific segment.""" if not segment_samples: return b'' # Convert samples back to bytes segment_bytes = await self._samples_to_bytes(segment_samples, audio_format) # Add WAV header if needed if audio_format.format == "wav": return await self._create_wav_with_header( segment_bytes, audio_format.sample_rate, audio_format.channels, audio_format.bit_depth ) return segment_bytes async def _estimate_audio_duration(self, audio_data: bytes) -> float: """Estimate audio duration for fallback cases.""" try: audio_format = await self._detect_audio_format(audio_data) return await self._calculate_duration(audio_data, audio_format) except Exception: # Very rough estimate: assume 16kHz, 16-bit, mono return len(audio_data) / (16000 * 2) async def _analyze_silence( self, samples: List[float], audio_format: AudioFormat, threshold: float ) -> List[AudioSegment]: """ Legacy silence analysis method (kept for backward compatibility). This method is now deprecated in favor of _analyze_silence_enhanced. """ # Delegate to enhanced method with default parameters return await self._analyze_silence_enhanced( samples, audio_format, threshold, min_silence_duration=0.5, min_speech_duration=0.1, window_size_ms=50 ) async def _remove_silence_segments(self, audio_data: bytes, segments: List[AudioSegment]) -> bytes: """Remove silence from audio data based on detected segments.""" # This is a placeholder implementation # In production, you would extract and concatenate the non-silent segments logger.debug(f"Removing silence from {len(segments)} segments") return audio_data async def apply_noise_reduction( self, audio_data: bytes, strength: float = None ) -> bytes: """ Apply noise reduction to audio data. Enhanced implementation that: - Uses configurable noise reduction algorithms - Supports multiple noise reduction techniques - Adapts to different audio characteristics - Preserves audio quality while reducing noise Args: audio_data: Raw audio bytes strength: Noise reduction strength (0.0 to 1.0), uses config default if None Returns: Processed audio bytes with reduced noise """ try: # Use configured strength if not provided if strength is None: strength = self.config.audio_processing.get("noise_reduction_strength", 0.5) # Clamp strength to valid range strength = clamp(strength, 0.0, 1.0) # Get noise reduction configuration algorithm = self.config.audio_processing.get("noise_reduction_algorithm", "spectral_subtraction") adaptive = self.config.audio_processing.get("noise_reduction_adaptive", True) preserve_speech = self.config.audio_processing.get("noise_reduction_preserve_speech", True) logger.debug(f"Applying noise reduction: algorithm={algorithm}, strength={strength}, adaptive={adaptive}") # Skip processing if strength is zero if strength == 0.0: logger.debug("Noise reduction strength is 0.0, skipping processing") return audio_data # Detect audio format and extract samples audio_format = await self._detect_audio_format(audio_data) samples = await self._extract_audio_samples(audio_data, audio_format) if not samples: logger.warning("No audio samples found for noise reduction") return audio_data # Apply noise reduction based on selected algorithm if algorithm == "spectral_subtraction": processed_samples = await self._apply_spectral_subtraction( samples, audio_format, strength, adaptive ) elif algorithm == "wiener_filter": processed_samples = await self._apply_wiener_filter( samples, audio_format, strength ) elif algorithm == "adaptive_filter": processed_samples = await self._apply_adaptive_filter( samples, audio_format, strength ) else: logger.warning(f"Unknown noise reduction algorithm: {algorithm}, using spectral subtraction") processed_samples = await self._apply_spectral_subtraction( samples, audio_format, strength, adaptive ) # Apply speech preservation if enabled if preserve_speech: processed_samples = await self._preserve_speech_characteristics( samples, processed_samples, audio_format ) # Convert back to bytes processed_bytes = await self._samples_to_bytes(processed_samples, audio_format) # Reconstruct audio with proper headers if audio_format.format == "wav": return await self._create_wav_with_header( processed_bytes, audio_format.sample_rate, audio_format.channels, audio_format.bit_depth ) return processed_bytes except Exception as e: logger.error(f"Noise reduction failed: {e}") # Return original audio on failure return audio_data async def _apply_spectral_subtraction( self, samples: List[float], audio_format: AudioFormat, strength: float, adaptive: bool ) -> List[float]: """ Apply spectral subtraction noise reduction. This is a simplified implementation. In production, you would use libraries like librosa, scipy, or noisereduce for proper spectral analysis. """ # Estimate noise profile from the first 0.5 seconds (assumed to be mostly noise) noise_samples = min(int(0.5 * audio_format.sample_rate), len(samples) // 4) noise_profile = samples[:noise_samples] if noise_samples > 0 else samples[:100] # Calculate noise energy noise_energy = sum(sample ** 2 for sample in noise_profile) / len(noise_profile) if noise_profile else 0.01 # Apply spectral subtraction (simplified) processed_samples = [] window_size = 512 # Small window for processing for i in range(0, len(samples), window_size): window = samples[i:i + window_size] if not window: break # Calculate window energy window_energy = sum(sample ** 2 for sample in window) / len(window) # Determine noise reduction factor if adaptive: # Adaptive: reduce more noise in low-energy regions snr_estimate = window_energy / (noise_energy + 1e-10) reduction_factor = strength * (1.0 / (1.0 + snr_estimate)) else: # Fixed reduction reduction_factor = strength * 0.5 # Apply noise reduction for sample in window: # Simple noise gate with spectral subtraction approximation if abs(sample) > noise_energy ** 0.5: # Likely speech, apply minimal reduction processed_sample = sample * (1.0 - reduction_factor * 0.3) else: # Likely noise, apply stronger reduction processed_sample = sample * (1.0 - reduction_factor) processed_samples.append(processed_sample) return processed_samples async def _apply_wiener_filter( self, samples: List[float], audio_format: AudioFormat, strength: float ) -> List[float]: """ Apply Wiener filter for noise reduction. Simplified implementation of Wiener filtering. """ # Estimate signal and noise power signal_power = sum(sample ** 2 for sample in samples) / len(samples) # Estimate noise from quiet portions (simplified) sorted_samples = sorted(abs(sample) for sample in samples) noise_threshold_idx = int(len(sorted_samples) * 0.1) # Bottom 10% assumed to be noise noise_power = sum(sorted_samples[:noise_threshold_idx]) / max(1, noise_threshold_idx) noise_power = noise_power ** 2 # Calculate Wiener filter coefficient wiener_coeff = signal_power / (signal_power + noise_power + 1e-10) # Apply filter with strength adjustment filter_strength = strength * wiener_coeff processed_samples = [sample * (1.0 - filter_strength + filter_strength * wiener_coeff) for sample in samples] return processed_samples async def _apply_adaptive_filter( self, samples: List[float], audio_format: AudioFormat, strength: float ) -> List[float]: """ Apply adaptive noise reduction filter. Uses a simple adaptive algorithm that adjusts based on local signal characteristics. """ processed_samples = [] window_size = 256 for i in range(len(samples)): # Define local window around current sample start_idx = max(0, i - window_size // 2) end_idx = min(len(samples), i + window_size // 2) local_window = samples[start_idx:end_idx] # Calculate local statistics local_mean = sum(local_window) / len(local_window) local_variance = sum((s - local_mean) ** 2 for s in local_window) / len(local_window) local_std = local_variance ** 0.5 # Adaptive threshold based on local characteristics adaptive_threshold = local_std * (1.0 + strength) # Apply noise reduction current_sample = samples[i] if abs(current_sample - local_mean) > adaptive_threshold: # Likely signal, preserve processed_samples.append(current_sample) else: # Likely noise, reduce reduction = strength * 0.7 processed_samples.append(current_sample * (1.0 - reduction)) return processed_samples async def _preserve_speech_characteristics( self, original_samples: List[float], processed_samples: List[float], audio_format: AudioFormat ) -> List[float]: """ Preserve important speech characteristics after noise reduction. This helps maintain speech intelligibility and naturalness. """ if len(original_samples) != len(processed_samples): logger.warning("Sample length mismatch in speech preservation") return processed_samples # Calculate speech activity detection speech_regions = await self._detect_speech_activity(original_samples, audio_format) # Blend original and processed audio in speech regions preserved_samples = [] for i, (original, processed) in enumerate(zip(original_samples, processed_samples)): # Check if current sample is in a speech region current_time = i / audio_format.sample_rate is_speech_region = any(start <= current_time <= end for start, end in speech_regions) if is_speech_region: # In speech regions, blend more towards original blend_factor = 0.7 # 70% original, 30% processed final_sample = blend_factor * original + (1 - blend_factor) * processed else: # In non-speech regions, use more processed audio blend_factor = 0.3 # 30% original, 70% processed final_sample = blend_factor * original + (1 - blend_factor) * processed preserved_samples.append(final_sample) return preserved_samples async def _detect_speech_activity( self, samples: List[float], audio_format: AudioFormat ) -> List[tuple]: """ Detect regions of speech activity for preservation. Returns list of (start_time, end_time) tuples for speech regions. """ speech_regions = [] window_size = audio_format.sample_rate // 20 # 50ms windows speech_threshold = 0.02 # Energy threshold for speech detection current_speech_start = None for i in range(0, len(samples), window_size): window = samples[i:i + window_size] if not window: break # Calculate window energy window_energy = sum(sample ** 2 for sample in window) / len(window) window_time = i / audio_format.sample_rate if window_energy > speech_threshold and current_speech_start is None: # Start of speech region current_speech_start = window_time elif window_energy <= speech_threshold and current_speech_start is not None: # End of speech region speech_regions.append((current_speech_start, window_time)) current_speech_start = None # Handle case where speech continues to end of audio if current_speech_start is not None: speech_regions.append((current_speech_start, len(samples) / audio_format.sample_rate)) return speech_regions async def chunk_audio( self, audio_data: bytes, chunk_duration: float = None, overlap: float = None, **kwargs ) -> List[AudioSegment]: """ Split audio into chunks of specified duration with configurable parameters. Enhanced implementation that: - Uses configurable chunk sizes based on provider requirements - Supports intelligent chunking at silence boundaries - Handles different overlap strategies - Optimizes chunk sizes for different providers Args: audio_data: Raw audio bytes chunk_duration: Duration of each chunk in seconds (uses config default if None) overlap: Overlap between chunks in seconds (uses config default if None) **kwargs: Additional chunking options: - provider: Target provider for optimization - boundary_detection: Whether to chunk at silence boundaries - min_chunk_duration: Minimum chunk duration - max_chunk_duration: Maximum chunk duration Returns: List of AudioSegment objects """ try: # Use configured defaults if not provided if chunk_duration is None: chunk_duration = self.config.audio_processing.get("default_chunk_duration", 30.0) if overlap is None: overlap = self.config.audio_processing.get("default_chunk_overlap", 0.0) # Get additional configuration provider = kwargs.get("provider", None) boundary_detection = kwargs.get("boundary_detection", self.config.audio_processing.get("chunk_at_silence_boundaries", True)) min_chunk_duration = kwargs.get("min_chunk_duration", self.config.audio_processing.get("min_chunk_duration", 1.0)) max_chunk_duration = kwargs.get("max_chunk_duration", self.config.audio_processing.get("max_chunk_duration", 60.0)) # Optimize chunk parameters for specific provider if provider: chunk_duration, overlap = await self._optimize_chunking_for_provider( provider, chunk_duration, overlap ) # Validate parameters chunk_duration = clamp(chunk_duration, min_chunk_duration, max_chunk_duration) overlap = clamp(overlap, 0.0, chunk_duration * 0.8) # Max 80% overlap logger.debug(f"Chunking audio: duration={chunk_duration}s, overlap={overlap}s, " f"boundary_detection={boundary_detection}, provider={provider}") # Detect audio format audio_format = await self._detect_audio_format(audio_data) # Calculate total audio duration total_duration = await self._calculate_duration(audio_data, audio_format) # If audio is shorter than chunk duration, return as single chunk if total_duration <= chunk_duration: logger.debug(f"Audio duration ({total_duration:.2f}s) <= chunk duration ({chunk_duration}s), returning single chunk") return [AudioSegment( data=audio_data, start_time=0.0, end_time=total_duration, sample_rate=audio_format.sample_rate, channels=audio_format.channels, format=audio_format.format )] # Choose chunking strategy if boundary_detection: chunks = await self._chunk_at_boundaries( audio_data, audio_format, chunk_duration, overlap, min_chunk_duration, max_chunk_duration ) else: chunks = await self._chunk_fixed_duration( audio_data, audio_format, chunk_duration, overlap ) # Post-process chunks chunks = await self._post_process_chunks(chunks, min_chunk_duration) logger.debug(f"Created {len(chunks)} audio chunks") return chunks except Exception as e: logger.error(f"Audio chunking failed: {e}") raise AudioProcessingError("chunking", f"Failed to chunk audio: {e}") async def _optimize_chunking_for_provider( self, provider: str, default_duration: float, default_overlap: float ) -> tuple: """ Optimize chunking parameters for specific provider requirements. Different providers have different optimal chunk sizes and processing characteristics. """ provider_lower = provider.lower() # Provider-specific optimizations if "web_speech" in provider_lower: # Web Speech API works well with shorter chunks for real-time processing optimal_duration = min(default_duration, 10.0) optimal_overlap = 0.5 # Small overlap for continuity elif "google" in provider_lower: # Google Speech-to-Text handles longer chunks well optimal_duration = min(default_duration, 60.0) optimal_overlap = default_overlap elif "azure" in provider_lower: # Azure Speech Services optimal chunk size optimal_duration = min(default_duration, 30.0) optimal_overlap = default_overlap elif "assembly" in provider_lower: # AssemblyAI works well with medium chunks optimal_duration = min(default_duration, 45.0) optimal_overlap = default_overlap elif "deepgram" in provider_lower: # Deepgram can handle longer chunks efficiently optimal_duration = min(default_duration, 120.0) optimal_overlap = default_overlap else: # Unknown provider, use defaults optimal_duration = default_duration optimal_overlap = default_overlap logger.debug(f"Optimized chunking for {provider}: duration={optimal_duration}s, overlap={optimal_overlap}s") return optimal_duration, optimal_overlap async def _chunk_at_boundaries( self, audio_data: bytes, audio_format: AudioFormat, target_duration: float, overlap: float, min_duration: float, max_duration: float ) -> List[AudioSegment]: """ Chunk audio at silence boundaries for more natural breaks. This approach tries to split audio at natural pauses rather than arbitrary time boundaries, which can improve transcription accuracy. """ # First, detect silence boundaries silence_segments = await self.detect_silence(audio_data) if not silence_segments: # Fallback to fixed duration chunking return await self._chunk_fixed_duration(audio_data, audio_format, target_duration, overlap) # Extract silence boundary times boundary_times = [0.0] # Start with beginning for segment in silence_segments: boundary_times.extend([segment.start_time, segment.end_time]) total_duration = await self._calculate_duration(audio_data, audio_format) boundary_times.append(total_duration) # Add end # Remove duplicates and sort boundary_times = sorted(set(boundary_times)) # Create chunks based on boundaries chunks = [] current_chunk_start = 0.0 for boundary_time in boundary_times[1:]: # Skip first boundary (0.0) potential_chunk_duration = boundary_time - current_chunk_start # Check if we should create a chunk if potential_chunk_duration >= target_duration or boundary_time == total_duration: # Create chunk chunk_start = max(0.0, current_chunk_start - overlap) chunk_end = boundary_time # Ensure chunk doesn't exceed maximum duration if chunk_end - chunk_start > max_duration: # Split into multiple fixed-duration chunks sub_chunks = await self._create_fixed_chunks_in_range( audio_data, audio_format, chunk_start, chunk_end, target_duration, overlap ) chunks.extend(sub_chunks) else: # Create single chunk chunk_data = await self._extract_audio_range( audio_data, audio_format, chunk_start, chunk_end ) chunks.append(AudioSegment( data=chunk_data, start_time=chunk_start, end_time=chunk_end, sample_rate=audio_format.sample_rate, channels=audio_format.channels, format=audio_format.format )) current_chunk_start = boundary_time - overlap return chunks async def _chunk_fixed_duration( self, audio_data: bytes, audio_format: AudioFormat, chunk_duration: float, overlap: float ) -> List[AudioSegment]: """ Chunk audio into fixed-duration segments. This is the traditional approach that splits audio at regular intervals. """ # Extract samples for processing samples = await self._extract_audio_samples(audio_data, audio_format) # Calculate chunk parameters samples_per_chunk = int(chunk_duration * audio_format.sample_rate) overlap_samples = int(overlap * audio_format.sample_rate) step_size = samples_per_chunk - overlap_samples chunks = [] for i in range(0, len(samples), step_size): chunk_samples = samples[i:i + samples_per_chunk] # Skip very short chunks at the end if len(chunk_samples) < samples_per_chunk // 2: break start_time = i / audio_format.sample_rate end_time = (i + len(chunk_samples)) / audio_format.sample_rate # Convert samples back to bytes chunk_data = await self._samples_to_bytes(chunk_samples, audio_format) # Add proper audio headers if audio_format.format == "wav": chunk_data = await self._create_wav_with_header( chunk_data, audio_format.sample_rate, audio_format.channels, audio_format.bit_depth ) chunks.append(AudioSegment( data=chunk_data, start_time=start_time, end_time=end_time, sample_rate=audio_format.sample_rate, channels=audio_format.channels, format=audio_format.format )) return chunks async def _create_fixed_chunks_in_range( self, audio_data: bytes, audio_format: AudioFormat, start_time: float, end_time: float, chunk_duration: float, overlap: float ) -> List[AudioSegment]: """Create fixed-duration chunks within a specific time range.""" chunks = [] current_time = start_time while current_time < end_time: chunk_end = min(current_time + chunk_duration, end_time) chunk_data = await self._extract_audio_range( audio_data, audio_format, current_time, chunk_end ) chunks.append(AudioSegment( data=chunk_data, start_time=current_time, end_time=chunk_end, sample_rate=audio_format.sample_rate, channels=audio_format.channels, format=audio_format.format )) current_time += chunk_duration - overlap return chunks async def _extract_audio_range( self, audio_data: bytes, audio_format: AudioFormat, start_time: float, end_time: float ) -> bytes: """Extract audio data for a specific time range.""" # Extract samples samples = await self._extract_audio_samples(audio_data, audio_format) # Calculate sample indices start_sample = int(start_time * audio_format.sample_rate) end_sample = int(end_time * audio_format.sample_rate) # Extract range range_samples = samples[start_sample:end_sample] # Convert back to bytes range_bytes = await self._samples_to_bytes(range_samples, audio_format) # Add headers if needed if audio_format.format == "wav": return await self._create_wav_with_header( range_bytes, audio_format.sample_rate, audio_format.channels, audio_format.bit_depth ) return range_bytes async def _post_process_chunks( self, chunks: List[AudioSegment], min_duration: float ) -> List[AudioSegment]: """ Post-process chunks to ensure quality and consistency. - Filters out chunks that are too short - Merges adjacent short chunks if beneficial - Validates chunk integrity """ if not chunks: return chunks processed_chunks = [] for chunk in chunks: # Filter out chunks that are too short if chunk.duration >= min_duration: processed_chunks.append(chunk) else: logger.debug(f"Filtered out short chunk: {chunk.duration:.3f}s < {min_duration}s") # If we filtered out too many chunks, try to merge short chunks if len(processed_chunks) < len(chunks) * 0.5 and len(chunks) > 1: logger.debug("Too many chunks filtered, attempting to merge short chunks") processed_chunks = await self._merge_short_chunks(chunks, min_duration) return processed_chunks async def _merge_short_chunks( self, chunks: List[AudioSegment], min_duration: float ) -> List[AudioSegment]: """ Merge adjacent short chunks to meet minimum duration requirements. """ if not chunks: return chunks merged_chunks = [] current_merge_group = [] for chunk in chunks: current_merge_group.append(chunk) # Calculate total duration of current merge group total_duration = sum(c.duration for c in current_merge_group) if total_duration >= min_duration: # Merge group meets minimum duration if len(current_merge_group) == 1: # Single chunk, add as-is merged_chunks.append(current_merge_group[0]) else: # Multiple chunks, merge them merged_chunk = await self._merge_chunk_group(current_merge_group) merged_chunks.append(merged_chunk) current_merge_group = [] # Handle remaining chunks in merge group if current_merge_group: if len(current_merge_group) == 1: merged_chunks.append(current_merge_group[0]) else: merged_chunk = await self._merge_chunk_group(current_merge_group) merged_chunks.append(merged_chunk) return merged_chunks async def _merge_chunk_group(self, chunk_group: List[AudioSegment]) -> AudioSegment: """ Merge a group of adjacent chunks into a single chunk. """ if not chunk_group: raise ValueError("Cannot merge empty chunk group") if len(chunk_group) == 1: return chunk_group[0] # Sort chunks by start time sorted_chunks = sorted(chunk_group, key=lambda c: c.start_time) # Combine audio data (simplified - assumes compatible formats) combined_data = b''.join(chunk.data for chunk in sorted_chunks) # Calculate merged chunk properties start_time = sorted_chunks[0].start_time end_time = sorted_chunks[-1].end_time return AudioSegment( data=combined_data, start_time=start_time, end_time=end_time, sample_rate=sorted_chunks[0].sample_rate, channels=sorted_chunks[0].channels, format=sorted_chunks[0].format ) async def _samples_to_bytes(self, samples: List[float], audio_format: AudioFormat) -> bytes: """Convert normalized samples back to bytes.""" if audio_format.bit_depth == 16: # Convert to 16-bit signed integers int_samples = [int(clamp(sample * 32767, -32768, 32767)) for sample in samples] return struct.pack(f'<{len(int_samples)}h', *int_samples) elif audio_format.bit_depth == 8: # Convert to 8-bit unsigned integers int_samples = [int(clamp((sample + 1.0) * 127.5, 0, 255)) for sample in samples] return struct.pack(f'{len(int_samples)}B', *int_samples) else: # Fallback return b'\x00' * len(samples) * 2 async def _apply_compression( self, audio_data: bytes, audio_format: AudioFormat, provider: str ) -> float: """ Apply audio compression optimized for the provider. Returns: Compression ratio achieved """ # This is a placeholder implementation # In production, you would apply provider-specific compression # For example: # - WebM/Opus for Web Speech API and Deepgram # - Compressed WAV for Google/Azure/AssemblyAI original_size = len(audio_data) # Simulate compression based on provider preferences if "webm" in audio_format.format or "opus" in str(audio_format.codec): # Opus compression typically achieves 8:1 ratio compression_ratio = 0.125 elif audio_format.format == "mp3": # MP3 compression typically achieves 10:1 ratio compression_ratio = 0.1 else: # Uncompressed formats compression_ratio = 1.0 logger.debug(f"Applied compression for {provider}: {compression_ratio:.2f} ratio") return compression_ratio async def _calculate_duration(self, audio_data: bytes, audio_format: AudioFormat) -> float: """Calculate the duration of audio data.""" try: if audio_format.format == "wav" and len(audio_data) > 44: # For WAV files, calculate from data size data_size = len(audio_data) - 44 # Subtract header size bytes_per_sample = audio_format.bit_depth // 8 samples_per_second = audio_format.sample_rate * audio_format.channels bytes_per_second = samples_per_second * bytes_per_sample if bytes_per_second > 0: return data_size / bytes_per_second # Fallback estimation # Assume 16kHz, 16-bit, mono for unknown formats estimated_bytes_per_second = 16000 * 2 * 1 # 32KB/s return len(audio_data) / estimated_bytes_per_second except Exception as e: logger.warning(f"Duration calculation failed: {e}") return 1.0 # Default fallback
"""
Audio processing and optimization for the voice control system.
This module provides audio format conversion, compression, noise reduction,
and provider-specific optimization for speech-to-text processing.
"""
import asyncio
import logging
import io
import struct
import wave
from typing import List, Optional, Dict, Any, Tuple
from dataclasses import dataclass
from .interfaces import AudioProcessorInterface
from .models import ProcessedAudio, AudioSegment, ProviderType
from .exceptions import AudioProcessingError, UnsupportedFormatError
from .utils import generate_fingerprint, clamp
from .config import get_config
logger = logging.getLogger(__name__)
@dataclass
class AudioFormat:
"""Audio format specification."""
format: str
sample_rate: int
channels: int
bit_depth: int
codec: Optional[str] = None
class AudioProcessor(AudioProcessorInterface):
"""
Audio processor for optimizing audio data for different STT providers.
Handles format conversion, compression, noise reduction, and provider-specific
audio optimization to improve transcription accuracy and reduce bandwidth usage.
"""
def __init__(self):
"""Initialize the audio processor."""
self.config = get_config()
self._provider_formats = self._load_provider_formats()
self._format_converters = self._initialize_converters()
def _load_provider_formats(self) -> Dict[str, AudioFormat]:
"""Load optimal audio formats for each provider type."""
return {
ProviderType.WEB_SPEECH_API.value: AudioFormat(
format="webm",
sample_rate=16000,
channels=1,
bit_depth=16,
codec="opus"
),
ProviderType.GOOGLE_SPEECH.value: AudioFormat(
format="wav",
sample_rate=16000,
channels=1,
bit_depth=16
),
ProviderType.AZURE_SPEECH.value: AudioFormat(
format="wav",
sample_rate=16000,
channels=1,
bit_depth=16
),
ProviderType.ASSEMBLY_AI.value: AudioFormat(
format="wav",
sample_rate=16000,
channels=1,
bit_depth=16
),
ProviderType.DEEPGRAM.value: AudioFormat(
format="webm",
sample_rate=16000,
channels=1,
bit_depth=16,
codec="opus"
)
}
def _initialize_converters(self) -> Dict[str, Any]:
"""Initialize format converters (placeholder for actual audio libraries)."""
# In a real implementation, this would initialize audio processing libraries
# like pydub, librosa, or ffmpeg-python
return {}
async def optimize_for_provider(
self,
audio_data: bytes,
provider: str,
target_format: Optional[str] = None
) -> ProcessedAudio:
"""
Optimize audio for a specific provider.