Spaces:
Configuration error
Configuration error
Delete video_processor_py.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289"""core/video_processor.py=======================Complete video processing pipeline: 1. Validate & copy video to temp session folder 2. Extract audio track (WAV, mono, 16kHz) via FFmpeg 3. Extract representative frames (adaptive interval) 4. Return structured VideoMeta object
Design choices: - ffmpeg-python for reliable cross-platform FFmpeg wrapping - Adaptive frame sampling: shorter videos β denser frames - Scene-change detection via simple pixel-diff to avoid redundant frames - All output goes to a per-session temp directory - moviepy used ONLY for duration probe (lighter than loading full video)"""
from __future__ import annotations
import osimport shutilimport timeimport hashlibimport threadingfrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import List, Optional, Callable, Tuple
import cv2import ffmpegimport numpy as npfrom loguru import loggerfrom PIL import Image
from utils.session_manager import SessionManager
# ββ Result types ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@dataclassclass FrameInfo: path: str timestamp_sec: float index: int
@dataclassclass VideoMeta: session_id: str original_filename: str video_path: str # path inside temp dir audio_path: str # extracted WAV frames: List[FrameInfo] # sampled frames duration_sec: float fps: float width: int height: int frame_dir: str processing_time_sec: float = 0.0 file_hash: str = ""
# ββ Main processor ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class VideoProcessor:
# Adaptive sampling config FRAME_INTERVAL_SHORT = 3 # <10 min β 1 frame every 3s FRAME_INTERVAL_MEDIUM = 6 # 10-30min β 1 frame every 6s FRAME_INTERVAL_LONG = 10 # >30min β 1 frame every 10s MAX_FRAMES = 300 # hard cap to keep RAM sane SCENE_DIFF_THRESHOLD = 30 # mean pixel diff to trigger scene capture
def __init__(self): self._lock = threading.Lock()
# ββ Public entry point ββββββββββββββββββββββββββββββββββββββββββββββββββββ def process( self, uploaded_path: str, session_id: str, progress_cb: Optional[Callable[[str, float], None]] = None, ) -> VideoMeta: """ Full pipeline. progress_cb(message, 0.0-1.0) for UI updates. Raises ValueError on bad input, RuntimeError on processing failure. """ t0 = time.time() p = progress_cb or (lambda msg, pct: None)
p("Validating videoβ¦", 0.02) src = Path(uploaded_path) if not src.exists(): raise ValueError(f"File not found: {uploaded_path}")
suffix = src.suffix.lower() allowed = {".mp4", ".mkv", ".avi", ".mov", ".webm", ".flv", ".wmv", ".m4v"} if suffix not in allowed: raise ValueError(f"Unsupported format: {suffix}")
# ββ Session temp dir βββββββββββββββββββββββββββββββββββββββββββββββββ mgr = SessionManager(session_id) session_dir = mgr.get_dir() frame_dir = session_dir / "frames" frame_dir.mkdir(parents=True, exist_ok=True)
# ββ Copy to session dir ββββββββββββββββββββββββββββββββββββββββββββββ p("Copying video to secure temp folderβ¦", 0.05) dst_video = session_dir / ("video" + suffix) shutil.copy2(str(src), str(dst_video)) file_hash = _sha256_partial(dst_video)
# ββ Probe video metadata βββββββββββββββββββββββββββββββββββββββββββββ p("Probing video metadataβ¦", 0.08) dur, fps, w, h = _probe_video(str(dst_video)) logger.info(f"Video: {dur:.1f}s, {fps:.2f}fps, {w}x{h}")
# ββ Extract audio ββββββββββββββββββββββββββββββββββββββββββββββββββββ p("Extracting audio trackβ¦", 0.12) audio_path = session_dir / "audio.wav" _extract_audio(str(dst_video), str(audio_path)) p("Audio extracted β", 0.25)
# ββ Extract frames βββββββββββββββββββββββββββββββββββββββββββββββββββ p("Sampling video framesβ¦", 0.28) interval = self._adaptive_interval(dur) frames = self._extract_frames( str(dst_video), str(frame_dir), dur, fps, interval, p ) p(f"Extracted {len(frames)} frames β", 0.80)
elapsed = time.time() - t0 meta = VideoMeta( session_id=session_id, original_filename=src.name, video_path=str(dst_video), audio_path=str(audio_path), frames=frames, duration_sec=dur, fps=fps, width=w, height=h, frame_dir=str(frame_dir), processing_time_sec=elapsed, file_hash=file_hash, ) logger.info(f"VideoProcessor done in {elapsed:.1f}s β {len(frames)} frames") return meta
# ββ Adaptive interval βββββββββββββββββββββββββββββββββββββββββββββββββββββ def _adaptive_interval(self, duration_sec: float) -> int: if duration_sec < 600: return self.FRAME_INTERVAL_SHORT elif duration_sec < 1800: return self.FRAME_INTERVAL_MEDIUM return self.FRAME_INTERVAL_LONG
# ββ Frame extraction ββββββββββββββββββββββββββββββββββββββββββββββββββββββ def _extract_frames( self, video_path: str, frame_dir: str, duration: float, fps: float, interval_sec: int, progress_cb: Callable, ) -> List[FrameInfo]: cap = cv2.VideoCapture(video_path) if not cap.isOpened(): raise RuntimeError(f"Cannot open video: {video_path}")
frames: List[FrameInfo] = [] prev_gray: Optional[np.ndarray] = None frame_idx = 0 saved_idx = 0 total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) step = max(1, int(fps * interval_sec))
while True: ret, frame = cap.read() if not ret: break
if frame_idx % step == 0: ts = frame_idx / max(fps, 1.0) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gray_small = cv2.resize(gray, (160, 90))
# Scene-change gate: always save first frame save = True if prev_gray is not None: diff = np.mean(np.abs(gray_small.astype(float) - prev_gray.astype(float))) save = diff > self.SCENE_DIFF_THRESHOLD or (saved_idx == 0)
if save and saved_idx < self.MAX_FRAMES: out_path = os.path.join(frame_dir, f"frame_{saved_idx:05d}_{int(ts):06d}.jpg") # Resize to max 720p to save RAM frame_resized = _resize_frame(frame, max_dim=720) cv2.imwrite(out_path, frame_resized, [cv2.IMWRITE_JPEG_QUALITY, 80]) frames.append(FrameInfo(path=out_path, timestamp_sec=ts, index=saved_idx)) prev_gray = gray_small saved_idx += 1
if saved_idx % 20 == 0: pct = 0.28 + 0.50 * (frame_idx / max(total_frames, 1)) progress_cb(f"Sampling frames⦠{saved_idx} captured", min(pct, 0.78))
frame_idx += 1
cap.release() return frames
# ββ Thumbnail helper ββββββββββββββββββββββββββββββββββββββββββββββββββββββ def get_thumbnail(self, meta: VideoMeta) -> Optional[Image.Image]: if not meta.frames: return None try: return Image.open(meta.frames[len(meta.frames) // 2].path) except Exception: return None
def frames_near_timestamp( self, meta: VideoMeta, ts: float, window: float = 30.0 ) -> List[FrameInfo]: return [ f for f in meta.frames if abs(f.timestamp_sec - ts) <= window ]
# ββ FFmpeg helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _probe_video(path: str) -> Tuple[float, float, int, int]: """Returns (duration_sec, fps, width, height).""" try: probe = ffmpeg.probe(path) vs = next( (s for s in probe["streams"] if s["codec_type"] == "video"), None, ) if vs is None: raise RuntimeError("No video stream found")
dur = float(probe["format"].get("duration", 0)) r_num, r_den = (vs.get("r_frame_rate", "25/1") or "25/1").split("/") fps = float(r_num) / max(float(r_den), 1.0) w = int(vs.get("width", 1280)) h = int(vs.get("height", 720)) return dur, fps, w, h except Exception as e: logger.warning(f"ffprobe fallback β {e}") return 0.0, 25.0, 1280, 720
def _extract_audio(video_path: str, audio_path: str) -> None: """Extract mono 16kHz WAV (ideal for Whisper).""" try: ( ffmpeg .input(video_path) .output( audio_path, format="wav", acodec="pcm_s16le", ac=1, # mono ar="16000", # 16kHz ) .overwrite_output() .run(quiet=True) ) except ffmpeg.Error as e: raise RuntimeError(f"Audio extraction failed: {e.stderr.decode()}")
def _resize_frame(frame: np.ndarray, max_dim: int = 720) -> np.ndarray: h, w = frame.shape[:2] if max(h, w) <= max_dim: return frame scale = max_dim / max(h, w) new_w, new_h = int(w * scale), int(h * scale) return cv2.resize(frame, (new_w, new_h), interpolation=cv2.INTER_AREA)
def _sha256_partial(path: Path, chunk_size: int = 65536) -> str: """Quick partial hash for dedup / integrity.""" h = hashlib.sha256() with open(path, "rb") as f: h.update(f.read(chunk_size)) return h.hexdigest()[:16]video_processor_py.pyDeleted-289