Jerry Hill commited on
Commit
ed2222b
·
1 Parent(s): bb1d98c

refactor for readability

Browse files
Files changed (8) hide show
  1. README.md +85 -20
  2. audio.py +462 -0
  3. classification.json +1652 -1
  4. config.py +163 -0
  5. inference.py +80 -455
  6. run_all_clips.py +49 -16
  7. transcripts.json +77 -1
  8. video.py +398 -0
README.md CHANGED
@@ -38,13 +38,22 @@ This inference pipeline is part of a larger AWS-based NFL play analysis system.
38
  +-------------------------| X3D |
39
  +-----+------+
40
  |
41
- v
42
- +-----+------+
43
- | Amazon S3: |
44
- | output- |
45
- | plays |
46
  +-----+------+
47
- |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  v
49
  +-----+------+
50
  | DynamoDB: |
@@ -52,20 +61,59 @@ This inference pipeline is part of a larger AWS-based NFL play analysis system.
52
  +------------+
53
  ```
54
 
55
- **This repository specifically implements the X3D classification component** that runs on SageMaker to analyze video clips and determine play scoring characteristics.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
  ## Repository Structure
58
 
59
  ```plaintext
60
- ├── data/ # Put your 2s video clips here (.mov or .mp4)
61
- ├── segments/ # Output directory for ContinuousScreenSplitter.swift
62
- ├── ContinuousScreenSplitter.swift # Swift tool to capture screen and split into 2s segments
63
- ├── inference.py # Main inference script: loads model and scores one clip
64
- ├── run_all_clips.py # Wrapper to iterate over all clips and save classification + transcripts
65
- ├── kinetics_classnames.json# Kinetics-400 label map (auto-downloaded on first run)
66
- ├── requirements.txt # Python dependencies
67
- ├── classification.json # Output file with video classification results
68
- ── transcripts.json # Output file with audio transcription results
 
 
 
 
 
 
69
  ```
70
 
71
  ## Prerequisites
@@ -135,9 +183,15 @@ python inference.py data/segment_000.mov
135
  ```
136
 
137
  This will:
138
- - Print the Top-5 predicted Kinetics-400 labels + probabilities for the given clip
139
- - Generate high-quality audio transcription using Whisper-Medium with NFL sports vocabulary
140
- - Save results to `classification.json` and `transcripts.json`
 
 
 
 
 
 
141
 
142
  ### 4. Process clips with optimized pipeline
143
 
@@ -284,10 +338,21 @@ After: "is the sixth best quarterback in the NFL"
284
  ### Pipeline Customization
285
 
286
  * **Processing phases**: Use `--video-only` for speed-critical applications
287
- * **Batch sizes**: Modify save frequency in `run_all_clips.py` (currently every 5 video clips, 3 audio clips)
288
  * **Testing**: Use `--max-clips N` to limit processing for development
289
  * **File output**: Customize output file names with `--classification-file`, `--transcript-file`, `--play-analysis-file`
290
 
 
 
 
 
 
 
 
 
 
 
 
291
  ## Troubleshooting
292
 
293
  ### Video Issues
 
38
  +-------------------------| X3D |
39
  +-----+------+
40
  |
 
 
 
 
 
41
  +-----+------+
42
+ | | |
43
+ v | v
44
+ +------+--+ | +---+--------+
45
+ | Amazon | | | SageMaker: |
46
+ | S3: | | | Whisper |
47
+ | output- | | | Audio |
48
+ | plays | | | Transcript |
49
+ +---------+ | +-----+------+
50
+ | |
51
+ | v
52
+ | +-----+------+
53
+ | | Amazon S3: |
54
+ | | play- |
55
+ | | transcripts|
56
+ | +------------+
57
  v
58
  +-----+------+
59
  | DynamoDB: |
 
61
  +------------+
62
  ```
63
 
64
+ **This repository implements both the X3D video classification and Whisper audio transcription components** that run on SageMaker to analyze video clips for play scoring characteristics and NFL commentary transcription. In the production architecture, Whisper transcription is applied only to identified plays rather than all video segments.
65
+
66
+ ### Local Processing Pipeline
67
+
68
+ The optimized processing pipeline separates video and audio analysis for maximum efficiency:
69
+
70
+ ```mermaid
71
+ graph TD
72
+ A[Video Clips] --> B[Phase 1: Video Analysis]
73
+ B --> C[X3D Classification]
74
+ B --> D[NFL Play State Analysis]
75
+ B --> E[Play Boundary Detection]
76
+
77
+ E --> F{Play Detected?}
78
+ F -->|Yes| G[Phase 2: Audio Analysis<br/>Play Clips Only]
79
+ F -->|No| H[Skip Audio]
80
+
81
+ G --> I[Whisper Transcription]
82
+ G --> J[NFL Sports Corrections]
83
+
84
+ C --> K[classification.json]
85
+ D --> L[play_analysis.json]
86
+ E --> L
87
+ I --> M[transcripts.json<br/>Play Audio Only]
88
+ J --> M
89
+ H --> N[No Transcript]
90
+
91
+ style B fill:#e1f5fe
92
+ style G fill:#f3e5f5
93
+ style F fill:#fff3e0
94
+ style K fill:#c8e6c9
95
+ style L fill:#c8e6c9
96
+ style M fill:#c8e6c9
97
+ ```
98
 
99
  ## Repository Structure
100
 
101
  ```plaintext
102
+ ├── config.py # 🔧 Central configuration and constants
103
+ ├── video.py # 🎬 Video classification and NFL play analysis
104
+ ├── audio.py # 🎙️ Audio transcription with NFL enhancements
105
+ ├── inference.py # 🔄 Backward compatibility interface
106
+ ├── run_all_clips.py # 🚀 Main processing pipeline orchestrator
107
+ ├── speed_test.py # Performance benchmarking tools
108
+ ├── data/ # 📼 Put your 2s video clips here (.mov or .mp4)
109
+ ├── segments/ # 📁 Output directory for ContinuousScreenSplitter.swift
110
+ ── ContinuousScreenSplitter.swift # 📱 Swift tool to capture screen and split into segments
111
+ ├── kinetics_classnames.json# 📋 Kinetics-400 label map (auto-downloaded on first run)
112
+ ├── requirements.txt # 📦 Python dependencies
113
+ ├── classification.json # 📊 Output: video classification results
114
+ ├── transcripts.json # 📝 Output: audio transcription results
115
+ ├── play_analysis.json # 🏈 Output: NFL play analysis and boundaries
116
+ └── ARCHITECTURE.md # 📖 Detailed architecture documentation
117
  ```
118
 
119
  ## Prerequisites
 
183
  ```
184
 
185
  This will:
186
+ - Run X3D video classification with NFL play state analysis
187
+ - Generate high-quality audio transcription using Whisper-Medium with NFL enhancements
188
+ - Print results to console and save to `classification.json` and `transcripts.json`
189
+
190
+ **🏗️ Modular Architecture**: The system now uses a clean modular design:
191
+ - `video.py`: Video classification and play analysis
192
+ - `audio.py`: Audio transcription with NFL corrections
193
+ - `config.py`: Centralized configuration management
194
+ - `inference.py`: Backward compatibility interface
195
 
196
  ### 4. Process clips with optimized pipeline
197
 
 
338
  ### Pipeline Customization
339
 
340
  * **Processing phases**: Use `--video-only` for speed-critical applications
341
+ * **Batch sizes**: Modify `VIDEO_SAVE_INTERVAL` and `AUDIO_SAVE_INTERVAL` in `config.py`
342
  * **Testing**: Use `--max-clips N` to limit processing for development
343
  * **File output**: Customize output file names with `--classification-file`, `--transcript-file`, `--play-analysis-file`
344
 
345
+ ### Modular Architecture Benefits
346
+
347
+ * **🔧 Easy Configuration**: All settings centralized in `config.py`
348
+ * **🎯 Focused Development**: Separate modules for video, audio, and configuration
349
+ * **🧪 Better Testing**: Individual modules can be tested in isolation
350
+ * **⚡ Performance Tuning**: Optimize video and audio processing independently
351
+ * **📈 Scalability**: Add new models or sports without affecting existing code
352
+ * **🔄 Backward Compatibility**: Existing scripts continue to work unchanged
353
+
354
+ See `ARCHITECTURE.md` for detailed technical documentation.
355
+
356
  ## Troubleshooting
357
 
358
  ### Video Issues
audio.py ADDED
@@ -0,0 +1,462 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Audio Transcription and NFL Commentary Processing Module.
3
+
4
+ This module handles:
5
+ 1. Whisper-based speech-to-text transcription optimized for NFL broadcasts
6
+ 2. NFL-specific vocabulary enhancement and corrections
7
+ 3. Audio preprocessing with noise filtering and normalization
8
+ 4. Sports-specific text post-processing and standardization
9
+
10
+ Key Components:
11
+ - AudioTranscriber: Main class for speech recognition
12
+ - NFLTextCorrector: Sports-specific text correction and enhancement
13
+ - AudioPreprocessor: Audio loading and filtering utilities
14
+ """
15
+
16
+ import re
17
+ import subprocess
18
+ from typing import Dict, List, Optional, Tuple
19
+
20
+ import numpy as np
21
+ from transformers import pipeline
22
+
23
+ from config import (
24
+ AUDIO_MODEL_NAME, AUDIO_DEVICE, AUDIO_SAMPLE_RATE, AUDIO_MIN_DURATION,
25
+ AUDIO_MIN_AMPLITUDE, AUDIO_HIGHPASS_FREQ, AUDIO_LOWPASS_FREQ,
26
+ WHISPER_GENERATION_PARAMS, NFL_SPORTS_CONTEXT, NFL_TEAMS, NFL_POSITIONS,
27
+ ENABLE_DEBUG_PRINTS
28
+ )
29
+
30
+
31
+ class AudioPreprocessor:
32
+ """
33
+ Audio preprocessing utilities for enhanced transcription quality.
34
+
35
+ Handles audio loading, filtering, and normalization to optimize
36
+ Whisper transcription for NFL broadcast content.
37
+ """
38
+
39
+ def __init__(self,
40
+ sample_rate: int = AUDIO_SAMPLE_RATE,
41
+ highpass_freq: int = AUDIO_HIGHPASS_FREQ,
42
+ lowpass_freq: int = AUDIO_LOWPASS_FREQ):
43
+ """
44
+ Initialize audio preprocessor.
45
+
46
+ Args:
47
+ sample_rate: Target sample rate for audio
48
+ highpass_freq: High-pass filter frequency (removes low rumble)
49
+ lowpass_freq: Low-pass filter frequency (removes high noise)
50
+ """
51
+ self.sample_rate = sample_rate
52
+ self.highpass_freq = highpass_freq
53
+ self.lowpass_freq = lowpass_freq
54
+
55
+ def load_audio(self, path: str) -> Tuple[np.ndarray, int]:
56
+ """
57
+ Load and preprocess audio from video file using FFmpeg.
58
+
59
+ Applies noise filtering and normalization for optimal transcription.
60
+
61
+ Args:
62
+ path: Path to video/audio file
63
+
64
+ Returns:
65
+ Tuple of (audio_array, sample_rate)
66
+ """
67
+ # Build FFmpeg command with audio filtering
68
+ cmd = [
69
+ "ffmpeg", "-i", path,
70
+ "-af", f"highpass=f={self.highpass_freq},lowpass=f={self.lowpass_freq},loudnorm",
71
+ "-f", "s16le", # 16-bit signed little-endian
72
+ "-acodec", "pcm_s16le", # PCM codec
73
+ "-ac", "1", # Mono channel
74
+ "-ar", str(self.sample_rate), # Sample rate
75
+ "pipe:1" # Output to stdout
76
+ ]
77
+
78
+ try:
79
+ # Run FFmpeg and capture audio data
80
+ process = subprocess.Popen(
81
+ cmd,
82
+ stdout=subprocess.PIPE,
83
+ stderr=subprocess.DEVNULL
84
+ )
85
+ raw_audio = process.stdout.read()
86
+
87
+ # Convert to numpy array and normalize to [-1, 1]
88
+ audio = np.frombuffer(raw_audio, np.int16).astype(np.float32) / 32768.0
89
+
90
+ # Apply additional normalization if audio is present
91
+ if len(audio) > 0:
92
+ max_amplitude = np.max(np.abs(audio))
93
+ if max_amplitude > 0:
94
+ audio = audio / (max_amplitude + 1e-8) # Prevent division by zero
95
+
96
+ return audio, self.sample_rate
97
+
98
+ except Exception as e:
99
+ if ENABLE_DEBUG_PRINTS:
100
+ print(f"[ERROR] Audio loading failed for {path}: {e}")
101
+ return np.array([]), self.sample_rate
102
+
103
+ def is_valid_audio(self, audio: np.ndarray) -> bool:
104
+ """
105
+ Check if audio meets minimum quality requirements for transcription.
106
+
107
+ Args:
108
+ audio: Audio array to validate
109
+
110
+ Returns:
111
+ True if audio is suitable for transcription
112
+ """
113
+ if len(audio) == 0:
114
+ return False
115
+
116
+ # Check minimum duration
117
+ duration = len(audio) / self.sample_rate
118
+ if duration < AUDIO_MIN_DURATION:
119
+ return False
120
+
121
+ # Check minimum amplitude (not too quiet)
122
+ max_amplitude = np.max(np.abs(audio))
123
+ if max_amplitude < AUDIO_MIN_AMPLITUDE:
124
+ return False
125
+
126
+ return True
127
+
128
+
129
+ class NFLTextCorrector:
130
+ """
131
+ NFL-specific text correction and enhancement system.
132
+
133
+ Applies sports vocabulary corrections, standardizes terminology,
134
+ and fixes common transcription errors in NFL commentary.
135
+ """
136
+
137
+ def __init__(self):
138
+ """Initialize NFL text corrector with sports-specific rules."""
139
+ self.nfl_teams = NFL_TEAMS
140
+ self.nfl_positions = NFL_POSITIONS
141
+ self.sports_context = NFL_SPORTS_CONTEXT
142
+
143
+ # Build correction dictionaries
144
+ self._build_correction_patterns()
145
+
146
+ def _build_correction_patterns(self) -> None:
147
+ """Build regex patterns for common NFL terminology corrections."""
148
+ self.basic_corrections = {
149
+ # Position corrections
150
+ r'\bqb\b': "QB",
151
+ r'\bquarter back\b': "quarterback",
152
+ r'\bwide receiver\b': "wide receiver",
153
+ r'\btight end\b': "tight end",
154
+ r'\brunning back\b': "running back",
155
+ r'\bline backer\b': "linebacker",
156
+ r'\bcorner back\b': "cornerback",
157
+
158
+ # Play corrections
159
+ r'\btouch down\b': "touchdown",
160
+ r'\bfield goal\b': "field goal",
161
+ r'\bfirst down\b': "first down",
162
+ r'\bsecond down\b': "second down",
163
+ r'\bthird down\b': "third down",
164
+ r'\bfourth down\b': "fourth down",
165
+ r'\byard line\b': "yard line",
166
+ r'\bend zone\b': "end zone",
167
+ r'\bred zone\b': "red zone",
168
+ r'\btwo minute warning\b': "two minute warning",
169
+
170
+ # Common misheard words
171
+ r'\bfourty\b': "forty",
172
+ r'\bfourty yard\b': "forty yard",
173
+ r'\btwenny\b': "twenty",
174
+ r'\bthirty yard\b': "thirty yard",
175
+
176
+ # Numbers/downs that are often misheard
177
+ r'\b1st\b': "first",
178
+ r'\b2nd\b': "second",
179
+ r'\b3rd\b': "third",
180
+ r'\b4th\b': "fourth",
181
+ r'\b1st and 10\b': "first and ten",
182
+ r'\b2nd and long\b': "second and long",
183
+ r'\b3rd and short\b': "third and short",
184
+
185
+ # Team name corrections (common mishears)
186
+ r'\bforty niners\b': "49ers",
187
+ r'\bforty-niners\b': "49ers",
188
+ r'\bsan francisco\b': "49ers",
189
+ r'\bnew england\b': "Patriots",
190
+ r'\bgreen bay\b': "Packers",
191
+ r'\bkansas city\b': "Chiefs",
192
+ r'\bnew york giants\b': "Giants",
193
+ r'\bnew york jets\b': "Jets",
194
+ r'\blos angeles rams\b': "Rams",
195
+ r'\blos angeles chargers\b': "Chargers",
196
+
197
+ # Yard markers and positions
198
+ r'\b10 yard line\b': "ten yard line",
199
+ r'\b20 yard line\b': "twenty yard line",
200
+ r'\b30 yard line\b': "thirty yard line",
201
+ r'\b40 yard line\b': "forty yard line",
202
+ r'\b50 yard line\b': "fifty yard line",
203
+ r'\bmid field\b': "midfield",
204
+ r'\bgoal line\b': "goal line",
205
+
206
+ # Penalties and flags
207
+ r'\bfalse start\b': "false start",
208
+ r'\boff side\b': "offside",
209
+ r'\bpass interference\b': "pass interference",
210
+ r'\broughing the passer\b': "roughing the passer",
211
+ r'\bdelay of game\b': "delay of game",
212
+
213
+ # Common play calls
214
+ r'\bplay action\b': "play action",
215
+ r'\bscreen pass\b': "screen pass",
216
+ r'\bdraw play\b': "draw play",
217
+ r'\bboot leg\b': "bootleg",
218
+ r'\broll out\b': "rollout",
219
+ r'\bshot gun\b': "shotgun",
220
+ r'\bno huddle\b': "no huddle"
221
+ }
222
+
223
+ self.fuzzy_corrections = {
224
+ # Team names with common misspellings
225
+ r'\bpatriots?\b': "Patriots",
226
+ r'\bcowboys?\b': "Cowboys",
227
+ r'\bpackers?\b': "Packers",
228
+ r'\bchief\b': "Chiefs",
229
+ r'\bchiefs?\b': "Chiefs",
230
+ r'\beagles?\b': "Eagles",
231
+ r'\bgiants?\b': "Giants",
232
+ r'\brams?\b': "Rams",
233
+ r'\bsaints?\b': "Saints",
234
+
235
+ # Positions with common variations
236
+ r'\bquarterbacks?\b': "quarterback",
237
+ r'\brunning backs?\b': "running back",
238
+ r'\bwide receivers?\b': "wide receiver",
239
+ r'\btight ends?\b': "tight end",
240
+ r'\blinebackers?\b': "linebacker",
241
+ r'\bcornerbacks?\b': "cornerback",
242
+ r'\bsafety\b': "safety",
243
+ r'\bsafeties\b': "safety",
244
+
245
+ # Play terms
246
+ r'\btouchdowns?\b': "touchdown",
247
+ r'\bfield goals?\b': "field goal",
248
+ r'\binterceptions?\b': "interception",
249
+ r'\bfumbles?\b': "fumble",
250
+ r'\bsacks?\b': "sack",
251
+ r'\bpunt\b': "punt",
252
+ r'\bpunts?\b': "punt",
253
+
254
+ # Numbers and yards
255
+ r'\byards?\b': "yard",
256
+ r'\byards? line\b': "yard line",
257
+ r'\byard lines?\b': "yard line"
258
+ }
259
+
260
+ # Terms that should always be capitalized
261
+ self.capitalization_terms = [
262
+ "NFL", "QB", "Patriots", "Cowboys", "Chiefs", "Packers", "49ers",
263
+ "Eagles", "Giants", "Rams", "Saints", "Bills", "Ravens", "Steelers"
264
+ ]
265
+
266
+ def correct_text(self, text: str) -> str:
267
+ """
268
+ Apply comprehensive NFL-specific text corrections.
269
+
270
+ Args:
271
+ text: Raw transcription text
272
+
273
+ Returns:
274
+ Corrected and standardized text
275
+ """
276
+ if not text:
277
+ return text
278
+
279
+ corrected = text
280
+
281
+ # Apply basic corrections
282
+ corrected = self._apply_corrections(corrected, self.basic_corrections)
283
+
284
+ # Apply fuzzy corrections
285
+ corrected = self._apply_corrections(corrected, self.fuzzy_corrections)
286
+
287
+ # Apply capitalization rules
288
+ corrected = self._apply_capitalization(corrected)
289
+
290
+ return corrected.strip()
291
+
292
+ def _apply_corrections(self, text: str, corrections: Dict[str, str]) -> str:
293
+ """Apply a set of regex corrections to text."""
294
+ corrected = text
295
+ for pattern, replacement in corrections.items():
296
+ corrected = re.sub(pattern, replacement, corrected, flags=re.IGNORECASE)
297
+ return corrected
298
+
299
+ def _apply_capitalization(self, text: str) -> str:
300
+ """Apply proper capitalization for NFL terms."""
301
+ corrected = text
302
+ for term in self.capitalization_terms:
303
+ pattern = r'\b' + re.escape(term.lower()) + r'\b'
304
+ corrected = re.sub(pattern, term, corrected, flags=re.IGNORECASE)
305
+ return corrected
306
+
307
+
308
+ class AudioTranscriber:
309
+ """
310
+ Whisper-based audio transcriber optimized for NFL broadcasts.
311
+
312
+ Combines Whisper speech recognition with NFL-specific enhancements
313
+ for high-quality sports commentary transcription.
314
+ """
315
+
316
+ def __init__(self,
317
+ model_name: str = AUDIO_MODEL_NAME,
318
+ device: int = AUDIO_DEVICE):
319
+ """
320
+ Initialize audio transcriber.
321
+
322
+ Args:
323
+ model_name: Whisper model name (base, medium, large)
324
+ device: Device for inference (-1 for CPU, 0+ for GPU)
325
+ """
326
+ self.model_name = model_name
327
+ self.device = device
328
+ self.preprocessor = AudioPreprocessor()
329
+ self.corrector = NFLTextCorrector()
330
+
331
+ # Initialize Whisper pipeline
332
+ self._initialize_pipeline()
333
+
334
+ def _initialize_pipeline(self) -> None:
335
+ """Initialize the Whisper transcription pipeline."""
336
+ if ENABLE_DEBUG_PRINTS:
337
+ print(f"Initializing Whisper pipeline: {self.model_name}")
338
+
339
+ self.pipeline = pipeline(
340
+ "automatic-speech-recognition",
341
+ model=self.model_name,
342
+ device=self.device,
343
+ generate_kwargs=WHISPER_GENERATION_PARAMS
344
+ )
345
+
346
+ if ENABLE_DEBUG_PRINTS:
347
+ print("Whisper pipeline ready")
348
+
349
+ def transcribe_clip(self, video_path: str) -> str:
350
+ """
351
+ Transcribe audio from a video clip with NFL-specific enhancements.
352
+
353
+ Args:
354
+ video_path: Path to video file
355
+
356
+ Returns:
357
+ Transcribed and corrected text
358
+ """
359
+ # Load and preprocess audio
360
+ audio, sample_rate = self.preprocessor.load_audio(video_path)
361
+
362
+ # Validate audio quality
363
+ if not self.preprocessor.is_valid_audio(audio):
364
+ return ""
365
+
366
+ try:
367
+ # Run Whisper transcription
368
+ result = self.pipeline(audio, generate_kwargs=WHISPER_GENERATION_PARAMS)
369
+ text = result.get("text", "").strip()
370
+
371
+ # Clean up common Whisper artifacts
372
+ text = self._clean_whisper_artifacts(text)
373
+
374
+ # Apply NFL-specific corrections
375
+ text = self.corrector.correct_text(text)
376
+
377
+ return text
378
+
379
+ except Exception as e:
380
+ if ENABLE_DEBUG_PRINTS:
381
+ print(f"[WARN] Transcription failed for {video_path}: {e}")
382
+ return ""
383
+
384
+ def _clean_whisper_artifacts(self, text: str) -> str:
385
+ """Remove common Whisper transcription artifacts."""
386
+ # Remove placeholder text
387
+ text = text.replace("[BLANK_AUDIO]", "")
388
+ text = text.replace("♪", "") # Remove music notes
389
+ text = text.replace("(music)", "")
390
+ text = text.replace("[music]", "")
391
+
392
+ # Clean up extra whitespace
393
+ text = re.sub(r'\s+', ' ', text)
394
+
395
+ return text.strip()
396
+
397
+
398
+ # ============================================================================
399
+ # CONVENIENCE FUNCTIONS FOR BACKWARD COMPATIBILITY
400
+ # ============================================================================
401
+
402
+ # Global instance for backward compatibility
403
+ _audio_transcriber = None
404
+
405
+ def get_audio_transcriber() -> AudioTranscriber:
406
+ """Get global audio transcriber instance (lazy initialization)."""
407
+ global _audio_transcriber
408
+ if _audio_transcriber is None:
409
+ _audio_transcriber = AudioTranscriber()
410
+ return _audio_transcriber
411
+
412
+ def transcribe_clip(path: str) -> str:
413
+ """
414
+ Backward compatibility function for audio transcription.
415
+
416
+ Args:
417
+ path: Path to video file
418
+
419
+ Returns:
420
+ Transcribed text
421
+ """
422
+ transcriber = get_audio_transcriber()
423
+ return transcriber.transcribe_clip(path)
424
+
425
+ def load_audio(path: str, sr: int = AUDIO_SAMPLE_RATE) -> Tuple[np.ndarray, int]:
426
+ """
427
+ Backward compatibility function for audio loading.
428
+
429
+ Args:
430
+ path: Path to audio/video file
431
+ sr: Sample rate (kept for compatibility)
432
+
433
+ Returns:
434
+ Tuple of (audio_array, sample_rate)
435
+ """
436
+ preprocessor = AudioPreprocessor(sample_rate=sr)
437
+ return preprocessor.load_audio(path)
438
+
439
+ def apply_sports_corrections(text: str) -> str:
440
+ """
441
+ Backward compatibility function for text corrections.
442
+
443
+ Args:
444
+ text: Text to correct
445
+
446
+ Returns:
447
+ Corrected text
448
+ """
449
+ corrector = NFLTextCorrector()
450
+ return corrector.correct_text(text)
451
+
452
+ def fuzzy_sports_corrections(text: str) -> str:
453
+ """
454
+ Backward compatibility function (now handled within NFLTextCorrector).
455
+
456
+ Args:
457
+ text: Text to correct
458
+
459
+ Returns:
460
+ Corrected text
461
+ """
462
+ return apply_sports_corrections(text)
classification.json CHANGED
@@ -20,5 +20,1656 @@
20
  "\"passing American football (in game)\"",
21
  0.0025873929262161255
22
  ]
23
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  }
 
20
  "\"passing American football (in game)\"",
21
  0.0025873929262161255
22
  ]
23
+ ],
24
+ "segment_002.mov": [
25
+ [
26
+ "\"mowing lawn\"",
27
+ 0.004539191722869873
28
+ ],
29
+ [
30
+ "\"riding or walking with horse\"",
31
+ 0.002820482011884451
32
+ ],
33
+ [
34
+ "\"driving tractor\"",
35
+ 0.002591945929452777
36
+ ],
37
+ [
38
+ "\"catching or throwing baseball\"",
39
+ 0.002587514230981469
40
+ ],
41
+ [
42
+ "archery",
43
+ 0.0025512496940791607
44
+ ]
45
+ ],
46
+ "segment_003.mov": [
47
+ [
48
+ "\"hurling (sport)\"",
49
+ 0.0035289316438138485
50
+ ],
51
+ [
52
+ "headbutting",
53
+ 0.0029045743867754936
54
+ ],
55
+ [
56
+ "\"passing American football (not in game)\"",
57
+ 0.002668950939550996
58
+ ],
59
+ [
60
+ "\"pumping fist\"",
61
+ 0.0026475831400603056
62
+ ],
63
+ [
64
+ "\"playing cricket\"",
65
+ 0.002635735785588622
66
+ ]
67
+ ],
68
+ "segment_004.mov": [
69
+ [
70
+ "applauding",
71
+ 0.00304257869720459
72
+ ],
73
+ [
74
+ "headbutting",
75
+ 0.0029725206550210714
76
+ ],
77
+ [
78
+ "\"pumping fist\"",
79
+ 0.0029444803949445486
80
+ ],
81
+ [
82
+ "\"hurling (sport)\"",
83
+ 0.0027822419069707394
84
+ ],
85
+ [
86
+ "\"shaking hands\"",
87
+ 0.002624393440783024
88
+ ]
89
+ ],
90
+ "segment_005.mov": [
91
+ [
92
+ "\"catching or throwing baseball\"",
93
+ 0.003370030550286174
94
+ ],
95
+ [
96
+ "\"pumping fist\"",
97
+ 0.00289507070556283
98
+ ],
99
+ [
100
+ "\"catching or throwing frisbee\"",
101
+ 0.0026615660171955824
102
+ ],
103
+ [
104
+ "\"eating hotdog\"",
105
+ 0.002651733811944723
106
+ ],
107
+ [
108
+ "\"javelin throw\"",
109
+ 0.0026478723157197237
110
+ ]
111
+ ],
112
+ "segment_006.mov": [
113
+ [
114
+ "\"riding mountain bike\"",
115
+ 0.0030539515428245068
116
+ ],
117
+ [
118
+ "\"bench pressing\"",
119
+ 0.0030068582855165005
120
+ ],
121
+ [
122
+ "\"changing wheel\"",
123
+ 0.0028557234909385443
124
+ ],
125
+ [
126
+ "\"checking tires\"",
127
+ 0.002828161232173443
128
+ ],
129
+ [
130
+ "\"changing oil\"",
131
+ 0.0025825132615864277
132
+ ]
133
+ ],
134
+ "segment_007.mov": [
135
+ [
136
+ "\"changing oil\"",
137
+ 0.003507673041895032
138
+ ],
139
+ [
140
+ "\"pushing wheelchair\"",
141
+ 0.0028540242929011583
142
+ ],
143
+ [
144
+ "motorcycling",
145
+ 0.002735486486926675
146
+ ],
147
+ [
148
+ "\"checking tires\"",
149
+ 0.0026065800338983536
150
+ ],
151
+ [
152
+ "\"changing wheel\"",
153
+ 0.0026001674123108387
154
+ ]
155
+ ],
156
+ "segment_008.mov": [
157
+ [
158
+ "motorcycling",
159
+ 0.0034892940893769264
160
+ ],
161
+ [
162
+ "\"riding mountain bike\"",
163
+ 0.0027264610398560762
164
+ ],
165
+ [
166
+ "\"pushing wheelchair\"",
167
+ 0.0026729153469204903
168
+ ],
169
+ [
170
+ "\"changing oil\"",
171
+ 0.002655936172232032
172
+ ],
173
+ [
174
+ "snowmobiling",
175
+ 0.002622972708195448
176
+ ]
177
+ ],
178
+ "segment_009.mov": [
179
+ [
180
+ "\"kicking field goal\"",
181
+ 0.0051559642888605595
182
+ ],
183
+ [
184
+ "\"tossing coin\"",
185
+ 0.002858997555449605
186
+ ],
187
+ [
188
+ "\"passing American football (in game)\"",
189
+ 0.002840855158865452
190
+ ],
191
+ [
192
+ "\"high kick\"",
193
+ 0.0024956425186246634
194
+ ],
195
+ [
196
+ "headbutting",
197
+ 0.002494481625035405
198
+ ]
199
+ ],
200
+ "segment_010.mov": [
201
+ [
202
+ "\"tossing coin\"",
203
+ 0.003494303673505783
204
+ ],
205
+ [
206
+ "headbutting",
207
+ 0.003139702370390296
208
+ ],
209
+ [
210
+ "\"kicking field goal\"",
211
+ 0.003000226803123951
212
+ ],
213
+ [
214
+ "\"passing American football (in game)\"",
215
+ 0.0028010711539536715
216
+ ],
217
+ [
218
+ "\"pumping fist\"",
219
+ 0.0026133027859032154
220
+ ]
221
+ ],
222
+ "segment_011.mov": [
223
+ [
224
+ "headbutting",
225
+ 0.0035944455303251743
226
+ ],
227
+ [
228
+ "\"kicking field goal\"",
229
+ 0.002746515441685915
230
+ ],
231
+ [
232
+ "\"passing American football (in game)\"",
233
+ 0.00274651194922626
234
+ ],
235
+ [
236
+ "cheerleading",
237
+ 0.0027097328566014767
238
+ ],
239
+ [
240
+ "\"playing ice hockey\"",
241
+ 0.002675419207662344
242
+ ]
243
+ ],
244
+ "segment_012.mov": [
245
+ [
246
+ "cheerleading",
247
+ 0.0033036908134818077
248
+ ],
249
+ [
250
+ "\"dancing macarena\"",
251
+ 0.0031919179018586874
252
+ ],
253
+ [
254
+ "applauding",
255
+ 0.0027217946480959654
256
+ ],
257
+ [
258
+ "\"hitting baseball\"",
259
+ 0.0026708708610385656
260
+ ],
261
+ [
262
+ "\"garbage collecting\"",
263
+ 0.0026213040109723806
264
+ ]
265
+ ],
266
+ "segment_013.mov": [
267
+ [
268
+ "\"pumping fist\"",
269
+ 0.0035472228191792965
270
+ ],
271
+ [
272
+ "\"kicking field goal\"",
273
+ 0.0027715854812413454
274
+ ],
275
+ [
276
+ "\"dunking basketball\"",
277
+ 0.0027416404336690903
278
+ ],
279
+ [
280
+ "applauding",
281
+ 0.002673310926184058
282
+ ],
283
+ [
284
+ "celebrating",
285
+ 0.002629267517477274
286
+ ]
287
+ ],
288
+ "segment_014.mov": [
289
+ [
290
+ "headbutting",
291
+ 0.0038350492250174284
292
+ ],
293
+ [
294
+ "bobsledding",
295
+ 0.002937863813713193
296
+ ],
297
+ [
298
+ "\"playing ice hockey\"",
299
+ 0.002785387681797147
300
+ ],
301
+ [
302
+ "\"punching person (boxing)\"",
303
+ 0.002671806840226054
304
+ ],
305
+ [
306
+ "\"changing wheel\"",
307
+ 0.0026315213181078434
308
+ ]
309
+ ],
310
+ "segment_015.mov": [
311
+ [
312
+ "\"passing American football (in game)\"",
313
+ 0.00389948021620512
314
+ ],
315
+ [
316
+ "\"side kick\"",
317
+ 0.003301523393020034
318
+ ],
319
+ [
320
+ "\"kicking field goal\"",
321
+ 0.002986735198646784
322
+ ],
323
+ [
324
+ "\"passing American football (not in game)\"",
325
+ 0.0026217757258564234
326
+ ],
327
+ [
328
+ "\"catching or throwing baseball\"",
329
+ 0.002540471963584423
330
+ ]
331
+ ],
332
+ "segment_016.mov": [
333
+ [
334
+ "\"passing American football (in game)\"",
335
+ 0.006536518689244986
336
+ ],
337
+ [
338
+ "\"side kick\"",
339
+ 0.0025378491263836622
340
+ ],
341
+ [
342
+ "\"passing American football (not in game)\"",
343
+ 0.0025076796300709248
344
+ ],
345
+ [
346
+ "\"kicking field goal\"",
347
+ 0.002507618861272931
348
+ ],
349
+ [
350
+ "\"high kick\"",
351
+ 0.0024923686869442463
352
+ ]
353
+ ],
354
+ "segment_017.mov": [
355
+ [
356
+ "\"passing American football (in game)\"",
357
+ 0.004528654273599386
358
+ ],
359
+ [
360
+ "\"kicking field goal\"",
361
+ 0.003415569895878434
362
+ ],
363
+ [
364
+ "\"passing American football (not in game)\"",
365
+ 0.0026175878010690212
366
+ ],
367
+ [
368
+ "\"side kick\"",
369
+ 0.0025776273105293512
370
+ ],
371
+ [
372
+ "\"high kick\"",
373
+ 0.0025026851799339056
374
+ ]
375
+ ],
376
+ "segment_018.mov": [
377
+ [
378
+ "\"passing American football (in game)\"",
379
+ 0.004061450716108084
380
+ ],
381
+ [
382
+ "\"side kick\"",
383
+ 0.0038009993731975555
384
+ ],
385
+ [
386
+ "\"kicking field goal\"",
387
+ 0.002601894084364176
388
+ ],
389
+ [
390
+ "\"high kick\"",
391
+ 0.002582114189863205
392
+ ],
393
+ [
394
+ "\"passing American football (not in game)\"",
395
+ 0.0025175546761602163
396
+ ]
397
+ ],
398
+ "segment_019.mov": [
399
+ [
400
+ "\"passing American football (in game)\"",
401
+ 0.006576324347406626
402
+ ],
403
+ [
404
+ "\"passing American football (not in game)\"",
405
+ 0.002554940525442362
406
+ ],
407
+ [
408
+ "\"kicking field goal\"",
409
+ 0.0024935186374932528
410
+ ],
411
+ [
412
+ "\"side kick\"",
413
+ 0.0024903316516429186
414
+ ],
415
+ [
416
+ "\"catching or throwing frisbee\"",
417
+ 0.002489960053935647
418
+ ]
419
+ ],
420
+ "segment_020.mov": [
421
+ [
422
+ "\"passing American football (in game)\"",
423
+ 0.006745155900716782
424
+ ],
425
+ [
426
+ "\"passing American football (not in game)\"",
427
+ 0.002495990600436926
428
+ ],
429
+ [
430
+ "\"kicking field goal\"",
431
+ 0.0024898555129766464
432
+ ],
433
+ [
434
+ "headbutting",
435
+ 0.002489602193236351
436
+ ],
437
+ [
438
+ "\"shaking hands\"",
439
+ 0.0024894699454307556
440
+ ]
441
+ ],
442
+ "segment_021.mov": [
443
+ [
444
+ "\"passing American football (in game)\"",
445
+ 0.004887602757662535
446
+ ],
447
+ [
448
+ "\"passing American football (not in game)\"",
449
+ 0.002793429885059595
450
+ ],
451
+ [
452
+ "situp",
453
+ 0.0026539755053818226
454
+ ],
455
+ [
456
+ "\"dribbling basketball\"",
457
+ 0.0026028482243418694
458
+ ],
459
+ [
460
+ "\"throwing ball\"",
461
+ 0.002529650926589966
462
+ ]
463
+ ],
464
+ "segment_022.mov": [
465
+ [
466
+ "\"pumping fist\"",
467
+ 0.002948896726593375
468
+ ],
469
+ [
470
+ "\"passing American football (in game)\"",
471
+ 0.0028372337110340595
472
+ ],
473
+ [
474
+ "\"tossing coin\"",
475
+ 0.0027690029237419367
476
+ ],
477
+ [
478
+ "\"shaking hands\"",
479
+ 0.0027542426250874996
480
+ ],
481
+ [
482
+ "headbutting",
483
+ 0.0026179237756878138
484
+ ]
485
+ ],
486
+ "segment_023.mov": [
487
+ [
488
+ "\"pumping fist\"",
489
+ 0.003991341684013605
490
+ ],
491
+ [
492
+ "headbutting",
493
+ 0.002623251872137189
494
+ ],
495
+ [
496
+ "motorcycling",
497
+ 0.0025920518673956394
498
+ ],
499
+ [
500
+ "skydiving",
501
+ 0.0025866003707051277
502
+ ],
503
+ [
504
+ "bobsledding",
505
+ 0.0025851819664239883
506
+ ]
507
+ ],
508
+ "segment_024.mov": [
509
+ [
510
+ "\"riding a bike\"",
511
+ 0.0037740382831543684
512
+ ],
513
+ [
514
+ "motorcycling",
515
+ 0.002751761581748724
516
+ ],
517
+ [
518
+ "bobsledding",
519
+ 0.0026172574143856764
520
+ ],
521
+ [
522
+ "\"riding unicycle\"",
523
+ 0.0025924895890057087
524
+ ],
525
+ [
526
+ "\"pumping fist\"",
527
+ 0.0025839442387223244
528
+ ]
529
+ ],
530
+ "segment_025.mov": [
531
+ [
532
+ "bobsledding",
533
+ 0.004564006347209215
534
+ ],
535
+ [
536
+ "\"shaking hands\"",
537
+ 0.0026650093495845795
538
+ ],
539
+ [
540
+ "motorcycling",
541
+ 0.002605688525363803
542
+ ],
543
+ [
544
+ "\"pumping fist\"",
545
+ 0.0026000377256423235
546
+ ],
547
+ [
548
+ "skydiving",
549
+ 0.0025698416866362095
550
+ ]
551
+ ],
552
+ "segment_026.mov": [
553
+ [
554
+ "\"tossing coin\"",
555
+ 0.005768336355686188
556
+ ],
557
+ [
558
+ "squat",
559
+ 0.0025260422844439745
560
+ ],
561
+ [
562
+ "\"side kick\"",
563
+ 0.0025187088176608086
564
+ ],
565
+ [
566
+ "\"shaking hands\"",
567
+ 0.0025166154373437166
568
+ ],
569
+ [
570
+ "\"kicking field goal\"",
571
+ 0.0025109625421464443
572
+ ]
573
+ ],
574
+ "segment_027.mov": [
575
+ [
576
+ "\"carrying baby\"",
577
+ 0.0028944576624780893
578
+ ],
579
+ [
580
+ "\"side kick\"",
581
+ 0.002688055858016014
582
+ ],
583
+ [
584
+ "\"salsa dancing\"",
585
+ 0.002644676947966218
586
+ ],
587
+ [
588
+ "\"hula hooping\"",
589
+ 0.0026000014040619135
590
+ ],
591
+ [
592
+ "archery",
593
+ 0.002581424079835415
594
+ ]
595
+ ],
596
+ "segment_028.mov": [
597
+ [
598
+ "\"stretching arm\"",
599
+ 0.004183173179626465
600
+ ],
601
+ [
602
+ "archery",
603
+ 0.0028685072902590036
604
+ ],
605
+ [
606
+ "\"carrying baby\"",
607
+ 0.002629334107041359
608
+ ],
609
+ [
610
+ "yoga",
611
+ 0.0025525041855871677
612
+ ],
613
+ [
614
+ "\"stretching leg\"",
615
+ 0.0025523642543703318
616
+ ]
617
+ ],
618
+ "segment_029.mov": [
619
+ [
620
+ "\"getting a tattoo\"",
621
+ 0.0036486154422163963
622
+ ],
623
+ [
624
+ "archery",
625
+ 0.0027306571137160063
626
+ ],
627
+ [
628
+ "\"punching person (boxing)\"",
629
+ 0.0027052827645093203
630
+ ],
631
+ [
632
+ "\"punching bag\"",
633
+ 0.002618985017761588
634
+ ],
635
+ [
636
+ "squat",
637
+ 0.0026112094055861235
638
+ ]
639
+ ],
640
+ "segment_030.mov": [
641
+ [
642
+ "\"spray painting\"",
643
+ 0.004089465364813805
644
+ ],
645
+ [
646
+ "\"getting a tattoo\"",
647
+ 0.002762633841484785
648
+ ],
649
+ [
650
+ "\"playing paintball\"",
651
+ 0.0027071302756667137
652
+ ],
653
+ [
654
+ "\"changing wheel\"",
655
+ 0.0026773668359965086
656
+ ],
657
+ [
658
+ "bobsledding",
659
+ 0.0025922050699591637
660
+ ]
661
+ ],
662
+ "segment_031.mov": [
663
+ [
664
+ "\"mowing lawn\"",
665
+ 0.0034001749008893967
666
+ ],
667
+ [
668
+ "\"passing American football (not in game)\"",
669
+ 0.003030994674190879
670
+ ],
671
+ [
672
+ "\"catching or throwing baseball\"",
673
+ 0.0028556634206324816
674
+ ],
675
+ [
676
+ "\"pumping fist\"",
677
+ 0.002578843617811799
678
+ ],
679
+ [
680
+ "\"riding or walking with horse\"",
681
+ 0.002575062680989504
682
+ ]
683
+ ],
684
+ "segment_032.mov": [
685
+ [
686
+ "\"passing American football (in game)\"",
687
+ 0.003045632503926754
688
+ ],
689
+ [
690
+ "marching",
691
+ 0.0030235128942877054
692
+ ],
693
+ [
694
+ "\"passing American football (not in game)\"",
695
+ 0.0029362209606915712
696
+ ],
697
+ [
698
+ "\"kicking field goal\"",
699
+ 0.0027396646328270435
700
+ ],
701
+ [
702
+ "\"hurling (sport)\"",
703
+ 0.002676320029422641
704
+ ]
705
+ ],
706
+ "segment_033.mov": [
707
+ [
708
+ "\"mowing lawn\"",
709
+ 0.004852019250392914
710
+ ],
711
+ [
712
+ "\"passing American football (not in game)\"",
713
+ 0.002654429292306304
714
+ ],
715
+ [
716
+ "\"hurling (sport)\"",
717
+ 0.002581879962235689
718
+ ],
719
+ [
720
+ "\"kicking soccer ball\"",
721
+ 0.0025664607528597116
722
+ ],
723
+ [
724
+ "\"juggling soccer ball\"",
725
+ 0.002544356742873788
726
+ ]
727
+ ],
728
+ "segment_034.mov": [
729
+ [
730
+ "archery",
731
+ 0.004724352620542049
732
+ ],
733
+ [
734
+ "\"trimming or shaving beard\"",
735
+ 0.0026578360702842474
736
+ ],
737
+ [
738
+ "\"golf driving\"",
739
+ 0.002610759809613228
740
+ ],
741
+ [
742
+ "\"tossing coin\"",
743
+ 0.002541653113439679
744
+ ],
745
+ [
746
+ "\"mowing lawn\"",
747
+ 0.0025332642253488302
748
+ ]
749
+ ],
750
+ "segment_035.mov": [
751
+ [
752
+ "\"playing harmonica\"",
753
+ 0.006103646010160446
754
+ ],
755
+ [
756
+ "whistling",
757
+ 0.002615551697090268
758
+ ],
759
+ [
760
+ "smoking",
761
+ 0.0025100400671362877
762
+ ],
763
+ [
764
+ "yawning",
765
+ 0.0025017866864800453
766
+ ],
767
+ [
768
+ "\"playing ukulele\"",
769
+ 0.0025011510588228703
770
+ ]
771
+ ],
772
+ "segment_036.mov": [
773
+ [
774
+ "\"passing American football (in game)\"",
775
+ 0.006577454507350922
776
+ ],
777
+ [
778
+ "\"passing American football (not in game)\"",
779
+ 0.002514705527573824
780
+ ],
781
+ [
782
+ "\"kicking field goal\"",
783
+ 0.0025104687083512545
784
+ ],
785
+ [
786
+ "\"side kick\"",
787
+ 0.0025097192265093327
788
+ ],
789
+ [
790
+ "\"high kick\"",
791
+ 0.002491986844688654
792
+ ]
793
+ ],
794
+ "segment_037.mov": [
795
+ [
796
+ "\"passing American football (in game)\"",
797
+ 0.006760087329894304
798
+ ],
799
+ [
800
+ "\"passing American football (not in game)\"",
801
+ 0.0024913023225963116
802
+ ],
803
+ [
804
+ "\"kicking field goal\"",
805
+ 0.00248970789834857
806
+ ],
807
+ [
808
+ "\"side kick\"",
809
+ 0.002489360049366951
810
+ ],
811
+ [
812
+ "\"high kick\"",
813
+ 0.002489320933818817
814
+ ]
815
+ ],
816
+ "segment_038.mov": [
817
+ [
818
+ "\"passing American football (in game)\"",
819
+ 0.0062811062671244144
820
+ ],
821
+ [
822
+ "\"kicking field goal\"",
823
+ 0.0026691341772675514
824
+ ],
825
+ [
826
+ "\"passing American football (not in game)\"",
827
+ 0.002501868177205324
828
+ ],
829
+ [
830
+ "\"side kick\"",
831
+ 0.0024906292092055082
832
+ ],
833
+ [
834
+ "\"tossing coin\"",
835
+ 0.0024903123266994953
836
+ ]
837
+ ],
838
+ "segment_039.mov": [
839
+ [
840
+ "\"passing American football (in game)\"",
841
+ 0.004427704028785229
842
+ ],
843
+ [
844
+ "\"kicking field goal\"",
845
+ 0.00305744051001966
846
+ ],
847
+ [
848
+ "\"passing American football (not in game)\"",
849
+ 0.0028497367165982723
850
+ ],
851
+ [
852
+ "\"shaking hands\"",
853
+ 0.0025244825519621372
854
+ ],
855
+ [
856
+ "\"tossing coin\"",
857
+ 0.0025086107198148966
858
+ ]
859
+ ],
860
+ "segment_040.mov": [
861
+ [
862
+ "\"passing American football (in game)\"",
863
+ 0.00507122790440917
864
+ ],
865
+ [
866
+ "\"tossing coin\"",
867
+ 0.0028494407888501883
868
+ ],
869
+ [
870
+ "\"kicking field goal\"",
871
+ 0.0025832131505012512
872
+ ],
873
+ [
874
+ "\"shaking hands\"",
875
+ 0.0025662044063210487
876
+ ],
877
+ [
878
+ "\"passing American football (not in game)\"",
879
+ 0.0025347082410007715
880
+ ]
881
+ ],
882
+ "segment_041.mov": [
883
+ [
884
+ "\"passing American football (in game)\"",
885
+ 0.002910151146352291
886
+ ],
887
+ [
888
+ "\"tossing coin\"",
889
+ 0.00288573419675231
890
+ ],
891
+ [
892
+ "bobsledding",
893
+ 0.0027363626286387444
894
+ ],
895
+ [
896
+ "\"changing wheel\"",
897
+ 0.0027150516398251057
898
+ ],
899
+ [
900
+ "\"kicking field goal\"",
901
+ 0.0026453319005668163
902
+ ]
903
+ ],
904
+ "segment_042.mov": [
905
+ [
906
+ "bobsledding",
907
+ 0.0029746112413704395
908
+ ],
909
+ [
910
+ "marching",
911
+ 0.0026662067975848913
912
+ ],
913
+ [
914
+ "\"riding mountain bike\"",
915
+ 0.0026005373802036047
916
+ ],
917
+ [
918
+ "archery",
919
+ 0.002575363963842392
920
+ ],
921
+ [
922
+ "\"passing American football (not in game)\"",
923
+ 0.0025738172698765993
924
+ ]
925
+ ],
926
+ "segment_043.mov": [
927
+ [
928
+ "bobsledding",
929
+ 0.0032584425061941147
930
+ ],
931
+ [
932
+ "\"changing wheel\"",
933
+ 0.002937484998255968
934
+ ],
935
+ [
936
+ "\"driving car\"",
937
+ 0.0028462321497499943
938
+ ],
939
+ [
940
+ "motorcycling",
941
+ 0.00263536861166358
942
+ ],
943
+ [
944
+ "skateboarding",
945
+ 0.002625212771818042
946
+ ]
947
+ ],
948
+ "segment_044.mov": [
949
+ [
950
+ "archery",
951
+ 0.0029061429668217897
952
+ ],
953
+ [
954
+ "bobsledding",
955
+ 0.002719373907893896
956
+ ],
957
+ [
958
+ "\"golf driving\"",
959
+ 0.0027050392236560583
960
+ ],
961
+ [
962
+ "barbequing",
963
+ 0.0025971110444515944
964
+ ],
965
+ [
966
+ "\"golf putting\"",
967
+ 0.0025699003599584103
968
+ ]
969
+ ],
970
+ "segment_045.mov": [
971
+ [
972
+ "barbequing",
973
+ 0.003022523829713464
974
+ ],
975
+ [
976
+ "\"changing wheel\"",
977
+ 0.002754890127107501
978
+ ],
979
+ [
980
+ "\"mowing lawn\"",
981
+ 0.0026360696647316217
982
+ ],
983
+ [
984
+ "auctioning",
985
+ 0.0026054272893816233
986
+ ],
987
+ [
988
+ "\"changing oil\"",
989
+ 0.0025794513057917356
990
+ ]
991
+ ],
992
+ "segment_046.mov": [
993
+ [
994
+ "\"tossing coin\"",
995
+ 0.003568414831534028
996
+ ],
997
+ [
998
+ "\"side kick\"",
999
+ 0.003212416311725974
1000
+ ],
1001
+ [
1002
+ "\"rock scissors paper\"",
1003
+ 0.002615532139316201
1004
+ ],
1005
+ [
1006
+ "\"punching person (boxing)\"",
1007
+ 0.0026119472458958626
1008
+ ],
1009
+ [
1010
+ "\"high kick\"",
1011
+ 0.002596732461825013
1012
+ ]
1013
+ ],
1014
+ "segment_047.mov": [
1015
+ [
1016
+ "\"passing American football (in game)\"",
1017
+ 0.0031079247128218412
1018
+ ],
1019
+ [
1020
+ "\"juggling soccer ball\"",
1021
+ 0.0028041608165949583
1022
+ ],
1023
+ [
1024
+ "\"passing American football (not in game)\"",
1025
+ 0.002784370444715023
1026
+ ],
1027
+ [
1028
+ "\"catching or throwing baseball\"",
1029
+ 0.0027656129095703363
1030
+ ],
1031
+ [
1032
+ "\"tossing coin\"",
1033
+ 0.0027509713545441628
1034
+ ]
1035
+ ],
1036
+ "segment_048.mov": [
1037
+ [
1038
+ "\"tossing coin\"",
1039
+ 0.004612566903233528
1040
+ ],
1041
+ [
1042
+ "\"passing American football (in game)\"",
1043
+ 0.0030128920916467905
1044
+ ],
1045
+ [
1046
+ "\"side kick\"",
1047
+ 0.002602673601359129
1048
+ ],
1049
+ [
1050
+ "\"passing American football (not in game)\"",
1051
+ 0.0025423497427254915
1052
+ ],
1053
+ [
1054
+ "\"rock scissors paper\"",
1055
+ 0.0025353787932544947
1056
+ ]
1057
+ ],
1058
+ "segment_049.mov": [
1059
+ [
1060
+ "beatboxing",
1061
+ 0.002776292385533452
1062
+ ],
1063
+ [
1064
+ "\"pumping fist\"",
1065
+ 0.0027726562693715096
1066
+ ],
1067
+ [
1068
+ "\"shaking hands\"",
1069
+ 0.0027530265506356955
1070
+ ],
1071
+ [
1072
+ "\"playing poker\"",
1073
+ 0.002649413887411356
1074
+ ],
1075
+ [
1076
+ "\"arm wrestling\"",
1077
+ 0.0026053758338093758
1078
+ ]
1079
+ ],
1080
+ "segment_050.mov": [
1081
+ [
1082
+ "crying",
1083
+ 0.0032352209091186523
1084
+ ],
1085
+ [
1086
+ "beatboxing",
1087
+ 0.002813587663695216
1088
+ ],
1089
+ [
1090
+ "\"fixing hair\"",
1091
+ 0.002721605822443962
1092
+ ],
1093
+ [
1094
+ "\"pumping fist\"",
1095
+ 0.002583273220807314
1096
+ ],
1097
+ [
1098
+ "\"brushing hair\"",
1099
+ 0.0025578502099961042
1100
+ ]
1101
+ ],
1102
+ "segment_051.mov": [
1103
+ [
1104
+ "\"passing American football (in game)\"",
1105
+ 0.005108952056616545
1106
+ ],
1107
+ [
1108
+ "\"passing American football (not in game)\"",
1109
+ 0.002873431658372283
1110
+ ],
1111
+ [
1112
+ "\"side kick\"",
1113
+ 0.002661630278453231
1114
+ ],
1115
+ [
1116
+ "\"kicking field goal\"",
1117
+ 0.0026403891388326883
1118
+ ],
1119
+ [
1120
+ "\"high kick\"",
1121
+ 0.0025104281958192587
1122
+ ]
1123
+ ],
1124
+ "segment_052.mov": [
1125
+ [
1126
+ "\"passing American football (in game)\"",
1127
+ 0.0058504920452833176
1128
+ ],
1129
+ [
1130
+ "\"kicking field goal\"",
1131
+ 0.0027115345001220703
1132
+ ],
1133
+ [
1134
+ "\"passing American football (not in game)\"",
1135
+ 0.0026032112073153257
1136
+ ],
1137
+ [
1138
+ "\"side kick\"",
1139
+ 0.0025289678014814854
1140
+ ],
1141
+ [
1142
+ "\"high kick\"",
1143
+ 0.002494329586625099
1144
+ ]
1145
+ ],
1146
+ "segment_053.mov": [
1147
+ [
1148
+ "\"passing American football (in game)\"",
1149
+ 0.006694582756608725
1150
+ ],
1151
+ [
1152
+ "\"passing American football (not in game)\"",
1153
+ 0.0025113301817327738
1154
+ ],
1155
+ [
1156
+ "\"side kick\"",
1157
+ 0.0024927803315222263
1158
+ ],
1159
+ [
1160
+ "\"kicking field goal\"",
1161
+ 0.0024906357284635305
1162
+ ],
1163
+ [
1164
+ "\"high kick\"",
1165
+ 0.002489699050784111
1166
+ ]
1167
+ ],
1168
+ "segment_054.mov": [
1169
+ [
1170
+ "\"passing American football (in game)\"",
1171
+ 0.006701494567096233
1172
+ ],
1173
+ [
1174
+ "\"passing American football (not in game)\"",
1175
+ 0.0025095203891396523
1176
+ ],
1177
+ [
1178
+ "\"kicking field goal\"",
1179
+ 0.0024933733511716127
1180
+ ],
1181
+ [
1182
+ "\"side kick\"",
1183
+ 0.002489532344043255
1184
+ ],
1185
+ [
1186
+ "headbutting",
1187
+ 0.002489422680810094
1188
+ ]
1189
+ ],
1190
+ "segment_055.mov": [
1191
+ [
1192
+ "\"passing American football (in game)\"",
1193
+ 0.005614574532955885
1194
+ ],
1195
+ [
1196
+ "\"kicking field goal\"",
1197
+ 0.002844724338501692
1198
+ ],
1199
+ [
1200
+ "\"tossing coin\"",
1201
+ 0.0025539705529809
1202
+ ],
1203
+ [
1204
+ "\"passing American football (not in game)\"",
1205
+ 0.0025522371288388968
1206
+ ],
1207
+ [
1208
+ "headbutting",
1209
+ 0.0024937023408710957
1210
+ ]
1211
+ ],
1212
+ "segment_056.mov": [
1213
+ [
1214
+ "headbutting",
1215
+ 0.003259368008002639
1216
+ ],
1217
+ [
1218
+ "\"pumping fist\"",
1219
+ 0.0029684980399906635
1220
+ ],
1221
+ [
1222
+ "\"playing ice hockey\"",
1223
+ 0.0029396419413387775
1224
+ ],
1225
+ [
1226
+ "\"shaking hands\"",
1227
+ 0.002817715285345912
1228
+ ],
1229
+ [
1230
+ "\"passing American football (in game)\"",
1231
+ 0.002679395256564021
1232
+ ]
1233
+ ],
1234
+ "segment_057.mov": [
1235
+ [
1236
+ "bobsledding",
1237
+ 0.004842189606279135
1238
+ ],
1239
+ [
1240
+ "\"pumping fist\"",
1241
+ 0.002615878591313958
1242
+ ],
1243
+ [
1244
+ "\"driving car\"",
1245
+ 0.002567970659583807
1246
+ ],
1247
+ [
1248
+ "\"playing poker\"",
1249
+ 0.0025621275417506695
1250
+ ],
1251
+ [
1252
+ "\"playing ice hockey\"",
1253
+ 0.002544831018894911
1254
+ ]
1255
+ ],
1256
+ "segment_058.mov": [
1257
+ [
1258
+ "motorcycling",
1259
+ 0.002834487706422806
1260
+ ],
1261
+ [
1262
+ "\"driving car\"",
1263
+ 0.002728639403358102
1264
+ ],
1265
+ [
1266
+ "\"changing wheel\"",
1267
+ 0.0027119864244014025
1268
+ ],
1269
+ [
1270
+ "bobsledding",
1271
+ 0.002644300926476717
1272
+ ],
1273
+ [
1274
+ "kissing",
1275
+ 0.002592987846583128
1276
+ ]
1277
+ ],
1278
+ "segment_059.mov": [
1279
+ [
1280
+ "bobsledding",
1281
+ 0.004265598952770233
1282
+ ],
1283
+ [
1284
+ "\"playing ice hockey\"",
1285
+ 0.0030175303108990192
1286
+ ],
1287
+ [
1288
+ "\"playing paintball\"",
1289
+ 0.002638093428686261
1290
+ ],
1291
+ [
1292
+ "motorcycling",
1293
+ 0.0025540166534483433
1294
+ ],
1295
+ [
1296
+ "\"riding mountain bike\"",
1297
+ 0.002545550698414445
1298
+ ]
1299
+ ],
1300
+ "segment_060.mov": [
1301
+ [
1302
+ "\"passing American football (in game)\"",
1303
+ 0.005962858442217112
1304
+ ],
1305
+ [
1306
+ "\"kicking field goal\"",
1307
+ 0.002803174778819084
1308
+ ],
1309
+ [
1310
+ "\"passing American football (not in game)\"",
1311
+ 0.0025008893571794033
1312
+ ],
1313
+ [
1314
+ "\"side kick\"",
1315
+ 0.0024952334351837635
1316
+ ],
1317
+ [
1318
+ "headbutting",
1319
+ 0.002492264611646533
1320
+ ]
1321
+ ],
1322
+ "segment_061.mov": [
1323
+ [
1324
+ "\"passing American football (in game)\"",
1325
+ 0.006750195287168026
1326
+ ],
1327
+ [
1328
+ "\"kicking field goal\"",
1329
+ 0.0024920343421399593
1330
+ ],
1331
+ [
1332
+ "\"passing American football (not in game)\"",
1333
+ 0.002491830848157406
1334
+ ],
1335
+ [
1336
+ "\"side kick\"",
1337
+ 0.0024899402633309364
1338
+ ],
1339
+ [
1340
+ "\"high kick\"",
1341
+ 0.002489452948793769
1342
+ ]
1343
+ ],
1344
+ "segment_062.mov": [
1345
+ [
1346
+ "\"passing American football (in game)\"",
1347
+ 0.006219817325472832
1348
+ ],
1349
+ [
1350
+ "\"passing American football (not in game)\"",
1351
+ 0.002605071058496833
1352
+ ],
1353
+ [
1354
+ "headbutting",
1355
+ 0.0025401373859494925
1356
+ ],
1357
+ [
1358
+ "\"kicking field goal\"",
1359
+ 0.0025001864414662123
1360
+ ],
1361
+ [
1362
+ "\"pumping fist\"",
1363
+ 0.002497575245797634
1364
+ ]
1365
+ ],
1366
+ "segment_063.mov": [
1367
+ [
1368
+ "marching",
1369
+ 0.003558160038664937
1370
+ ],
1371
+ [
1372
+ "\"passing American football (in game)\"",
1373
+ 0.0030603946652263403
1374
+ ],
1375
+ [
1376
+ "\"tango dancing\"",
1377
+ 0.00266551086679101
1378
+ ],
1379
+ [
1380
+ "\"side kick\"",
1381
+ 0.002660425379872322
1382
+ ],
1383
+ [
1384
+ "\"passing American football (not in game)\"",
1385
+ 0.002627450041472912
1386
+ ]
1387
+ ],
1388
+ "segment_064.mov": [
1389
+ [
1390
+ "\"passing American football (in game)\"",
1391
+ 0.00557365408167243
1392
+ ],
1393
+ [
1394
+ "\"passing American football (not in game)\"",
1395
+ 0.0027207054663449526
1396
+ ],
1397
+ [
1398
+ "headbutting",
1399
+ 0.0026054433546960354
1400
+ ],
1401
+ [
1402
+ "\"pumping fist\"",
1403
+ 0.00251823291182518
1404
+ ],
1405
+ [
1406
+ "\"kicking field goal\"",
1407
+ 0.002515583299100399
1408
+ ]
1409
+ ],
1410
+ "segment_065.mov": [
1411
+ [
1412
+ "\"side kick\"",
1413
+ 0.005902828648686409
1414
+ ],
1415
+ [
1416
+ "\"high kick\"",
1417
+ 0.0025668020825833082
1418
+ ],
1419
+ [
1420
+ "wrestling",
1421
+ 0.0025415299460291862
1422
+ ],
1423
+ [
1424
+ "squat",
1425
+ 0.0025292884092777967
1426
+ ],
1427
+ [
1428
+ "\"drop kicking\"",
1429
+ 0.00251045823097229
1430
+ ]
1431
+ ],
1432
+ "segment_066.mov": [
1433
+ [
1434
+ "bobsledding",
1435
+ 0.003806664375588298
1436
+ ],
1437
+ [
1438
+ "\"changing wheel\"",
1439
+ 0.0029659303836524487
1440
+ ],
1441
+ [
1442
+ "\"punching bag\"",
1443
+ 0.0027637933380901814
1444
+ ],
1445
+ [
1446
+ "headbutting",
1447
+ 0.00258650747127831
1448
+ ],
1449
+ [
1450
+ "motorcycling",
1451
+ 0.002585215028375387
1452
+ ]
1453
+ ],
1454
+ "segment_067.mov": [
1455
+ [
1456
+ "\"changing wheel\"",
1457
+ 0.0038947509601712227
1458
+ ],
1459
+ [
1460
+ "\"pushing car\"",
1461
+ 0.002689485903829336
1462
+ ],
1463
+ [
1464
+ "\"driving car\"",
1465
+ 0.00266862940043211
1466
+ ],
1467
+ [
1468
+ "\"changing oil\"",
1469
+ 0.0026266295462846756
1470
+ ],
1471
+ [
1472
+ "\"arm wrestling\"",
1473
+ 0.0025696069933474064
1474
+ ]
1475
+ ],
1476
+ "segment_068.mov": [
1477
+ [
1478
+ "\"passing American football (not in game)\"",
1479
+ 0.0030197601299732924
1480
+ ],
1481
+ [
1482
+ "\"passing American football (in game)\"",
1483
+ 0.0029855112079530954
1484
+ ],
1485
+ [
1486
+ "\"kicking field goal\"",
1487
+ 0.0027115403208881617
1488
+ ],
1489
+ [
1490
+ "\"catching or throwing baseball\"",
1491
+ 0.0026096913497895002
1492
+ ],
1493
+ [
1494
+ "\"high kick\"",
1495
+ 0.0026070410385727882
1496
+ ]
1497
+ ],
1498
+ "segment_069.mov": [
1499
+ [
1500
+ "\"passing American football (in game)\"",
1501
+ 0.005361294839531183
1502
+ ],
1503
+ [
1504
+ "\"kicking field goal\"",
1505
+ 0.002796306274831295
1506
+ ],
1507
+ [
1508
+ "\"passing American football (not in game)\"",
1509
+ 0.0027009581681340933
1510
+ ],
1511
+ [
1512
+ "\"side kick\"",
1513
+ 0.002553092548623681
1514
+ ],
1515
+ [
1516
+ "\"high kick\"",
1517
+ 0.002506962278857827
1518
+ ]
1519
+ ],
1520
+ "segment_070.mov": [
1521
+ [
1522
+ "\"passing American football (in game)\"",
1523
+ 0.005472357384860516
1524
+ ],
1525
+ [
1526
+ "\"passing American football (not in game)\"",
1527
+ 0.002799208741635084
1528
+ ],
1529
+ [
1530
+ "\"kicking field goal\"",
1531
+ 0.0027042534202337265
1532
+ ],
1533
+ [
1534
+ "\"side kick\"",
1535
+ 0.0025148894637823105
1536
+ ],
1537
+ [
1538
+ "\"catching or throwing baseball\"",
1539
+ 0.002496932167559862
1540
+ ]
1541
+ ],
1542
+ "segment_071.mov": [
1543
+ [
1544
+ "\"side kick\"",
1545
+ 0.003893344197422266
1546
+ ],
1547
+ [
1548
+ "\"passing American football (in game)\"",
1549
+ 0.0035547567531466484
1550
+ ],
1551
+ [
1552
+ "\"kicking field goal\"",
1553
+ 0.002741483272984624
1554
+ ],
1555
+ [
1556
+ "\"passing American football (not in game)\"",
1557
+ 0.0026810814160853624
1558
+ ],
1559
+ [
1560
+ "\"catching or throwing baseball\"",
1561
+ 0.0025338695850223303
1562
+ ]
1563
+ ],
1564
+ "segment_072.mov": [
1565
+ [
1566
+ "\"passing American football (in game)\"",
1567
+ 0.005563896149396896
1568
+ ],
1569
+ [
1570
+ "\"passing American football (not in game)\"",
1571
+ 0.0027015593368560076
1572
+ ],
1573
+ [
1574
+ "\"side kick\"",
1575
+ 0.002657951321452856
1576
+ ],
1577
+ [
1578
+ "\"kicking field goal\"",
1579
+ 0.0026104655116796494
1580
+ ],
1581
+ [
1582
+ "\"catching or throwing baseball\"",
1583
+ 0.0024953498505055904
1584
+ ]
1585
+ ],
1586
+ "segment_073.mov": [
1587
+ [
1588
+ "\"passing American football (in game)\"",
1589
+ 0.006470989435911179
1590
+ ],
1591
+ [
1592
+ "\"passing American football (not in game)\"",
1593
+ 0.0025515288580209017
1594
+ ],
1595
+ [
1596
+ "\"side kick\"",
1597
+ 0.0025365715846419334
1598
+ ],
1599
+ [
1600
+ "\"kicking field goal\"",
1601
+ 0.002492384286597371
1602
+ ],
1603
+ [
1604
+ "\"high kick\"",
1605
+ 0.002490945626050234
1606
+ ]
1607
+ ],
1608
+ "segment_074.mov": [
1609
+ [
1610
+ "\"passing American football (in game)\"",
1611
+ 0.004092047456651926
1612
+ ],
1613
+ [
1614
+ "\"passing American football (not in game)\"",
1615
+ 0.0037548826076090336
1616
+ ],
1617
+ [
1618
+ "\"side kick\"",
1619
+ 0.0026034193579107523
1620
+ ],
1621
+ [
1622
+ "\"kicking field goal\"",
1623
+ 0.0025540809147059917
1624
+ ],
1625
+ [
1626
+ "\"catching or throwing baseball\"",
1627
+ 0.0025116554461419582
1628
+ ]
1629
+ ],
1630
+ "segment_075.mov": [
1631
+ [
1632
+ "\"passing American football (in game)\"",
1633
+ 0.006258341949433088
1634
+ ],
1635
+ [
1636
+ "\"passing American football (not in game)\"",
1637
+ 0.002621858147904277
1638
+ ],
1639
+ [
1640
+ "\"kicking field goal\"",
1641
+ 0.0025423644110560417
1642
+ ],
1643
+ [
1644
+ "\"catching or throwing baseball\"",
1645
+ 0.0024970977101475
1646
+ ],
1647
+ [
1648
+ "\"pumping fist\"",
1649
+ 0.0024926913902163506
1650
+ ]
1651
+ ],
1652
+ "segment_076.mov": [
1653
+ [
1654
+ "\"hurling (sport)\"",
1655
+ 0.003916610963642597
1656
+ ],
1657
+ [
1658
+ "headbutting",
1659
+ 0.0029018200002610683
1660
+ ],
1661
+ [
1662
+ "\"passing American football (in game)\"",
1663
+ 0.0027735705953091383
1664
+ ],
1665
+ [
1666
+ "\"passing American football (not in game)\"",
1667
+ 0.00273358216509223
1668
+ ],
1669
+ [
1670
+ "\"kicking field goal\"",
1671
+ 0.0026465952396392822
1672
+ ]
1673
+ ],
1674
+ "segment_077.mov": []
1675
  }
config.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Configuration constants and settings for NFL Play Detection System.
3
+
4
+ This module centralizes all configuration parameters to make the system
5
+ easier to tune and maintain.
6
+ """
7
+
8
+ import torch
9
+
10
+ # ============================================================================
11
+ # MODEL CONFIGURATION
12
+ # ============================================================================
13
+
14
+ # Video Classification Model
15
+ VIDEO_MODEL_NAME = "x3d_m" # Options: x3d_xs, x3d_s, x3d_m, x3d_l
16
+ DEVICE = torch.device("cpu") # Use "cuda" for GPU acceleration if available
17
+
18
+ # Audio Transcription Model
19
+ AUDIO_MODEL_NAME = "openai/whisper-medium" # Options: whisper-base, whisper-medium, whisper-large
20
+ AUDIO_DEVICE = -1 # -1 for CPU, 0+ for GPU device index
21
+
22
+ # ============================================================================
23
+ # VIDEO PROCESSING PARAMETERS
24
+ # ============================================================================
25
+
26
+ # Video preprocessing settings
27
+ VIDEO_CLIP_DURATION = 2.0 # Duration in seconds for video clips
28
+ VIDEO_NUM_SAMPLES = 16 # Number of frames to sample from clip
29
+ VIDEO_SIZE = 224 # Spatial size for model input (224x224)
30
+
31
+ # Kinetics-400 label map
32
+ KINETICS_LABELS_URL = "https://dl.fbaipublicfiles.com/pyslowfast/dataset/class_names/kinetics_classnames.json"
33
+ KINETICS_LABELS_PATH = "kinetics_classnames.json"
34
+
35
+ # Video preprocessing normalization (ImageNet standards)
36
+ VIDEO_MEAN = [0.45, 0.45, 0.45]
37
+ VIDEO_STD = [0.225, 0.225, 0.225]
38
+
39
+ # ============================================================================
40
+ # PLAY DETECTION PARAMETERS
41
+ # ============================================================================
42
+
43
+ # Confidence thresholds for play state detection
44
+ PLAY_CONFIDENCE_THRESHOLD = 0.002
45
+ PLAY_BOUNDARY_WINDOW_SIZE = 3
46
+
47
+ # NFL-specific action classifications for play state detection
48
+ PLAY_START_INDICATORS = [
49
+ "passing American football (in game)",
50
+ "kicking field goal",
51
+ "side kick",
52
+ "high kick"
53
+ ]
54
+
55
+ PLAY_ACTION_INDICATORS = [
56
+ "catching or throwing baseball", # Often misclassified football throws
57
+ "catching or throwing softball",
58
+ "playing cricket", # Sometimes catches football
59
+ "throwing ball"
60
+ ]
61
+
62
+ NON_PLAY_INDICATORS = [
63
+ "applauding",
64
+ "marching",
65
+ "sitting",
66
+ "standing",
67
+ "clapping",
68
+ "cheering"
69
+ ]
70
+
71
+ # ============================================================================
72
+ # AUDIO PROCESSING PARAMETERS
73
+ # ============================================================================
74
+
75
+ # Audio preprocessing settings
76
+ AUDIO_SAMPLE_RATE = 16000
77
+ AUDIO_MIN_DURATION = 0.5 # Minimum duration in seconds to process
78
+ AUDIO_MIN_AMPLITUDE = 0.01 # Minimum amplitude threshold
79
+
80
+ # FFmpeg audio filtering parameters
81
+ AUDIO_HIGHPASS_FREQ = 80 # Hz - remove low frequency noise
82
+ AUDIO_LOWPASS_FREQ = 8000 # Hz - remove high frequency noise
83
+
84
+ # Whisper generation parameters (optimized for speed and NFL content)
85
+ WHISPER_GENERATION_PARAMS = {
86
+ "language": "en", # Force English detection
87
+ "task": "transcribe", # Don't translate
88
+ "temperature": 0.0, # Deterministic output
89
+ "do_sample": False, # Greedy decoding (fastest)
90
+ "num_beams": 1, # Single beam (fastest)
91
+ "length_penalty": 0.0, # No length penalty for speed
92
+ "early_stopping": True # Stop as soon as possible
93
+ }
94
+
95
+ # ============================================================================
96
+ # NFL SPORTS VOCABULARY AND CORRECTIONS
97
+ # ============================================================================
98
+
99
+ # Comprehensive NFL terminology for transcription enhancement
100
+ NFL_TEAMS = [
101
+ "Patriots", "Cowboys", "Packers", "49ers", "Chiefs", "Bills", "Ravens", "Steelers",
102
+ "Eagles", "Giants", "Rams", "Saints", "Buccaneers", "Panthers", "Falcons", "Cardinals",
103
+ "Seahawks", "Broncos", "Raiders", "Chargers", "Dolphins", "Jets", "Colts", "Titans",
104
+ "Jaguars", "Texans", "Browns", "Bengals", "Lions", "Vikings", "Bears", "Commanders"
105
+ ]
106
+
107
+ NFL_POSITIONS = [
108
+ "quarterback", "QB", "running back", "wide receiver", "tight end", "offensive line",
109
+ "defensive end", "linebacker", "cornerback", "safety", "kicker", "punter",
110
+ "center", "guard", "tackle", "fullback", "nose tackle", "middle linebacker"
111
+ ]
112
+
113
+ NFL_TERMINOLOGY = [
114
+ "touchdown", "field goal", "first down", "second down", "third down", "fourth down",
115
+ "punt", "fumble", "interception", "sack", "blitz", "snap", "hike", "audible",
116
+ "red zone", "end zone", "yard line", "scrimmage", "pocket", "shotgun formation",
117
+ "play action", "screen pass", "draw play", "bootleg", "rollout", "scramble",
118
+ "timeout", "penalty", "flag", "holding", "false start", "offside", "encroachment",
119
+ "pass interference", "roughing the passer", "illegal formation", "delay of game"
120
+ ]
121
+
122
+ NFL_GAME_SITUATIONS = [
123
+ "two minute warning", "overtime", "coin toss", "kickoff", "touchback", "fair catch",
124
+ "onside kick", "safety", "conversion", "extra point", "two point conversion",
125
+ "challenge", "replay", "incomplete", "completion", "rushing yards", "passing yards"
126
+ ]
127
+
128
+ NFL_COMMENTARY_TERMS = [
129
+ "yards to go", "first and ten", "goal line", "midfield", "hash marks",
130
+ "pocket presence", "arm strength", "accuracy", "mobility", "coverage",
131
+ "rush defense", "pass rush", "secondary", "offensive line", "defensive line"
132
+ ]
133
+
134
+ # Combine all NFL terms for comprehensive vocabulary
135
+ NFL_SPORTS_CONTEXT = NFL_TEAMS + NFL_POSITIONS + NFL_TERMINOLOGY + NFL_GAME_SITUATIONS + NFL_COMMENTARY_TERMS
136
+
137
+ # ============================================================================
138
+ # FILE PROCESSING PARAMETERS
139
+ # ============================================================================
140
+
141
+ # Supported video file formats
142
+ SUPPORTED_VIDEO_FORMATS = ["*.mov", "*.mp4"]
143
+
144
+ # Default output file names
145
+ DEFAULT_CLASSIFICATION_FILE = "classification.json"
146
+ DEFAULT_TRANSCRIPT_FILE = "transcripts.json"
147
+ DEFAULT_PLAY_ANALYSIS_FILE = "play_analysis.json"
148
+
149
+ # Progress saving intervals
150
+ VIDEO_SAVE_INTERVAL = 5 # Save video results every N clips
151
+ AUDIO_SAVE_INTERVAL = 3 # Save audio results every N clips
152
+
153
+ # ============================================================================
154
+ # LOGGING AND DEBUG SETTINGS
155
+ # ============================================================================
156
+
157
+ # Debug output control
158
+ ENABLE_DEBUG_PRINTS = False
159
+ ENABLE_FRAME_SHAPE_DEBUG = False # Can be expensive for large batches
160
+
161
+ # Progress reporting
162
+ ENABLE_PROGRESS_BARS = True
163
+ ENABLE_PERFORMANCE_TIMING = True
inference.py CHANGED
@@ -1,471 +1,96 @@
1
- import os
2
- import subprocess
3
- import numpy as np
4
- import torch
5
- import json
6
- import urllib.request
7
- from pytorchvideo.data.encoded_video import EncodedVideo
8
- from transformers import pipeline
9
 
10
- # === Config ===
11
- model_name = "x3d_m" # options: x3d_xs, x3d_s, x3d_m, x3d_l
12
- device = torch.device("cpu")
13
 
14
- # === Load Model ===
15
- model = torch.hub.load(
16
- "facebookresearch/pytorchvideo",
17
- model_name,
18
- pretrained=True
19
- ).to(device).eval()
20
 
21
- # === Load Kinetics-400 Labels ===
22
- label_map_path = "kinetics_classnames.json"
23
- if not os.path.exists(label_map_path):
24
- urllib.request.urlretrieve(
25
- "https://dl.fbaipublicfiles.com/pyslowfast/dataset/class_names/kinetics_classnames.json",
26
- label_map_path
27
- )
28
- with open(label_map_path, "r") as f:
29
- raw = json.load(f)
30
 
31
- # Determine mapping: list, numeric-keys dict, or inverted dict
32
- if isinstance(raw, list):
33
- kinetics_labels = {i: raw[i] for i in range(len(raw))}
34
- elif isinstance(raw, dict):
35
- # check if keys are numeric strings
36
- numeric_keys = True
37
- for k in raw.keys():
38
- try:
39
- int(k)
40
- except:
41
- numeric_keys = False
42
- break
43
- if numeric_keys:
44
- kinetics_labels = {int(k): v for k, v in raw.items()}
45
- else:
46
- # assume values are indices
47
- kinetics_labels = {}
48
- for k, v in raw.items():
49
- try:
50
- idx = int(v)
51
- kinetics_labels[idx] = k
52
- except:
53
- continue
54
- else:
55
- raise ValueError("Unexpected label map format for kinetics_classnames.json")
56
 
57
- # === Preprocessing ===
58
- def preprocess(frames, num_samples: int = 16, size: int = 224) -> torch.Tensor:
59
- C, T, H, W = frames.shape
60
- vid = frames.permute(1, 0, 2, 3).float() / 255.0
61
- idxs = torch.linspace(0, T - 1, num_samples).long()
62
- clip = vid[idxs]
63
- top = max((H - size) // 2, 0)
64
- left = max((W - size) // 2, 0)
65
- clip = clip[:, :, top:top+size, left:left+size]
66
- clip = clip.permute(1, 0, 2, 3).unsqueeze(0)
67
- mean = torch.tensor([0.45, 0.45, 0.45], device=device).view(1, 3, 1, 1, 1)
68
- std = torch.tensor([0.225, 0.225, 0.225], device=device).view(1, 3, 1, 1, 1)
69
- clip = (clip - mean) / std
70
- return clip
71
 
72
- # === Play State Detection ===
73
- def analyze_play_state(predictions, confidence_threshold=0.002):
74
- """
75
- Analyze predictions to determine if this is likely start, middle, or end of play
76
  """
77
- if not predictions:
78
- return "unknown", 0.0
79
-
80
- # Football-specific labels that indicate different play states
81
- play_start_indicators = [
82
- "passing American football (in game)",
83
- "kicking field goal",
84
- "side kick",
85
- "high kick"
86
- ]
87
-
88
- play_action_indicators = [
89
- "catching or throwing baseball", # Often misclassified football throws
90
- "catching or throwing softball",
91
- "playing cricket", # Sometimes catches football
92
- "throwing ball"
93
- ]
94
 
95
- non_play_indicators = [
96
- "applauding",
97
- "marching",
98
- "sitting",
99
- "standing",
100
- "clapping",
101
- "cheering"
102
- ]
103
-
104
- # Calculate weighted scores for each state
105
- play_start_score = 0.0
106
- play_action_score = 0.0
107
- non_play_score = 0.0
108
-
109
- for label, confidence in predictions:
110
- # Remove quotes and normalize
111
- clean_label = label.replace('"', '').lower()
112
-
113
- if any(indicator.lower() in clean_label for indicator in play_start_indicators):
114
- play_start_score += confidence * 2.0 # Weight play-specific actions higher
115
- elif any(indicator.lower() in clean_label for indicator in play_action_indicators):
116
- play_action_score += confidence
117
- elif any(indicator.lower() in clean_label for indicator in non_play_indicators):
118
- non_play_score += confidence
119
-
120
- # Determine play state
121
- max_score = max(play_start_score, play_action_score, non_play_score)
122
-
123
- if max_score < confidence_threshold:
124
- return "unknown", max_score
125
- elif play_start_score == max_score:
126
- return "play_active", play_start_score
127
- elif play_action_score == max_score:
128
- return "play_action", play_action_score
129
- else:
130
- return "non_play", non_play_score
131
-
132
- # === Enhanced Prediction ===
133
- def predict_clip(path: str):
134
- try:
135
- video = EncodedVideo.from_path(path)
136
- clip_data = video.get_clip(0, 2.0)
137
- frames = clip_data["video"]
138
-
139
- if frames is None:
140
- print(f"[ERROR] Failed to load video frames from {path}")
141
- return []
142
-
143
- # print(f"[DEBUG] Loaded video frames shape: {frames.shape}") # Disabled for speed
144
- inp = preprocess(frames).to(device)
145
- with torch.no_grad():
146
- logits = model(inp)
147
- probs = torch.softmax(logits, dim=1)[0]
148
- top5 = torch.topk(probs, k=5)
149
- results = []
150
- for idx_tensor, score in zip(top5.indices, top5.values):
151
- idx = idx_tensor.item()
152
- label = kinetics_labels.get(idx, f"Class_{idx}")
153
- results.append((label, float(score)))
154
-
155
- # Add play state analysis
156
- play_state, confidence = analyze_play_state(results)
157
- print(f"[PLAY STATE] {play_state} (confidence: {confidence:.3f})")
158
-
159
- return results
160
- except Exception as e:
161
- print(f"[ERROR] Failed to process {path}: {e}")
162
- return []
163
-
164
- # === Advanced Play Sequence Detection ===
165
- def detect_play_boundaries(clip_results, window_size=3):
166
  """
167
- Analyze sequence of clips to detect play start and end boundaries
168
- """
169
- if len(clip_results) < window_size:
170
- return []
171
-
172
- play_states = []
173
- for results in clip_results:
174
- state, confidence = analyze_play_state(results)
175
- play_states.append((state, confidence))
176
-
177
- boundaries = []
178
-
179
- # Look for transitions from non_play -> play_active (START)
180
- # and play_active -> non_play (END)
181
- for i in range(len(play_states) - 1):
182
- current_state, current_conf = play_states[i]
183
- next_state, next_conf = play_states[i + 1]
184
-
185
- if (current_state in ["non_play", "unknown"] and
186
- next_state in ["play_active", "play_action"] and
187
- next_conf > 0.002):
188
- boundaries.append(("play_start", i + 1, next_conf))
189
-
190
- if (current_state in ["play_active", "play_action"] and
191
- next_state in ["non_play", "unknown"] and
192
- current_conf > 0.002):
193
- boundaries.append(("play_end", i, current_conf))
194
-
195
- return boundaries
196
-
197
- # === Audio ASR Setup ===
198
- # Using Whisper Medium for optimal NFL broadcast transcription accuracy
199
- asr = pipeline(
200
- "automatic-speech-recognition",
201
- model="openai/whisper-medium", # Medium model for complex broadcast audio
202
- device=-1,
203
- # Optimized for English sports content
204
- generate_kwargs={
205
- "language": "en", # Force English to avoid multilingual detection
206
- "task": "transcribe" # Don't translate
207
- }
208
- )
209
-
210
- # === Sports-Specific Vocabulary ===
211
- NFL_SPORTS_CONTEXT = [
212
- # NFL Teams
213
- "Patriots", "Cowboys", "Packers", "49ers", "Chiefs", "Bills", "Ravens", "Steelers",
214
- "Eagles", "Giants", "Rams", "Saints", "Buccaneers", "Panthers", "Falcons", "Cardinals",
215
- "Seahawks", "Broncos", "Raiders", "Chargers", "Dolphins", "Jets", "Colts", "Titans",
216
- "Jaguars", "Texans", "Browns", "Bengals", "Lions", "Vikings", "Bears", "Commanders",
217
-
218
- # NFL Positions
219
- "quarterback", "QB", "running back", "wide receiver", "tight end", "offensive line",
220
- "defensive end", "linebacker", "cornerback", "safety", "kicker", "punter",
221
- "center", "guard", "tackle", "fullback", "nose tackle", "middle linebacker",
222
-
223
- # NFL Terminology
224
- "touchdown", "field goal", "first down", "second down", "third down", "fourth down",
225
- "punt", "fumble", "interception", "sack", "blitz", "snap", "hike", "audible",
226
- "red zone", "end zone", "yard line", "scrimmage", "pocket", "shotgun formation",
227
- "play action", "screen pass", "draw play", "bootleg", "rollout", "scramble",
228
- "timeout", "penalty", "flag", "holding", "false start", "offside", "encroachment",
229
- "pass interference", "roughing the passer", "illegal formation", "delay of game",
230
-
231
- # Game Situations
232
- "two minute warning", "overtime", "coin toss", "kickoff", "touchback", "fair catch",
233
- "onside kick", "safety", "conversion", "extra point", "two point conversion",
234
- "challenge", "replay", "incomplete", "completion", "rushing yards", "passing yards",
235
-
236
- # Common Commentary
237
- "yards to go", "first and ten", "goal line", "midfield", "hash marks",
238
- "pocket presence", "arm strength", "accuracy", "mobility", "coverage",
239
- "rush defense", "pass rush", "secondary", "offensive line", "defensive line"
240
- ]
241
-
242
- NFL_PROMPT = " ".join(NFL_SPORTS_CONTEXT[:20]) # Use first 20 terms as prompt context
243
-
244
- # === Audio Loading via FFmpeg ===
245
- def load_audio(path: str, sr: int = 16000):
246
- """Enhanced audio loading with filtering and normalization"""
247
- cmd = [
248
- "ffmpeg", "-i", path,
249
- "-af", "highpass=f=80,lowpass=f=8000,loudnorm", # Filter noise and normalize
250
- "-f", "s16le",
251
- "-acodec", "pcm_s16le",
252
- "-ac", "1", "-ar", str(sr),
253
- "pipe:1"
254
- ]
255
- proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
256
- raw = proc.stdout.read()
257
- audio = np.frombuffer(raw, np.int16).astype(np.float32) / 32768.0
258
-
259
- # Normalize audio levels
260
- if len(audio) > 0:
261
- audio = audio / (np.max(np.abs(audio)) + 1e-8)
262
-
263
- return audio, sr
264
-
265
- # === Enhanced Transcription with Sports Context ===
266
- def transcribe_clip(path: str) -> str:
267
- audio, sr = load_audio(path, sr=16000)
268
-
269
- # Skip transcription if audio is too short or quiet
270
- if len(audio) < sr * 0.5: # Less than 0.5 seconds
271
- return ""
272
-
273
- if np.max(np.abs(audio)) < 0.01: # Very quiet audio
274
- return ""
275
-
276
- try:
277
- # Speed-optimized parameters for fast testing
278
- result = asr(
279
- audio,
280
- generate_kwargs={
281
- "language": "en",
282
- "task": "transcribe",
283
- "temperature": 0.0, # Deterministic output
284
- "do_sample": False, # Greedy decoding (fastest)
285
- "num_beams": 1, # Single beam (fastest)
286
- "length_penalty": 0.0, # No length penalty for speed
287
- "early_stopping": True # Stop as soon as possible
288
- }
289
- )
290
- text = result.get("text", "").strip()
291
-
292
- # Clean up common Whisper artifacts
293
- text = text.replace("[BLANK_AUDIO]", "").strip()
294
- text = text.replace("♪", "").strip() # Remove music notes
295
-
296
- # Post-process with sports-specific corrections
297
- text = apply_sports_corrections(text)
298
-
299
- return text
300
- except Exception as e:
301
- print(f"[WARN] Transcription failed: {e}")
302
- return ""
303
-
304
- def apply_sports_corrections(text: str) -> str:
305
- """Apply NFL-specific text corrections and standardization"""
306
- import re
307
 
308
- if not text:
309
- return text
 
310
 
311
- # Common misheard sports terms corrections
312
- corrections = {
313
- # Position corrections
314
- r'\bqb\b': "QB",
315
- r'\bquarter back\b': "quarterback",
316
- r'\bwide receiver\b': "wide receiver",
317
- r'\btight end\b': "tight end",
318
- r'\brunning back\b': "running back",
319
- r'\bline backer\b': "linebacker",
320
- r'\bcorner back\b': "cornerback",
321
-
322
- # Play corrections
323
- r'\btouch down\b': "touchdown",
324
- r'\bfield goal\b': "field goal",
325
- r'\bfirst down\b': "first down",
326
- r'\bsecond down\b': "second down",
327
- r'\bthird down\b': "third down",
328
- r'\bfourth down\b': "fourth down",
329
- r'\byard line\b': "yard line",
330
- r'\bend zone\b': "end zone",
331
- r'\bred zone\b': "red zone",
332
- r'\btwo minute warning\b': "two minute warning",
333
-
334
- # Common misheard words
335
- r'\bfourty\b': "forty",
336
- r'\bfourty yard\b': "forty yard",
337
- r'\btwenny\b': "twenty",
338
- r'\bthirty yard\b': "thirty yard",
339
-
340
- # Numbers/downs that are often misheard
341
- r'\b1st\b': "first",
342
- r'\b2nd\b': "second",
343
- r'\b3rd\b': "third",
344
- r'\b4th\b': "fourth",
345
- r'\b1st and 10\b': "first and ten",
346
- r'\b2nd and long\b': "second and long",
347
- r'\b3rd and short\b': "third and short",
348
-
349
- # Team name corrections (common mishears)
350
- r'\bforty niners\b': "49ers",
351
- r'\bforty-niners\b': "49ers",
352
- r'\bsan francisco\b': "49ers",
353
- r'\bnew england\b': "Patriots",
354
- r'\bgreen bay\b': "Packers",
355
- r'\bkansas city\b': "Chiefs",
356
- r'\bnew york giants\b': "Giants",
357
- r'\bnew york jets\b': "Jets",
358
- r'\blos angeles rams\b': "Rams",
359
- r'\blos angeles chargers\b': "Chargers",
360
 
361
- # Yard markers and positions
362
- r'\b10 yard line\b': "ten yard line",
363
- r'\b20 yard line\b': "twenty yard line",
364
- r'\b30 yard line\b': "thirty yard line",
365
- r'\b40 yard line\b': "forty yard line",
366
- r'\b50 yard line\b': "fifty yard line",
367
- r'\bmid field\b': "midfield",
368
- r'\bgoal line\b': "goal line",
369
-
370
- # Penalties and flags
371
- r'\bfalse start\b': "false start",
372
- r'\boff side\b': "offside",
373
- r'\bpass interference\b': "pass interference",
374
- r'\broughing the passer\b': "roughing the passer",
375
- r'\bdelay of game\b': "delay of game",
376
-
377
- # Common play calls
378
- r'\bplay action\b': "play action",
379
- r'\bscreen pass\b': "screen pass",
380
- r'\bdraw play\b': "draw play",
381
- r'\bboot leg\b': "bootleg",
382
- r'\broll out\b': "rollout",
383
- r'\bshot gun\b': "shotgun",
384
- r'\bno huddle\b': "no huddle"
385
- }
386
-
387
- # Apply corrections (case-insensitive)
388
- corrected_text = text
389
- for pattern, replacement in corrections.items():
390
- corrected_text = re.sub(pattern, replacement, corrected_text, flags=re.IGNORECASE)
391
-
392
- # Capitalize specific terms that should always be capitalized
393
- capitalize_terms = ["NFL", "QB", "Patriots", "Cowboys", "Chiefs", "Packers", "49ers",
394
- "Eagles", "Giants", "Rams", "Saints", "Bills", "Ravens", "Steelers"]
395
- for term in capitalize_terms:
396
- pattern = r'\b' + re.escape(term.lower()) + r'\b'
397
- corrected_text = re.sub(pattern, term, corrected_text, flags=re.IGNORECASE)
398
-
399
- # Enhanced spell-check for common NFL terms using fuzzy matching
400
- corrected_text = fuzzy_sports_corrections(corrected_text)
401
 
402
- return corrected_text.strip()
403
 
404
- def fuzzy_sports_corrections(text: str) -> str:
405
- """Apply fuzzy matching for sports terms that might be slightly misheard"""
406
- import re
407
-
408
- # Define common NFL terms and their likely misspellings
409
- fuzzy_corrections = {
410
- # Team names with common misspellings
411
- r'\bpatriots?\b': "Patriots",
412
- r'\bcowboys?\b': "Cowboys",
413
- r'\bpackers?\b': "Packers",
414
- r'\bchief\b': "Chiefs",
415
- r'\bchiefs?\b': "Chiefs",
416
- r'\beagles?\b': "Eagles",
417
- r'\bgiants?\b': "Giants",
418
- r'\brams?\b': "Rams",
419
- r'\bsaints?\b': "Saints",
420
-
421
- # Positions with common variations
422
- r'\bquarterbacks?\b': "quarterback",
423
- r'\brunning backs?\b': "running back",
424
- r'\bwide receivers?\b': "wide receiver",
425
- r'\btight ends?\b': "tight end",
426
- r'\blinebackers?\b': "linebacker",
427
- r'\bcornerbacks?\b': "cornerback",
428
- r'\bsafety\b': "safety",
429
- r'\bsafeties\b': "safety",
430
-
431
- # Play terms
432
- r'\btouchdowns?\b': "touchdown",
433
- r'\bfield goals?\b': "field goal",
434
- r'\binterceptions?\b': "interception",
435
- r'\bfumbles?\b': "fumble",
436
- r'\bsacks?\b': "sack",
437
- r'\bpunt\b': "punt",
438
- r'\bpunts?\b': "punt",
439
-
440
- # Numbers and yards
441
- r'\byards?\b': "yard",
442
- r'\byards? line\b': "yard line",
443
- r'\byard lines?\b': "yard line"
444
- }
445
-
446
- corrected = text
447
- for pattern, replacement in fuzzy_corrections.items():
448
- corrected = re.sub(pattern, replacement, corrected, flags=re.IGNORECASE)
449
-
450
- return corrected
451
 
452
- # === CLI ===
453
  if __name__ == "__main__":
454
- import sys
455
- clip_path = sys.argv[1] if len(sys.argv) > 1 else "segments/segment_000.mov"
456
-
457
- # Video classification + classification.json
458
- preds = predict_clip(clip_path)
459
- with open("classification.json", "w") as f:
460
- json.dump({os.path.basename(clip_path): preds}, f, indent=2)
461
- print("\nTop-5 labels for", clip_path)
462
- for label, score in preds:
463
- print(f"{label:>30s} : {score:.3f}")
464
-
465
- # Audio transcription + transcripts.json
466
- transcript = transcribe_clip(clip_path)
467
- print(f"Transcript for {clip_path}: {transcript}")
468
- with open("transcripts.json", "w") as f:
469
- json.dump({os.path.basename(clip_path): transcript}, f, indent=2)
470
- print("Wrote transcripts.json")
471
-
 
1
+ """
2
+ Legacy Inference Module - Backward Compatibility Interface.
 
 
 
 
 
 
3
 
4
+ This module provides a simplified interface that maintains backward compatibility
5
+ with the original inference.py while leveraging the new modular architecture.
 
6
 
7
+ For new development, use the specific modules directly:
8
+ - video.py: Video classification and play analysis
9
+ - audio.py: Audio transcription and NFL corrections
10
+ - config.py: Configuration and constants
 
 
11
 
12
+ This module is maintained for:
13
+ 1. Backward compatibility with existing scripts
14
+ 2. Simple single-clip processing interface
15
+ 3. Legacy CLI functionality
16
+ """
 
 
 
 
17
 
18
+ import os
19
+ import sys
20
+ import json
21
+ from typing import List, Tuple
22
+
23
+ # Import from new modular structure
24
+ from video import predict_clip, analyze_play_state, detect_play_boundaries
25
+ from audio import transcribe_clip, load_audio, apply_sports_corrections, fuzzy_sports_corrections
26
+
27
+ # Re-export all functions for backward compatibility
28
+ __all__ = [
29
+ 'predict_clip',
30
+ 'analyze_play_state',
31
+ 'detect_play_boundaries',
32
+ 'transcribe_clip',
33
+ 'load_audio',
34
+ 'apply_sports_corrections',
35
+ 'fuzzy_sports_corrections'
36
+ ]
 
 
 
 
 
 
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
+ def main():
 
 
 
40
  """
41
+ CLI interface for single clip processing (backward compatibility).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
+ Usage:
44
+ python inference.py path/to/clip.mov
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  """
46
+ if len(sys.argv) < 2:
47
+ print("Usage: python inference.py <path_to_video_clip>")
48
+ print("Example: python inference.py data/segment_001.mov")
49
+ sys.exit(1)
50
+
51
+ clip_path = sys.argv[1]
52
+
53
+ if not os.path.exists(clip_path):
54
+ print(f"Error: File '{clip_path}' not found")
55
+ sys.exit(1)
56
+
57
+ print(f"Processing: {clip_path}")
58
+ print("=" * 50)
59
+
60
+ # Video classification
61
+ print("🎬 Video Classification:")
62
+ predictions = predict_clip(clip_path)
63
+
64
+ if predictions:
65
+ print(f"\nTop-5 labels for {clip_path}:")
66
+ for label, score in predictions:
67
+ print(f"{label:>30s} : {score:.3f}")
68
+
69
+ # Save classification results
70
+ clip_name = os.path.basename(clip_path)
71
+ with open("classification.json", "w") as f:
72
+ json.dump({clip_name: predictions}, f, indent=2)
73
+ print(f"\n✓ Classification saved to classification.json")
74
+ else:
75
+ print("❌ Video classification failed")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
+ # Audio transcription
78
+ print("\n🎙️ Audio Transcription:")
79
+ transcript = transcribe_clip(clip_path)
80
 
81
+ if transcript:
82
+ print(f"Transcript: {transcript}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
+ # Save transcript results
85
+ clip_name = os.path.basename(clip_path)
86
+ with open("transcripts.json", "w") as f:
87
+ json.dump({clip_name: transcript}, f, indent=2)
88
+ print(f"✓ Transcript saved to transcripts.json")
89
+ else:
90
+ print("ℹ️ No audio content detected or transcription failed")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
+ print("\n🏁 Processing complete!")
93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
 
 
95
  if __name__ == "__main__":
96
+ main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
run_all_clips.py CHANGED
@@ -1,23 +1,56 @@
1
  #!/usr/bin/env python3
2
  """
3
- Loop over all .mov/.mp4 files in the `data/` directory, call `predict_clip` and `transcribe_clip`
4
- from inference.py on each, print the results, and save both classification and transcription
5
- results to separate JSON files as they're generated.
 
 
 
 
 
 
6
  """
 
7
  import os
8
  import glob
9
  import json
10
  import argparse
11
  import time
12
- from inference import predict_clip, transcribe_clip, detect_play_boundaries, analyze_play_state
13
 
 
 
 
 
 
 
 
14
 
15
- def main(input_dir: str = "data", classification_file: str = "classification.json", transcript_file: str = "transcripts.json", play_analysis_file: str = "play_analysis.json", skip_audio: bool = False, max_clips: int = None):
16
- # find video files
17
- patterns = ["*.mov", "*.mp4"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  clips = []
19
- for pat in patterns:
20
- clips.extend(glob.glob(os.path.join(input_dir, pat)))
21
  clips = sorted(clips)
22
  if not clips:
23
  print(f"No clips found in '{input_dir}'.")
@@ -86,8 +119,8 @@ def main(input_dir: str = "data", classification_file: str = "classification.jso
86
  else:
87
  print(f" [WARN] No classification scores (skipped or error)")
88
 
89
- # Write incremental results after every 5 clips or at the end
90
- if i % 5 == 0 or i == len(clips):
91
  try:
92
  with open(classification_file, 'w') as f:
93
  json.dump(classification_results, f, indent=2)
@@ -169,8 +202,8 @@ def main(input_dir: str = "data", classification_file: str = "classification.jso
169
  print(f" [ERROR] Failed to transcribe: {e}")
170
  transcript_results[clip_name] = ""
171
 
172
- # Write incremental results after every 3 clips or at the end
173
- if i % 3 == 0 or i == len(clips):
174
  try:
175
  with open(transcript_file, 'w') as f:
176
  json.dump(transcript_results, f, indent=2)
@@ -213,9 +246,9 @@ if __name__ == "__main__":
213
  parser.add_argument('--video-only', action='store_true', help='Process only video classification (85%% faster)')
214
  parser.add_argument('--audio-only', action='store_true', help='Process only audio transcription (requires existing classification.json)')
215
  parser.add_argument('--max-clips', type=int, help='Limit processing to first N clips (for testing)')
216
- parser.add_argument('--classification-file', default='classification.json', help='Video classification output file')
217
- parser.add_argument('--transcript-file', default='transcripts.json', help='Audio transcript output file')
218
- parser.add_argument('--play-analysis-file', default='play_analysis.json', help='Play analysis output file')
219
 
220
  args = parser.parse_args()
221
 
 
1
  #!/usr/bin/env python3
2
  """
3
+ NFL Play Detection Pipeline - Optimized for continuous processing.
4
+
5
+ This script orchestrates the complete NFL play detection workflow:
6
+ 1. Video classification using X3D models (Phase 1)
7
+ 2. NFL-specific play state analysis and boundary detection
8
+ 3. Audio transcription using Whisper with NFL enhancements (Phase 2)
9
+
10
+ The pipeline is optimized for continuous processing with separate phases,
11
+ allowing for flexible deployment scenarios (real-time, batch, testing).
12
  """
13
+
14
  import os
15
  import glob
16
  import json
17
  import argparse
18
  import time
19
+ from typing import Dict, List, Any, Optional
20
 
21
+ # Import from new modular structure
22
+ from video import predict_clip, analyze_play_state, detect_play_boundaries
23
+ from audio import transcribe_clip
24
+ from config import (
25
+ SUPPORTED_VIDEO_FORMATS, DEFAULT_CLASSIFICATION_FILE, DEFAULT_TRANSCRIPT_FILE,
26
+ DEFAULT_PLAY_ANALYSIS_FILE, VIDEO_SAVE_INTERVAL, AUDIO_SAVE_INTERVAL
27
+ )
28
 
29
+
30
+ def main(input_dir: str = "data",
31
+ classification_file: str = DEFAULT_CLASSIFICATION_FILE,
32
+ transcript_file: str = DEFAULT_TRANSCRIPT_FILE,
33
+ play_analysis_file: str = DEFAULT_PLAY_ANALYSIS_FILE,
34
+ skip_audio: bool = False,
35
+ max_clips: Optional[int] = None) -> Dict[str, Any]:
36
+ """
37
+ Main processing function for NFL play detection pipeline.
38
+
39
+ Args:
40
+ input_dir: Directory containing video clips
41
+ classification_file: Output file for video classifications
42
+ transcript_file: Output file for audio transcriptions
43
+ play_analysis_file: Output file for play analysis results
44
+ skip_audio: If True, skip audio transcription (Phase 2)
45
+ max_clips: Limit processing to first N clips (for testing)
46
+
47
+ Returns:
48
+ Dictionary with processing statistics and results
49
+ """
50
+ # Find video files using supported formats
51
  clips = []
52
+ for pattern in SUPPORTED_VIDEO_FORMATS:
53
+ clips.extend(glob.glob(os.path.join(input_dir, pattern)))
54
  clips = sorted(clips)
55
  if not clips:
56
  print(f"No clips found in '{input_dir}'.")
 
119
  else:
120
  print(f" [WARN] No classification scores (skipped or error)")
121
 
122
+ # Write incremental results after every N clips or at the end
123
+ if i % VIDEO_SAVE_INTERVAL == 0 or i == len(clips):
124
  try:
125
  with open(classification_file, 'w') as f:
126
  json.dump(classification_results, f, indent=2)
 
202
  print(f" [ERROR] Failed to transcribe: {e}")
203
  transcript_results[clip_name] = ""
204
 
205
+ # Write incremental results after every N clips or at the end
206
+ if i % AUDIO_SAVE_INTERVAL == 0 or i == len(clips):
207
  try:
208
  with open(transcript_file, 'w') as f:
209
  json.dump(transcript_results, f, indent=2)
 
246
  parser.add_argument('--video-only', action='store_true', help='Process only video classification (85%% faster)')
247
  parser.add_argument('--audio-only', action='store_true', help='Process only audio transcription (requires existing classification.json)')
248
  parser.add_argument('--max-clips', type=int, help='Limit processing to first N clips (for testing)')
249
+ parser.add_argument('--classification-file', default=DEFAULT_CLASSIFICATION_FILE, help='Video classification output file')
250
+ parser.add_argument('--transcript-file', default=DEFAULT_TRANSCRIPT_FILE, help='Audio transcript output file')
251
+ parser.add_argument('--play-analysis-file', default=DEFAULT_PLAY_ANALYSIS_FILE, help='Play analysis output file')
252
 
253
  args = parser.parse_args()
254
 
transcripts.json CHANGED
@@ -1,3 +1,79 @@
1
  {
2
- "segment_001.mov": "I can tell you that Lamar Jackson right now is"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  }
 
1
  {
2
+ "segment_001.mov": "I can tell you that Lamar Jackson right now is",
3
+ "segment_002.mov": "is the sixth best quarterback in the NFL.",
4
+ "segment_003.mov": "Well and that's just pure",
5
+ "segment_004.mov": "It's totally based off of passing, right.",
6
+ "segment_005.mov": "You got to consider what he is.",
7
+ "segment_006.mov": "two time MVP that uses his",
8
+ "segment_007.mov": "legs as well as he uses his arm.",
9
+ "segment_008.mov": "They found a great combination.",
10
+ "segment_009.mov": "with him Derek Henry but.",
11
+ "segment_010.mov": "If they're going to stack the box, if the Bengals feel",
12
+ "segment_011.mov": "I feel like they're going to have to put eight in the box all day.",
13
+ "segment_012.mov": "to stop this run game. Don't be surprised.",
14
+ "segment_013.mov": "that Lamar has a big day through the.",
15
+ "segment_014.mov": "here.",
16
+ "segment_015.mov": "will be the I for",
17
+ "segment_016.mov": "Now they switch. That was about six hundred.",
18
+ "segment_017.mov": "pounds of running",
19
+ "segment_018.mov": "That very motion is flower",
20
+ "segment_019.mov": "It goes to flowers.",
21
+ "segment_020.mov": "brought by likely and a block",
22
+ "segment_021.mov": "Back by Kohler and out of bounds goes.",
23
+ "segment_022.mov": "flowers with a jet swing.",
24
+ "segment_023.mov": "and on the play picks up nine",
25
+ "segment_024.mov": "9 to the 39.",
26
+ "segment_025.mov": "on that offensive line.",
27
+ "segment_026.mov": "Donnie Stanley has been terrific at the left.",
28
+ "segment_027.mov": "tackle. He's healthy. He really has been.",
29
+ "segment_028.mov": "There's been some shuffling at the guards as you see that.",
30
+ "segment_029.mov": "He moved around in the rookie.",
31
+ "segment_030.mov": "We're on the side. Patrick Ricard.",
32
+ "segment_031.mov": "He gets overlooked a lot.",
33
+ "segment_032.mov": "But he does everything for this team.",
34
+ "segment_033.mov": "He's he's basically like an extra line.",
35
+ "segment_034.mov": "extra tight end out there leading the",
36
+ "segment_035.mov": "holes for this run game and a great job.",
37
+ "segment_036.mov": "with Todd Monkin last week striking a rough",
38
+ "segment_037.mov": "The defensive coordinator second down one.",
39
+ "segment_038.mov": "Down with the dives",
40
+ "segment_039.mov": "Very good.",
41
+ "segment_040.mov": "And a gain of four is.",
42
+ "segment_041.mov": "He's out to the 43.",
43
+ "segment_042.mov": "And a first down.",
44
+ "segment_043.mov": "Here's a look at Von Bell who makes that stuff.",
45
+ "segment_044.mov": "and on that defensive line.",
46
+ "segment_045.mov": "They get back Chris Jenkins",
47
+ "segment_046.mov": "and Hill. Hendrickson is healthy.",
48
+ "segment_047.mov": "and covered on the other side.",
49
+ "segment_048.mov": "The defense has been picked up.",
50
+ "segment_049.mov": "on some this year but they are getting healthy as you.",
51
+ "segment_050.mov": "So they get back McKinley Jackson today.",
52
+ "segment_051.mov": "He'll be right back, Myles Murphy, BJ Hill missed the last.",
53
+ "segment_052.mov": "couple of games it's important to.",
54
+ "segment_053.mov": "to have those guys up front. Henry.",
55
+ "segment_054.mov": "Trying to follow a block.",
56
+ "segment_055.mov": "Nice tackle made by Hubbard.",
57
+ "segment_056.mov": "with the forty five and a gain of two.",
58
+ "segment_057.mov": "It'll be second down and eight.",
59
+ "segment_058.mov": "Well, it's going to be important all day long.",
60
+ "segment_059.mov": "strong to tackle low you've got to be able.",
61
+ "segment_060.mov": "to take the legs out of Derrick",
62
+ "segment_061.mov": "for Kenry if you go up too high you know.",
63
+ "segment_062.mov": "that stiff arm and gets in the open field to score.",
64
+ "segment_063.mov": "speed so excellent job there.",
65
+ "segment_064.mov": "by Hill and Hubbard to bring him down.",
66
+ "segment_065.mov": "Thank you.",
67
+ "segment_066.mov": "Max Hill with the hit. Mike Hilton is out.",
68
+ "segment_067.mov": "today knee injury didn't practice",
69
+ "segment_068.mov": "this all week.",
70
+ "segment_069.mov": "A second year defensive backup",
71
+ "segment_070.mov": "Michigan taking his place.",
72
+ "segment_071.mov": "In the first possession of the game",
73
+ "segment_072.mov": "second down and eight",
74
+ "segment_073.mov": "That record is on the move.",
75
+ "segment_074.mov": "Jackson to the air.",
76
+ "segment_075.mov": "swings it up field",
77
+ "segment_076.mov": "Miller makes the grab.",
78
+ "segment_077.mov": ""
79
  }
video.py ADDED
@@ -0,0 +1,398 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Video Classification and NFL Play Analysis Module.
3
+
4
+ This module handles:
5
+ 1. X3D-based video classification using Kinetics-400 pretrained models
6
+ 2. NFL-specific play state analysis (play_active, play_action, non_play)
7
+ 3. Play boundary detection across video sequences
8
+ 4. Video preprocessing and frame extraction
9
+
10
+ Key Components:
11
+ - VideoClassifier: Main class for video classification
12
+ - PlayAnalyzer: NFL-specific play state detection
13
+ - BoundaryDetector: Sequence analysis for play start/end detection
14
+ """
15
+
16
+ import os
17
+ import json
18
+ import urllib.request
19
+ from typing import List, Tuple, Optional, Dict, Any
20
+
21
+ import torch
22
+ import numpy as np
23
+ from pytorchvideo.data.encoded_video import EncodedVideo
24
+
25
+ from config import (
26
+ VIDEO_MODEL_NAME, DEVICE, VIDEO_CLIP_DURATION, VIDEO_NUM_SAMPLES, VIDEO_SIZE,
27
+ KINETICS_LABELS_URL, KINETICS_LABELS_PATH, VIDEO_MEAN, VIDEO_STD,
28
+ PLAY_CONFIDENCE_THRESHOLD, PLAY_BOUNDARY_WINDOW_SIZE,
29
+ PLAY_START_INDICATORS, PLAY_ACTION_INDICATORS, NON_PLAY_INDICATORS,
30
+ ENABLE_DEBUG_PRINTS, ENABLE_FRAME_SHAPE_DEBUG
31
+ )
32
+
33
+
34
+ class VideoClassifier:
35
+ """
36
+ X3D-based video classifier for action recognition.
37
+
38
+ Uses PyTorchVideo's pretrained X3D models trained on Kinetics-400 dataset.
39
+ Supports multiple model sizes (xs, s, m, l) with different speed/accuracy tradeoffs.
40
+ """
41
+
42
+ def __init__(self, model_name: str = VIDEO_MODEL_NAME, device: torch.device = DEVICE):
43
+ """
44
+ Initialize the video classifier.
45
+
46
+ Args:
47
+ model_name: X3D model variant (x3d_xs, x3d_s, x3d_m, x3d_l)
48
+ device: PyTorch device for inference
49
+ """
50
+ self.model_name = model_name
51
+ self.device = device
52
+ self.model = None
53
+ self.labels = None
54
+
55
+ # Initialize model and labels
56
+ self._load_model()
57
+ self._load_kinetics_labels()
58
+
59
+ def _load_model(self) -> None:
60
+ """Load and prepare the X3D model for inference."""
61
+ if ENABLE_DEBUG_PRINTS:
62
+ print(f"Loading X3D model: {self.model_name}")
63
+
64
+ self.model = torch.hub.load(
65
+ "facebookresearch/pytorchvideo",
66
+ self.model_name,
67
+ pretrained=True
68
+ ).to(self.device).eval()
69
+
70
+ if ENABLE_DEBUG_PRINTS:
71
+ print(f"Model loaded successfully on {self.device}")
72
+
73
+ def _load_kinetics_labels(self) -> None:
74
+ """Download and load Kinetics-400 class labels."""
75
+ # Download labels if not present
76
+ if not os.path.exists(KINETICS_LABELS_PATH):
77
+ if ENABLE_DEBUG_PRINTS:
78
+ print("Downloading Kinetics-400 labels...")
79
+ urllib.request.urlretrieve(KINETICS_LABELS_URL, KINETICS_LABELS_PATH)
80
+
81
+ # Load and parse labels
82
+ with open(KINETICS_LABELS_PATH, "r") as f:
83
+ raw_labels = json.load(f)
84
+
85
+ # Handle different label formats
86
+ if isinstance(raw_labels, list):
87
+ self.labels = {i: raw_labels[i] for i in range(len(raw_labels))}
88
+ elif isinstance(raw_labels, dict):
89
+ # Check if keys are numeric strings
90
+ if all(k.isdigit() for k in raw_labels.keys()):
91
+ self.labels = {int(k): v for k, v in raw_labels.items()}
92
+ else:
93
+ # Assume values are indices, invert the mapping
94
+ self.labels = {}
95
+ for k, v in raw_labels.items():
96
+ try:
97
+ self.labels[int(v)] = k
98
+ except (ValueError, TypeError):
99
+ continue
100
+ else:
101
+ raise ValueError(f"Unexpected label format in {KINETICS_LABELS_PATH}")
102
+
103
+ if ENABLE_DEBUG_PRINTS:
104
+ print(f"Loaded {len(self.labels)} Kinetics-400 labels")
105
+
106
+ def preprocess_video(self, frames: torch.Tensor,
107
+ num_samples: int = VIDEO_NUM_SAMPLES,
108
+ size: int = VIDEO_SIZE) -> torch.Tensor:
109
+ """
110
+ Preprocess video frames for X3D model input.
111
+
112
+ Args:
113
+ frames: Video tensor of shape (C, T, H, W)
114
+ num_samples: Number of frames to sample
115
+ size: Spatial size for center crop
116
+
117
+ Returns:
118
+ Preprocessed tensor ready for model input
119
+ """
120
+ C, T, H, W = frames.shape
121
+
122
+ # Convert to float and normalize to [0, 1]
123
+ video = frames.permute(1, 0, 2, 3).float() / 255.0
124
+
125
+ # Temporal sampling - uniformly sample frames
126
+ indices = torch.linspace(0, T - 1, num_samples).long()
127
+ clip = video[indices]
128
+
129
+ # Spatial center crop
130
+ top = max((H - size) // 2, 0)
131
+ left = max((W - size) // 2, 0)
132
+ clip = clip[:, :, top:top+size, left:left+size]
133
+
134
+ # Rearrange dimensions and add batch dimension: (N, C, T, H, W)
135
+ clip = clip.permute(1, 0, 2, 3).unsqueeze(0)
136
+
137
+ # Apply ImageNet normalization
138
+ mean = torch.tensor(VIDEO_MEAN, device=self.device).view(1, 3, 1, 1, 1)
139
+ std = torch.tensor(VIDEO_STD, device=self.device).view(1, 3, 1, 1, 1)
140
+ clip = (clip - mean) / std
141
+
142
+ return clip
143
+
144
+ def classify_clip(self, video_path: str, top_k: int = 5) -> List[Tuple[str, float]]:
145
+ """
146
+ Classify a single video clip and return top-k predictions.
147
+
148
+ Args:
149
+ video_path: Path to video file
150
+ top_k: Number of top predictions to return
151
+
152
+ Returns:
153
+ List of (label, confidence) tuples sorted by confidence
154
+ """
155
+ try:
156
+ # Load video
157
+ video = EncodedVideo.from_path(video_path)
158
+ clip_data = video.get_clip(0, VIDEO_CLIP_DURATION)
159
+ frames = clip_data["video"]
160
+
161
+ if frames is None:
162
+ if ENABLE_DEBUG_PRINTS:
163
+ print(f"[ERROR] Failed to load video frames from {video_path}")
164
+ return []
165
+
166
+ if ENABLE_FRAME_SHAPE_DEBUG:
167
+ print(f"[DEBUG] Loaded video frames shape: {frames.shape}")
168
+
169
+ # Preprocess and run inference
170
+ input_tensor = self.preprocess_video(frames).to(self.device)
171
+
172
+ with torch.no_grad():
173
+ logits = self.model(input_tensor)
174
+ probabilities = torch.softmax(logits, dim=1)[0]
175
+
176
+ # Get top-k predictions
177
+ top_k_probs, top_k_indices = torch.topk(probabilities, k=top_k)
178
+
179
+ results = []
180
+ for idx_tensor, prob in zip(top_k_indices, top_k_probs):
181
+ idx = idx_tensor.item()
182
+ label = self.labels.get(idx, f"Class_{idx}")
183
+ results.append((label, float(prob)))
184
+
185
+ return results
186
+
187
+ except Exception as e:
188
+ if ENABLE_DEBUG_PRINTS:
189
+ print(f"[ERROR] Failed to process {video_path}: {e}")
190
+ return []
191
+
192
+
193
+ class PlayAnalyzer:
194
+ """
195
+ NFL-specific play state analyzer.
196
+
197
+ Analyzes video classification results to determine:
198
+ - play_active: Active football plays (passing, kicking)
199
+ - play_action: Football-related actions (catching, throwing)
200
+ - non_play: Non-game activities (applauding, commentary)
201
+ - unknown: Low confidence or ambiguous clips
202
+ """
203
+
204
+ def __init__(self, confidence_threshold: float = PLAY_CONFIDENCE_THRESHOLD):
205
+ """
206
+ Initialize play analyzer.
207
+
208
+ Args:
209
+ confidence_threshold: Minimum confidence for state classification
210
+ """
211
+ self.confidence_threshold = confidence_threshold
212
+ self.play_start_indicators = PLAY_START_INDICATORS
213
+ self.play_action_indicators = PLAY_ACTION_INDICATORS
214
+ self.non_play_indicators = NON_PLAY_INDICATORS
215
+
216
+ def analyze_play_state(self, predictions: List[Tuple[str, float]]) -> Tuple[str, float]:
217
+ """
218
+ Analyze video classification predictions to determine play state.
219
+
220
+ Args:
221
+ predictions: List of (label, confidence) tuples from video classifier
222
+
223
+ Returns:
224
+ Tuple of (play_state, confidence_score)
225
+ """
226
+ if not predictions:
227
+ return "unknown", 0.0
228
+
229
+ # Calculate weighted scores for each play state
230
+ play_start_score = 0.0
231
+ play_action_score = 0.0
232
+ non_play_score = 0.0
233
+
234
+ for label, confidence in predictions:
235
+ # Clean label for matching
236
+ clean_label = label.replace('"', '').lower()
237
+
238
+ # Check against different indicator categories
239
+ if self._matches_indicators(clean_label, self.play_start_indicators):
240
+ play_start_score += confidence * 2.0 # Weight play-specific actions higher
241
+ elif self._matches_indicators(clean_label, self.play_action_indicators):
242
+ play_action_score += confidence
243
+ elif self._matches_indicators(clean_label, self.non_play_indicators):
244
+ non_play_score += confidence
245
+
246
+ # Determine final play state
247
+ max_score = max(play_start_score, play_action_score, non_play_score)
248
+
249
+ if max_score < self.confidence_threshold:
250
+ return "unknown", max_score
251
+ elif play_start_score == max_score:
252
+ return "play_active", play_start_score
253
+ elif play_action_score == max_score:
254
+ return "play_action", play_action_score
255
+ else:
256
+ return "non_play", non_play_score
257
+
258
+ def _matches_indicators(self, label: str, indicators: List[str]) -> bool:
259
+ """Check if label matches any indicator in the list."""
260
+ return any(indicator.lower() in label for indicator in indicators)
261
+
262
+
263
+ class BoundaryDetector:
264
+ """
265
+ Play boundary detection for video sequences.
266
+
267
+ Analyzes sequences of play states to detect:
268
+ - Play start points (non_play -> play_active transitions)
269
+ - Play end points (play_active -> non_play transitions)
270
+ """
271
+
272
+ def __init__(self, window_size: int = PLAY_BOUNDARY_WINDOW_SIZE):
273
+ """
274
+ Initialize boundary detector.
275
+
276
+ Args:
277
+ window_size: Window size for sequence analysis
278
+ """
279
+ self.window_size = window_size
280
+ self.play_analyzer = PlayAnalyzer()
281
+
282
+ def detect_boundaries(self, clip_results: List[List[Tuple[str, float]]]) -> List[Tuple[str, int, float]]:
283
+ """
284
+ Detect play boundaries across a sequence of video clips.
285
+
286
+ Args:
287
+ clip_results: List of classification results for each clip
288
+
289
+ Returns:
290
+ List of (boundary_type, clip_index, confidence) tuples
291
+ """
292
+ if len(clip_results) < self.window_size:
293
+ return []
294
+
295
+ # Analyze play state for each clip
296
+ play_states = []
297
+ for results in clip_results:
298
+ state, confidence = self.play_analyzer.analyze_play_state(results)
299
+ play_states.append((state, confidence))
300
+
301
+ boundaries = []
302
+
303
+ # Look for state transitions
304
+ for i in range(len(play_states) - 1):
305
+ current_state, current_conf = play_states[i]
306
+ next_state, next_conf = play_states[i + 1]
307
+
308
+ # Detect play start: non_play/unknown -> play_active/play_action
309
+ if (current_state in ["non_play", "unknown"] and
310
+ next_state in ["play_active", "play_action"] and
311
+ next_conf > self.play_analyzer.confidence_threshold):
312
+ boundaries.append(("play_start", i + 1, next_conf))
313
+
314
+ # Detect play end: play_active/play_action -> non_play/unknown
315
+ if (current_state in ["play_active", "play_action"] and
316
+ next_state in ["non_play", "unknown"] and
317
+ current_conf > self.play_analyzer.confidence_threshold):
318
+ boundaries.append(("play_end", i, current_conf))
319
+
320
+ return boundaries
321
+
322
+
323
+ # ============================================================================
324
+ # CONVENIENCE FUNCTIONS FOR BACKWARD COMPATIBILITY
325
+ # ============================================================================
326
+
327
+ # Global instances for backward compatibility
328
+ _video_classifier = None
329
+ _play_analyzer = None
330
+ _boundary_detector = None
331
+
332
+ def get_video_classifier() -> VideoClassifier:
333
+ """Get global video classifier instance (lazy initialization)."""
334
+ global _video_classifier
335
+ if _video_classifier is None:
336
+ _video_classifier = VideoClassifier()
337
+ return _video_classifier
338
+
339
+ def get_play_analyzer() -> PlayAnalyzer:
340
+ """Get global play analyzer instance (lazy initialization)."""
341
+ global _play_analyzer
342
+ if _play_analyzer is None:
343
+ _play_analyzer = PlayAnalyzer()
344
+ return _play_analyzer
345
+
346
+ def get_boundary_detector() -> BoundaryDetector:
347
+ """Get global boundary detector instance (lazy initialization)."""
348
+ global _boundary_detector
349
+ if _boundary_detector is None:
350
+ _boundary_detector = BoundaryDetector()
351
+ return _boundary_detector
352
+
353
+ def predict_clip(path: str) -> List[Tuple[str, float]]:
354
+ """
355
+ Backward compatibility function for video classification.
356
+
357
+ Args:
358
+ path: Path to video file
359
+
360
+ Returns:
361
+ List of (label, confidence) tuples
362
+ """
363
+ classifier = get_video_classifier()
364
+ results = classifier.classify_clip(path)
365
+
366
+ # Print play state analysis for compatibility
367
+ if results:
368
+ analyzer = get_play_analyzer()
369
+ play_state, confidence = analyzer.analyze_play_state(results)
370
+ print(f"[PLAY STATE] {play_state} (confidence: {confidence:.3f})")
371
+
372
+ return results
373
+
374
+ def analyze_play_state(predictions: List[Tuple[str, float]]) -> Tuple[str, float]:
375
+ """
376
+ Backward compatibility function for play state analysis.
377
+
378
+ Args:
379
+ predictions: Classification results
380
+
381
+ Returns:
382
+ Tuple of (play_state, confidence)
383
+ """
384
+ analyzer = get_play_analyzer()
385
+ return analyzer.analyze_play_state(predictions)
386
+
387
+ def detect_play_boundaries(clip_results: List[List[Tuple[str, float]]]) -> List[Tuple[str, int, float]]:
388
+ """
389
+ Backward compatibility function for boundary detection.
390
+
391
+ Args:
392
+ clip_results: List of classification results for each clip
393
+
394
+ Returns:
395
+ List of boundary detections
396
+ """
397
+ detector = get_boundary_detector()
398
+ return detector.detect_boundaries(clip_results)