File size: 12,040 Bytes
5988ab2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
"""
YOLO11 Football Object Detection and Video Preprocessing Module.

This module integrates YOLOv11-based object detection into the NFL play detection pipeline.
It processes raw video clips to add bounding box annotations for football players, balls,
and other sports objects before video classification.

Key Components:
- YOLOProcessor: Main class for YOLO-based video preprocessing
- FootballDetector: Football-specific object detection functionality
- VideoAnnotator: Video annotation and output management

Integration Flow:
1. Raw clips in /segments/ are processed by YOLO11
2. Annotated clips are saved to /segments/yolo/
3. Video classification uses annotated clips
4. Audio transcription continues to use original clips
"""

import os
import shutil
import tempfile
import subprocess
import glob
from typing import Optional, Tuple, List
from pathlib import Path

from ultralytics import YOLO
from huggingface_hub import hf_hub_download

from config import (
    ENABLE_DEBUG_PRINTS, DEFAULT_SEGMENTS_DIR, DEFAULT_YOLO_OUTPUT_DIR,
    DEFAULT_TEMP_DIR, HUGGINGFACE_CACHE_DIR
)


class YOLOProcessor:
    """
    YOLOv11-based video processor for football object detection.
    
    Downloads and manages YOLOv11 models, processes video clips to add
    object detection annotations, and manages output directories.
    """
    
    def __init__(self, model_size: str = "nano", confidence_threshold: float = 0.25):
        """
        Initialize YOLO processor.
        
        Args:
            model_size: YOLO model size (nano, small, medium, large, xlarge)
            confidence_threshold: Detection confidence threshold
        """
        self.model_size = model_size
        self.confidence_threshold = confidence_threshold
        self.model = None
        self._load_model()
    
    def _load_model(self) -> None:
        """Download and load YOLOv11 model."""
        model_filename = f"yolo11{self.model_size[0]}.pt"  # nano -> yolo11n.pt
        
        if ENABLE_DEBUG_PRINTS:
            print(f"Loading YOLOv11 model: {model_filename}")
        
        try:
            # Set cache directory if configured
            download_kwargs = {
                "repo_id": "Ultralytics/YOLO11",
                "filename": model_filename,
                "repo_type": "model"
            }
            if HUGGINGFACE_CACHE_DIR:
                download_kwargs["cache_dir"] = HUGGINGFACE_CACHE_DIR
            
            model_path = hf_hub_download(**download_kwargs)
            self.model = YOLO(model_path)
            
            if ENABLE_DEBUG_PRINTS:
                print(f"YOLOv11 model loaded successfully from {model_path}")
                
        except Exception as e:
            print(f"[ERROR] Failed to load YOLOv11 model: {e}")
            raise
    
    def process_clip(self, input_path: str, output_dir: str) -> Optional[str]:
        """
        Process a single video clip with YOLO object detection.
        
        Args:
            input_path: Path to input video clip
            output_dir: Directory for output annotated clip
            
        Returns:
            Path to annotated clip with audio, or None if processing failed
        """
        if not os.path.exists(input_path):
            print(f"[ERROR] Input video not found: {input_path}")
            return None
        
        # Create output directory if it doesn't exist
        os.makedirs(output_dir, exist_ok=True)
        
        # Create temporary directory for processing
        temp_dir = DEFAULT_TEMP_DIR if DEFAULT_TEMP_DIR else None
        with tempfile.TemporaryDirectory(dir=temp_dir) as tmp_dir:
            try:
                return self._process_in_temp_dir(input_path, output_dir, tmp_dir)
            except Exception as e:
                print(f"[ERROR] Failed to process {input_path}: {e}")
                return None
    
    def _process_in_temp_dir(self, input_path: str, output_dir: str, tmp_dir: str) -> str:
        """Process video in temporary directory and return final output path."""
        base_name = os.path.basename(input_path)
        name_without_ext = os.path.splitext(base_name)[0]
        _, ext = os.path.splitext(base_name)
        
        # Stage input file in temp directory
        temp_input = os.path.join(tmp_dir, base_name)
        shutil.copy(input_path, temp_input)
        
        # Run YOLO inference
        if ENABLE_DEBUG_PRINTS:
            print(f"Running YOLO inference on {base_name}")
        
        self.model.predict(
            source=temp_input,
            imgsz=640,
            conf=self.confidence_threshold,
            save=True,
            project=tmp_dir,
            name="yolo_out",
            exist_ok=True,
            verbose=False  # Reduce YOLO output noise
        )
        
        # Find the annotated output
        yolo_out_dir = os.path.join(tmp_dir, "yolo_out")
        annotated_files = glob.glob(os.path.join(yolo_out_dir, "*"))
        
        if not annotated_files:
            raise FileNotFoundError(f"No YOLO output found in {yolo_out_dir}")
        
        # Get the largest file (should be the annotated video)
        annotated_video = max(annotated_files, key=lambda f: os.path.getsize(f))
        
        # Create final output path
        final_output = os.path.join(output_dir, f"{name_without_ext}_yolo{ext}")
        
        # Mux original audio with annotated video using FFmpeg
        self._mux_audio(annotated_video, input_path, final_output)
        
        if ENABLE_DEBUG_PRINTS:
            print(f"YOLO processing complete: {final_output}")
        
        return final_output
    
    def _mux_audio(self, video_path: str, audio_source: str, output_path: str) -> None:
        """
        Combine annotated video with original audio using FFmpeg.
        
        Args:
            video_path: Path to annotated video (without audio)
            audio_source: Path to original video (with audio)
            output_path: Path for final output with both video and audio
        """
        cmd = [
            "ffmpeg", "-y",  # Overwrite output file
            "-i", video_path,     # Annotated video input
            "-i", audio_source,   # Original audio source
            "-map", "0:v:0",      # Map video from first input
            "-map", "1:a:0",      # Map audio from second input
            "-c:v", "copy",       # Copy video without re-encoding
            "-c:a", "copy",       # Copy audio without re-encoding
            output_path
        ]
        
        try:
            subprocess.run(
                cmd, 
                check=True, 
                stdout=subprocess.DEVNULL, 
                stderr=subprocess.DEVNULL
            )
        except subprocess.CalledProcessError as e:
            raise RuntimeError(f"FFmpeg audio muxing failed: {e}")


class FootballDetector:
    """
    High-level interface for football-specific object detection pipeline.
    
    Manages the integration between raw video clips and the NFL play detection
    system by preprocessing clips with YOLO object detection.
    """
    
    def __init__(self, 
                 segments_dir: str = DEFAULT_SEGMENTS_DIR,
                 yolo_output_dir: str = DEFAULT_YOLO_OUTPUT_DIR,
                 model_size: str = "nano",
                 confidence: float = 0.25):
        """
        Initialize football detector.
        
        Args:
            segments_dir: Directory containing raw video segments
            yolo_output_dir: Directory for YOLO-processed clips
            model_size: YOLO model size for detection
            confidence: Detection confidence threshold
        """
        self.segments_dir = segments_dir
        self.yolo_output_dir = yolo_output_dir
        self.processor = YOLOProcessor(model_size=model_size, confidence_threshold=confidence)
        
        # Ensure output directory exists
        os.makedirs(self.yolo_output_dir, exist_ok=True)
    
    def process_all_segments(self, max_clips: Optional[int] = None) -> List[str]:
        """
        Process all video segments in the segments directory.
        
        Args:
            max_clips: Maximum number of clips to process (for testing)
            
        Returns:
            List of paths to processed YOLO clips
        """
        # Find all video files in segments directory
        video_patterns = ["*.mov", "*.mp4"]
        video_files = []
        
        for pattern in video_patterns:
            video_files.extend(glob.glob(os.path.join(self.segments_dir, pattern)))
        
        video_files = sorted(video_files)
        
        if max_clips:
            video_files = video_files[:max_clips]
        
        if not video_files:
            print(f"No video files found in {self.segments_dir}")
            return []
        
        print(f"🎯 YOLO PREPROCESSING: Processing {len(video_files)} clips")
        print("=" * 60)
        
        processed_clips = []
        
        for i, video_path in enumerate(video_files, 1):
            clip_name = os.path.basename(video_path)
            print(f"[{i}/{len(video_files)}] Processing: {clip_name}")
            
            # Check if already processed
            name_without_ext = os.path.splitext(clip_name)[0]
            _, ext = os.path.splitext(clip_name)
            expected_output = os.path.join(self.yolo_output_dir, f"{name_without_ext}_yolo{ext}")
            
            if os.path.exists(expected_output):
                print(f"  ✓ Already processed: {expected_output}")
                processed_clips.append(expected_output)
                continue
            
            # Process with YOLO
            output_path = self.processor.process_clip(video_path, self.yolo_output_dir)
            
            if output_path:
                processed_clips.append(output_path)
                print(f"  ✓ YOLO annotations added: {os.path.basename(output_path)}")
            else:
                print(f"  ✗ Processing failed for {clip_name}")
        
        print(f"\n🎯 YOLO PREPROCESSING COMPLETE")
        print(f"  Processed clips: {len(processed_clips)}")
        print(f"  Output directory: {self.yolo_output_dir}")
        
        return processed_clips
    
    def get_processed_clip_path(self, original_clip_path: str) -> Optional[str]:
        """
        Get the path to the YOLO-processed version of a clip.
        
        Args:
            original_clip_path: Path to original clip
            
        Returns:
            Path to YOLO-processed clip, or None if not found
        """
        clip_name = os.path.basename(original_clip_path)
        name_without_ext = os.path.splitext(clip_name)[0]
        _, ext = os.path.splitext(clip_name)
        
        yolo_clip_path = os.path.join(self.yolo_output_dir, f"{name_without_ext}_yolo{ext}")
        
        return yolo_clip_path if os.path.exists(yolo_clip_path) else None


# ============================================================================
# CONVENIENCE FUNCTIONS
# ============================================================================

def preprocess_segments_with_yolo(segments_dir: str = DEFAULT_SEGMENTS_DIR, 
                                 max_clips: Optional[int] = None) -> List[str]:
    """
    Convenience function to preprocess all segments with YOLO detection.
    
    Args:
        segments_dir: Directory containing video segments
        max_clips: Maximum clips to process (for testing)
        
    Returns:
        List of paths to YOLO-processed clips
    """
    detector = FootballDetector(segments_dir=segments_dir)
    return detector.process_all_segments(max_clips=max_clips)

def get_yolo_clip_for_original(original_path: str) -> Optional[str]:
    """
    Get YOLO-processed version of an original clip.
    
    Args:
        original_path: Path to original clip
        
    Returns:
        Path to YOLO-processed clip or None
    """
    detector = FootballDetector()
    return detector.get_processed_clip_path(original_path)