""" Audio Transcription and NFL Commentary Processing Module. This module handles: 1. Whisper-based speech-to-text transcription optimized for NFL broadcasts 2. NFL-specific vocabulary enhancement and corrections 3. Audio preprocessing with noise filtering and normalization 4. Sports-specific text post-processing and standardization Key Components: - AudioTranscriber: Main class for speech recognition - NFLTextCorrector: Sports-specific text correction and enhancement - AudioPreprocessor: Audio loading and filtering utilities """ import re import subprocess from typing import Dict, List, Optional, Tuple import numpy as np from transformers import pipeline from config import ( AUDIO_MODEL_NAME, AUDIO_DEVICE, AUDIO_SAMPLE_RATE, AUDIO_MIN_DURATION, AUDIO_MIN_AMPLITUDE, AUDIO_HIGHPASS_FREQ, AUDIO_LOWPASS_FREQ, WHISPER_GENERATION_PARAMS, NFL_SPORTS_CONTEXT, NFL_TEAMS, NFL_POSITIONS, ENABLE_DEBUG_PRINTS ) class AudioPreprocessor: """ Audio preprocessing utilities for enhanced transcription quality. Handles audio loading, filtering, and normalization to optimize Whisper transcription for NFL broadcast content. """ def __init__(self, sample_rate: int = AUDIO_SAMPLE_RATE, highpass_freq: int = AUDIO_HIGHPASS_FREQ, lowpass_freq: int = AUDIO_LOWPASS_FREQ): """ Initialize audio preprocessor. Args: sample_rate: Target sample rate for audio highpass_freq: High-pass filter frequency (removes low rumble) lowpass_freq: Low-pass filter frequency (removes high noise) """ self.sample_rate = sample_rate self.highpass_freq = highpass_freq self.lowpass_freq = lowpass_freq def load_audio(self, path: str) -> Tuple[np.ndarray, int]: """ Load and preprocess audio from video file using FFmpeg. Applies noise filtering and normalization for optimal transcription. Args: path: Path to video/audio file Returns: Tuple of (audio_array, sample_rate) """ # Build FFmpeg command with audio filtering cmd = [ "ffmpeg", "-i", path, "-af", f"highpass=f={self.highpass_freq},lowpass=f={self.lowpass_freq},loudnorm", "-f", "s16le", # 16-bit signed little-endian "-acodec", "pcm_s16le", # PCM codec "-ac", "1", # Mono channel "-ar", str(self.sample_rate), # Sample rate "pipe:1" # Output to stdout ] try: # Run FFmpeg and capture audio data process = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL ) raw_audio = process.stdout.read() # Convert to numpy array and normalize to [-1, 1] audio = np.frombuffer(raw_audio, np.int16).astype(np.float32) / 32768.0 # Apply additional normalization if audio is present if len(audio) > 0: max_amplitude = np.max(np.abs(audio)) if max_amplitude > 0: audio = audio / (max_amplitude + 1e-8) # Prevent division by zero return audio, self.sample_rate except Exception as e: if ENABLE_DEBUG_PRINTS: print(f"[ERROR] Audio loading failed for {path}: {e}") return np.array([]), self.sample_rate def is_valid_audio(self, audio: np.ndarray) -> bool: """ Check if audio meets minimum quality requirements for transcription. Args: audio: Audio array to validate Returns: True if audio is suitable for transcription """ if len(audio) == 0: return False # Check minimum duration duration = len(audio) / self.sample_rate if duration < AUDIO_MIN_DURATION: return False # Check minimum amplitude (not too quiet) max_amplitude = np.max(np.abs(audio)) if max_amplitude < AUDIO_MIN_AMPLITUDE: return False return True class NFLTextCorrector: """ NFL-specific text correction and enhancement system. Applies sports vocabulary corrections, standardizes terminology, and fixes common transcription errors in NFL commentary. """ def __init__(self): """Initialize NFL text corrector with sports-specific rules.""" self.nfl_teams = NFL_TEAMS self.nfl_positions = NFL_POSITIONS self.sports_context = NFL_SPORTS_CONTEXT # Build correction dictionaries self._build_correction_patterns() def _build_correction_patterns(self) -> None: """Build regex patterns for common NFL terminology corrections.""" self.basic_corrections = { # Position corrections r'\bqb\b': "QB", r'\bquarter back\b': "quarterback", r'\bwide receiver\b': "wide receiver", r'\btight end\b': "tight end", r'\brunning back\b': "running back", r'\bline backer\b': "linebacker", r'\bcorner back\b': "cornerback", # Play corrections r'\btouch down\b': "touchdown", r'\bfield goal\b': "field goal", r'\bfirst down\b': "first down", r'\bsecond down\b': "second down", r'\bthird down\b': "third down", r'\bfourth down\b': "fourth down", r'\byard line\b': "yard line", r'\bend zone\b': "end zone", r'\bred zone\b': "red zone", r'\btwo minute warning\b': "two minute warning", # Common misheard words r'\bfourty\b': "forty", r'\bfourty yard\b': "forty yard", r'\btwenny\b': "twenty", r'\bthirty yard\b': "thirty yard", # Numbers/downs that are often misheard r'\b1st\b': "first", r'\b2nd\b': "second", r'\b3rd\b': "third", r'\b4th\b': "fourth", r'\b1st and 10\b': "first and ten", r'\b2nd and long\b': "second and long", r'\b3rd and short\b': "third and short", # Team name corrections (common mishears) r'\bforty niners\b': "49ers", r'\bforty-niners\b': "49ers", r'\bsan francisco\b': "49ers", r'\bnew england\b': "Patriots", r'\bgreen bay\b': "Packers", r'\bkansas city\b': "Chiefs", r'\bnew york giants\b': "Giants", r'\bnew york jets\b': "Jets", r'\blos angeles rams\b': "Rams", r'\blos angeles chargers\b': "Chargers", # Yard markers and positions r'\b10 yard line\b': "ten yard line", r'\b20 yard line\b': "twenty yard line", r'\b30 yard line\b': "thirty yard line", r'\b40 yard line\b': "forty yard line", r'\b50 yard line\b': "fifty yard line", r'\bmid field\b': "midfield", r'\bgoal line\b': "goal line", # Penalties and flags r'\bfalse start\b': "false start", r'\boff side\b': "offside", r'\bpass interference\b': "pass interference", r'\broughing the passer\b': "roughing the passer", r'\bdelay of game\b': "delay of game", # Common play calls r'\bplay action\b': "play action", r'\bscreen pass\b': "screen pass", r'\bdraw play\b': "draw play", r'\bboot leg\b': "bootleg", r'\broll out\b': "rollout", r'\bshot gun\b': "shotgun", r'\bno huddle\b': "no huddle" } self.fuzzy_corrections = { # Team names with common misspellings r'\bpatriots?\b': "Patriots", r'\bcowboys?\b': "Cowboys", r'\bpackers?\b': "Packers", r'\bchief\b': "Chiefs", r'\bchiefs?\b': "Chiefs", r'\beagles?\b': "Eagles", r'\bgiants?\b': "Giants", r'\brams?\b': "Rams", r'\bsaints?\b': "Saints", # Positions with common variations r'\bquarterbacks?\b': "quarterback", r'\brunning backs?\b': "running back", r'\bwide receivers?\b': "wide receiver", r'\btight ends?\b': "tight end", r'\blinebackers?\b': "linebacker", r'\bcornerbacks?\b': "cornerback", r'\bsafety\b': "safety", r'\bsafeties\b': "safety", # Play terms r'\btouchdowns?\b': "touchdown", r'\bfield goals?\b': "field goal", r'\binterceptions?\b': "interception", r'\bfumbles?\b': "fumble", r'\bsacks?\b': "sack", r'\bpunt\b': "punt", r'\bpunts?\b': "punt", # Numbers and yards r'\byards?\b': "yard", r'\byards? line\b': "yard line", r'\byard lines?\b': "yard line" } # Terms that should always be capitalized self.capitalization_terms = [ "NFL", "QB", "Patriots", "Cowboys", "Chiefs", "Packers", "49ers", "Eagles", "Giants", "Rams", "Saints", "Bills", "Ravens", "Steelers" ] def correct_text(self, text: str) -> str: """ Apply comprehensive NFL-specific text corrections. Args: text: Raw transcription text Returns: Corrected and standardized text """ if not text: return text corrected = text # Apply basic corrections corrected = self._apply_corrections(corrected, self.basic_corrections) # Apply fuzzy corrections corrected = self._apply_corrections(corrected, self.fuzzy_corrections) # Apply capitalization rules corrected = self._apply_capitalization(corrected) return corrected.strip() def _apply_corrections(self, text: str, corrections: Dict[str, str]) -> str: """Apply a set of regex corrections to text.""" corrected = text for pattern, replacement in corrections.items(): corrected = re.sub(pattern, replacement, corrected, flags=re.IGNORECASE) return corrected def _apply_capitalization(self, text: str) -> str: """Apply proper capitalization for NFL terms.""" corrected = text for term in self.capitalization_terms: pattern = r'\b' + re.escape(term.lower()) + r'\b' corrected = re.sub(pattern, term, corrected, flags=re.IGNORECASE) return corrected class AudioTranscriber: """ Whisper-based audio transcriber optimized for NFL broadcasts. Combines Whisper speech recognition with NFL-specific enhancements for high-quality sports commentary transcription. """ def __init__(self, model_name: str = AUDIO_MODEL_NAME, device: int = AUDIO_DEVICE): """ Initialize audio transcriber. Args: model_name: Whisper model name (base, medium, large) device: Device for inference (-1 for CPU, 0+ for GPU) """ self.model_name = model_name self.device = device self.preprocessor = AudioPreprocessor() self.corrector = NFLTextCorrector() # Initialize Whisper pipeline self._initialize_pipeline() def _initialize_pipeline(self) -> None: """Initialize the Whisper transcription pipeline.""" if ENABLE_DEBUG_PRINTS: print(f"Initializing Whisper pipeline: {self.model_name}") self.pipeline = pipeline( "automatic-speech-recognition", model=self.model_name, device=self.device, generate_kwargs=WHISPER_GENERATION_PARAMS ) if ENABLE_DEBUG_PRINTS: print("Whisper pipeline ready") def transcribe_clip(self, video_path: str) -> str: """ Transcribe audio from a video clip with NFL-specific enhancements. Args: video_path: Path to video file Returns: Transcribed and corrected text """ # Load and preprocess audio audio, sample_rate = self.preprocessor.load_audio(video_path) # Validate audio quality if not self.preprocessor.is_valid_audio(audio): return "" try: # Run Whisper transcription result = self.pipeline(audio, generate_kwargs=WHISPER_GENERATION_PARAMS) text = result.get("text", "").strip() # Clean up common Whisper artifacts text = self._clean_whisper_artifacts(text) # Apply NFL-specific corrections text = self.corrector.correct_text(text) return text except Exception as e: if ENABLE_DEBUG_PRINTS: print(f"[WARN] Transcription failed for {video_path}: {e}") return "" def _clean_whisper_artifacts(self, text: str) -> str: """Remove common Whisper transcription artifacts.""" # Remove placeholder text text = text.replace("[BLANK_AUDIO]", "") text = text.replace("♪", "") # Remove music notes text = text.replace("(music)", "") text = text.replace("[music]", "") # Clean up extra whitespace text = re.sub(r'\s+', ' ', text) return text.strip() # ============================================================================ # CONVENIENCE FUNCTIONS FOR BACKWARD COMPATIBILITY # ============================================================================ # Global instance for backward compatibility _audio_transcriber = None def get_audio_transcriber() -> AudioTranscriber: """Get global audio transcriber instance (lazy initialization).""" global _audio_transcriber if _audio_transcriber is None: _audio_transcriber = AudioTranscriber() return _audio_transcriber def transcribe_clip(path: str) -> str: """ Backward compatibility function for audio transcription. Args: path: Path to video file Returns: Transcribed text """ transcriber = get_audio_transcriber() return transcriber.transcribe_clip(path) def load_audio(path: str, sr: int = AUDIO_SAMPLE_RATE) -> Tuple[np.ndarray, int]: """ Backward compatibility function for audio loading. Args: path: Path to audio/video file sr: Sample rate (kept for compatibility) Returns: Tuple of (audio_array, sample_rate) """ preprocessor = AudioPreprocessor(sample_rate=sr) return preprocessor.load_audio(path) def apply_sports_corrections(text: str) -> str: """ Backward compatibility function for text corrections. Args: text: Text to correct Returns: Corrected text """ corrector = NFLTextCorrector() return corrector.correct_text(text) def fuzzy_sports_corrections(text: str) -> str: """ Backward compatibility function (now handled within NFLTextCorrector). Args: text: Text to correct Returns: Corrected text """ return apply_sports_corrections(text)