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
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
"""
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)