hf-video-scoring / yolo_processor.py
Jerry Hill
adding yolo to pipeline
5988ab2
"""
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)