Spaces:
Configuration error
Configuration error
Delete video_processor_py.py
Browse files- video_processor_py.py +0 -289
video_processor_py.py
DELETED
|
@@ -1,289 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
core/video_processor.py
|
| 3 |
-
=======================
|
| 4 |
-
Complete video processing pipeline:
|
| 5 |
-
1. Validate & copy video to temp session folder
|
| 6 |
-
2. Extract audio track (WAV, mono, 16kHz) via FFmpeg
|
| 7 |
-
3. Extract representative frames (adaptive interval)
|
| 8 |
-
4. Return structured VideoMeta object
|
| 9 |
-
|
| 10 |
-
Design choices:
|
| 11 |
-
- ffmpeg-python for reliable cross-platform FFmpeg wrapping
|
| 12 |
-
- Adaptive frame sampling: shorter videos → denser frames
|
| 13 |
-
- Scene-change detection via simple pixel-diff to avoid redundant frames
|
| 14 |
-
- All output goes to a per-session temp directory
|
| 15 |
-
- moviepy used ONLY for duration probe (lighter than loading full video)
|
| 16 |
-
"""
|
| 17 |
-
|
| 18 |
-
from __future__ import annotations
|
| 19 |
-
|
| 20 |
-
import os
|
| 21 |
-
import shutil
|
| 22 |
-
import time
|
| 23 |
-
import hashlib
|
| 24 |
-
import threading
|
| 25 |
-
from dataclasses import dataclass, field
|
| 26 |
-
from pathlib import Path
|
| 27 |
-
from typing import List, Optional, Callable, Tuple
|
| 28 |
-
|
| 29 |
-
import cv2
|
| 30 |
-
import ffmpeg
|
| 31 |
-
import numpy as np
|
| 32 |
-
from loguru import logger
|
| 33 |
-
from PIL import Image
|
| 34 |
-
|
| 35 |
-
from utils.session_manager import SessionManager
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
# ── Result types ──────────────────────────────────────────────────────────────
|
| 39 |
-
|
| 40 |
-
@dataclass
|
| 41 |
-
class FrameInfo:
|
| 42 |
-
path: str
|
| 43 |
-
timestamp_sec: float
|
| 44 |
-
index: int
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
@dataclass
|
| 48 |
-
class VideoMeta:
|
| 49 |
-
session_id: str
|
| 50 |
-
original_filename: str
|
| 51 |
-
video_path: str # path inside temp dir
|
| 52 |
-
audio_path: str # extracted WAV
|
| 53 |
-
frames: List[FrameInfo] # sampled frames
|
| 54 |
-
duration_sec: float
|
| 55 |
-
fps: float
|
| 56 |
-
width: int
|
| 57 |
-
height: int
|
| 58 |
-
frame_dir: str
|
| 59 |
-
processing_time_sec: float = 0.0
|
| 60 |
-
file_hash: str = ""
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
# ── Main processor ────────────────────────────────────────────────────────────
|
| 64 |
-
|
| 65 |
-
class VideoProcessor:
|
| 66 |
-
|
| 67 |
-
# Adaptive sampling config
|
| 68 |
-
FRAME_INTERVAL_SHORT = 3 # <10 min → 1 frame every 3s
|
| 69 |
-
FRAME_INTERVAL_MEDIUM = 6 # 10-30min → 1 frame every 6s
|
| 70 |
-
FRAME_INTERVAL_LONG = 10 # >30min → 1 frame every 10s
|
| 71 |
-
MAX_FRAMES = 300 # hard cap to keep RAM sane
|
| 72 |
-
SCENE_DIFF_THRESHOLD = 30 # mean pixel diff to trigger scene capture
|
| 73 |
-
|
| 74 |
-
def __init__(self):
|
| 75 |
-
self._lock = threading.Lock()
|
| 76 |
-
|
| 77 |
-
# ── Public entry point ────────────────────────────────────────────────────
|
| 78 |
-
def process(
|
| 79 |
-
self,
|
| 80 |
-
uploaded_path: str,
|
| 81 |
-
session_id: str,
|
| 82 |
-
progress_cb: Optional[Callable[[str, float], None]] = None,
|
| 83 |
-
) -> VideoMeta:
|
| 84 |
-
"""
|
| 85 |
-
Full pipeline. progress_cb(message, 0.0-1.0) for UI updates.
|
| 86 |
-
Raises ValueError on bad input, RuntimeError on processing failure.
|
| 87 |
-
"""
|
| 88 |
-
t0 = time.time()
|
| 89 |
-
p = progress_cb or (lambda msg, pct: None)
|
| 90 |
-
|
| 91 |
-
p("Validating video…", 0.02)
|
| 92 |
-
src = Path(uploaded_path)
|
| 93 |
-
if not src.exists():
|
| 94 |
-
raise ValueError(f"File not found: {uploaded_path}")
|
| 95 |
-
|
| 96 |
-
suffix = src.suffix.lower()
|
| 97 |
-
allowed = {".mp4", ".mkv", ".avi", ".mov", ".webm", ".flv", ".wmv", ".m4v"}
|
| 98 |
-
if suffix not in allowed:
|
| 99 |
-
raise ValueError(f"Unsupported format: {suffix}")
|
| 100 |
-
|
| 101 |
-
# ── Session temp dir ─────────────────────────────────────────────────
|
| 102 |
-
mgr = SessionManager(session_id)
|
| 103 |
-
session_dir = mgr.get_dir()
|
| 104 |
-
frame_dir = session_dir / "frames"
|
| 105 |
-
frame_dir.mkdir(parents=True, exist_ok=True)
|
| 106 |
-
|
| 107 |
-
# ── Copy to session dir ──────────────────────────────────────────────
|
| 108 |
-
p("Copying video to secure temp folder…", 0.05)
|
| 109 |
-
dst_video = session_dir / ("video" + suffix)
|
| 110 |
-
shutil.copy2(str(src), str(dst_video))
|
| 111 |
-
file_hash = _sha256_partial(dst_video)
|
| 112 |
-
|
| 113 |
-
# ── Probe video metadata ─────────────────────────────────────────────
|
| 114 |
-
p("Probing video metadata…", 0.08)
|
| 115 |
-
dur, fps, w, h = _probe_video(str(dst_video))
|
| 116 |
-
logger.info(f"Video: {dur:.1f}s, {fps:.2f}fps, {w}x{h}")
|
| 117 |
-
|
| 118 |
-
# ── Extract audio ────────────────────────────────────────────────────
|
| 119 |
-
p("Extracting audio track…", 0.12)
|
| 120 |
-
audio_path = session_dir / "audio.wav"
|
| 121 |
-
_extract_audio(str(dst_video), str(audio_path))
|
| 122 |
-
p("Audio extracted ✓", 0.25)
|
| 123 |
-
|
| 124 |
-
# ── Extract frames ───────────────────────────────────────────────────
|
| 125 |
-
p("Sampling video frames…", 0.28)
|
| 126 |
-
interval = self._adaptive_interval(dur)
|
| 127 |
-
frames = self._extract_frames(
|
| 128 |
-
str(dst_video), str(frame_dir), dur, fps, interval, p
|
| 129 |
-
)
|
| 130 |
-
p(f"Extracted {len(frames)} frames ✓", 0.80)
|
| 131 |
-
|
| 132 |
-
elapsed = time.time() - t0
|
| 133 |
-
meta = VideoMeta(
|
| 134 |
-
session_id=session_id,
|
| 135 |
-
original_filename=src.name,
|
| 136 |
-
video_path=str(dst_video),
|
| 137 |
-
audio_path=str(audio_path),
|
| 138 |
-
frames=frames,
|
| 139 |
-
duration_sec=dur,
|
| 140 |
-
fps=fps,
|
| 141 |
-
width=w,
|
| 142 |
-
height=h,
|
| 143 |
-
frame_dir=str(frame_dir),
|
| 144 |
-
processing_time_sec=elapsed,
|
| 145 |
-
file_hash=file_hash,
|
| 146 |
-
)
|
| 147 |
-
logger.info(f"VideoProcessor done in {elapsed:.1f}s — {len(frames)} frames")
|
| 148 |
-
return meta
|
| 149 |
-
|
| 150 |
-
# ── Adaptive interval ─────────────────────────────────────────────────────
|
| 151 |
-
def _adaptive_interval(self, duration_sec: float) -> int:
|
| 152 |
-
if duration_sec < 600:
|
| 153 |
-
return self.FRAME_INTERVAL_SHORT
|
| 154 |
-
elif duration_sec < 1800:
|
| 155 |
-
return self.FRAME_INTERVAL_MEDIUM
|
| 156 |
-
return self.FRAME_INTERVAL_LONG
|
| 157 |
-
|
| 158 |
-
# ── Frame extraction ──────────────────────────────────────────────────────
|
| 159 |
-
def _extract_frames(
|
| 160 |
-
self,
|
| 161 |
-
video_path: str,
|
| 162 |
-
frame_dir: str,
|
| 163 |
-
duration: float,
|
| 164 |
-
fps: float,
|
| 165 |
-
interval_sec: int,
|
| 166 |
-
progress_cb: Callable,
|
| 167 |
-
) -> List[FrameInfo]:
|
| 168 |
-
cap = cv2.VideoCapture(video_path)
|
| 169 |
-
if not cap.isOpened():
|
| 170 |
-
raise RuntimeError(f"Cannot open video: {video_path}")
|
| 171 |
-
|
| 172 |
-
frames: List[FrameInfo] = []
|
| 173 |
-
prev_gray: Optional[np.ndarray] = None
|
| 174 |
-
frame_idx = 0
|
| 175 |
-
saved_idx = 0
|
| 176 |
-
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 177 |
-
step = max(1, int(fps * interval_sec))
|
| 178 |
-
|
| 179 |
-
while True:
|
| 180 |
-
ret, frame = cap.read()
|
| 181 |
-
if not ret:
|
| 182 |
-
break
|
| 183 |
-
|
| 184 |
-
if frame_idx % step == 0:
|
| 185 |
-
ts = frame_idx / max(fps, 1.0)
|
| 186 |
-
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
| 187 |
-
gray_small = cv2.resize(gray, (160, 90))
|
| 188 |
-
|
| 189 |
-
# Scene-change gate: always save first frame
|
| 190 |
-
save = True
|
| 191 |
-
if prev_gray is not None:
|
| 192 |
-
diff = np.mean(np.abs(gray_small.astype(float) - prev_gray.astype(float)))
|
| 193 |
-
save = diff > self.SCENE_DIFF_THRESHOLD or (saved_idx == 0)
|
| 194 |
-
|
| 195 |
-
if save and saved_idx < self.MAX_FRAMES:
|
| 196 |
-
out_path = os.path.join(frame_dir, f"frame_{saved_idx:05d}_{int(ts):06d}.jpg")
|
| 197 |
-
# Resize to max 720p to save RAM
|
| 198 |
-
frame_resized = _resize_frame(frame, max_dim=720)
|
| 199 |
-
cv2.imwrite(out_path, frame_resized, [cv2.IMWRITE_JPEG_QUALITY, 80])
|
| 200 |
-
frames.append(FrameInfo(path=out_path, timestamp_sec=ts, index=saved_idx))
|
| 201 |
-
prev_gray = gray_small
|
| 202 |
-
saved_idx += 1
|
| 203 |
-
|
| 204 |
-
if saved_idx % 20 == 0:
|
| 205 |
-
pct = 0.28 + 0.50 * (frame_idx / max(total_frames, 1))
|
| 206 |
-
progress_cb(f"Sampling frames… {saved_idx} captured", min(pct, 0.78))
|
| 207 |
-
|
| 208 |
-
frame_idx += 1
|
| 209 |
-
|
| 210 |
-
cap.release()
|
| 211 |
-
return frames
|
| 212 |
-
|
| 213 |
-
# ── Thumbnail helper ──────────────────────────────────────────────────────
|
| 214 |
-
def get_thumbnail(self, meta: VideoMeta) -> Optional[Image.Image]:
|
| 215 |
-
if not meta.frames:
|
| 216 |
-
return None
|
| 217 |
-
try:
|
| 218 |
-
return Image.open(meta.frames[len(meta.frames) // 2].path)
|
| 219 |
-
except Exception:
|
| 220 |
-
return None
|
| 221 |
-
|
| 222 |
-
def frames_near_timestamp(
|
| 223 |
-
self, meta: VideoMeta, ts: float, window: float = 30.0
|
| 224 |
-
) -> List[FrameInfo]:
|
| 225 |
-
return [
|
| 226 |
-
f for f in meta.frames
|
| 227 |
-
if abs(f.timestamp_sec - ts) <= window
|
| 228 |
-
]
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
# ── FFmpeg helpers ─────────────────────────────────────────────────────────────
|
| 232 |
-
|
| 233 |
-
def _probe_video(path: str) -> Tuple[float, float, int, int]:
|
| 234 |
-
"""Returns (duration_sec, fps, width, height)."""
|
| 235 |
-
try:
|
| 236 |
-
probe = ffmpeg.probe(path)
|
| 237 |
-
vs = next(
|
| 238 |
-
(s for s in probe["streams"] if s["codec_type"] == "video"),
|
| 239 |
-
None,
|
| 240 |
-
)
|
| 241 |
-
if vs is None:
|
| 242 |
-
raise RuntimeError("No video stream found")
|
| 243 |
-
|
| 244 |
-
dur = float(probe["format"].get("duration", 0))
|
| 245 |
-
r_num, r_den = (vs.get("r_frame_rate", "25/1") or "25/1").split("/")
|
| 246 |
-
fps = float(r_num) / max(float(r_den), 1.0)
|
| 247 |
-
w = int(vs.get("width", 1280))
|
| 248 |
-
h = int(vs.get("height", 720))
|
| 249 |
-
return dur, fps, w, h
|
| 250 |
-
except Exception as e:
|
| 251 |
-
logger.warning(f"ffprobe fallback — {e}")
|
| 252 |
-
return 0.0, 25.0, 1280, 720
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
def _extract_audio(video_path: str, audio_path: str) -> None:
|
| 256 |
-
"""Extract mono 16kHz WAV (ideal for Whisper)."""
|
| 257 |
-
try:
|
| 258 |
-
(
|
| 259 |
-
ffmpeg
|
| 260 |
-
.input(video_path)
|
| 261 |
-
.output(
|
| 262 |
-
audio_path,
|
| 263 |
-
format="wav",
|
| 264 |
-
acodec="pcm_s16le",
|
| 265 |
-
ac=1, # mono
|
| 266 |
-
ar="16000", # 16kHz
|
| 267 |
-
)
|
| 268 |
-
.overwrite_output()
|
| 269 |
-
.run(quiet=True)
|
| 270 |
-
)
|
| 271 |
-
except ffmpeg.Error as e:
|
| 272 |
-
raise RuntimeError(f"Audio extraction failed: {e.stderr.decode()}")
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
def _resize_frame(frame: np.ndarray, max_dim: int = 720) -> np.ndarray:
|
| 276 |
-
h, w = frame.shape[:2]
|
| 277 |
-
if max(h, w) <= max_dim:
|
| 278 |
-
return frame
|
| 279 |
-
scale = max_dim / max(h, w)
|
| 280 |
-
new_w, new_h = int(w * scale), int(h * scale)
|
| 281 |
-
return cv2.resize(frame, (new_w, new_h), interpolation=cv2.INTER_AREA)
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
def _sha256_partial(path: Path, chunk_size: int = 65536) -> str:
|
| 285 |
-
"""Quick partial hash for dedup / integrity."""
|
| 286 |
-
h = hashlib.sha256()
|
| 287 |
-
with open(path, "rb") as f:
|
| 288 |
-
h.update(f.read(chunk_size))
|
| 289 |
-
return h.hexdigest()[:16]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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