From 101a467c34fae744a4861a4065969ddea2efd0ec Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Sat, 18 Jul 2026 03:49:01 +0200 Subject: [PATCH 1/4] feat(reframe): TransNetV2 neural scene detection with PySceneDetect fallback MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New scene_detection module: TransNetV2 (small 3D-CNN, runs on 48x27 frames) as the primary shot-boundary detector — far more accurate than the fixed ContentDetector threshold on fast motion, flashes and gradual transitions. Adds a min-scene-length merge (SCENE_MIN_SEC, default 1s) to stop camera-snap bursts. Legacy PySceneDetect path is preserved untouched as automatic fallback and selectable via SCENE_ENGINE=pyscenedetect. --- main.py | 9 +-- requirements.txt | 1 + scene_detection.py | 148 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 151 insertions(+), 7 deletions(-) create mode 100644 scene_detection.py diff --git a/main.py b/main.py index 791578a..873b7e6 100644 --- a/main.py +++ b/main.py @@ -468,13 +468,8 @@ def analyze_scenes_strategy(video_path, scenes): return strategies def detect_scenes(video_path): - video = open_video(video_path) - scene_manager = SceneManager() - scene_manager.add_detector(ContentDetector()) - scene_manager.detect_scenes(video=video) - scene_list = scene_manager.get_scene_list() - fps = video.frame_rate - return scene_list, fps + import scene_detection + return scene_detection.detect_scenes(video_path) def get_video_resolution(video_path): cap = cv2.VideoCapture(video_path) diff --git a/requirements.txt b/requirements.txt index c40891d..419ad19 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,5 @@ scenedetect==0.7 +transnetv2-pytorch==1.0.5 ultralytics==8.4.46 torch==2.11.0 torchvision==0.26.0 diff --git a/scene_detection.py b/scene_detection.py new file mode 100644 index 0000000..e7de575 --- /dev/null +++ b/scene_detection.py @@ -0,0 +1,148 @@ +"""Scene detection engines for the reframe pipeline. + +Primary engine: TransNetV2, a small neural shot-boundary detector that is +markedly more accurate than threshold-based detection (handles fast camera +motion, flashes and gradual transitions such as fades/dissolves). Runs on +48x27 frames, faster than realtime even on CPU. + +Fallback/legacy engine: PySceneDetect ContentDetector, byte-for-byte the +pre-existing behavior. Any TransNetV2 failure (missing package, corrupt +weights, decode error) falls back automatically so a scene-detection edge +case can never kill a job. + +Environment variables: + SCENE_ENGINE "transnetv2" (default) | "pyscenedetect" (legacy) + SCENE_MIN_SEC minimum scene length in seconds; shorter scenes are + merged into a neighbor (default 1.0, TransNetV2 path + only — the legacy path stays untouched) + TRANSNETV2_THRESHOLD shot-boundary probability threshold (default 0.5) + TRANSNETV2_DEVICE torch device: "auto" (default) | "cpu" | "cuda" | "mps" +""" + +import os +import subprocess +import threading + +import cv2 +import numpy as np +from scenedetect import open_video, SceneManager, FrameTimecode +from scenedetect.detectors import ContentDetector + +# TransNetV2 input size (width x height), fixed by the trained model. +_TN2_W, _TN2_H = 48, 27 + +# One shared model instance; clips can process in parallel (CLIP_WORKERS) so +# inference is serialized like the other detectors in main.py. +_TN2_LOCK = threading.Lock() +_tn2_model = None + + +def detect_scenes(video_path): + """Detect scenes. Returns (scene_list, fps) where scene_list is a list of + (FrameTimecode, FrameTimecode) pairs — the same contract PySceneDetect's + SceneManager.get_scene_list() has always given callers.""" + engine = os.environ.get("SCENE_ENGINE", "transnetv2").strip().lower() + if engine != "pyscenedetect": + try: + return _detect_transnetv2(video_path) + except Exception as e: + print(f" ⚠️ TransNetV2 scene detection failed " + f"({type(e).__name__}: {e}) — falling back to PySceneDetect") + return _detect_pyscenedetect(video_path) + + +# --- legacy engine ---------------------------------------------------------- + +def _detect_pyscenedetect(video_path): + video = open_video(video_path) + scene_manager = SceneManager() + scene_manager.add_detector(ContentDetector()) + scene_manager.detect_scenes(video=video) + scene_list = scene_manager.get_scene_list() + fps = video.frame_rate + return scene_list, fps + + +# --- TransNetV2 engine ------------------------------------------------------ + +def _get_tn2_model(): + global _tn2_model + if _tn2_model is None: + from transnetv2_pytorch import TransNetV2 + device = os.environ.get("TRANSNETV2_DEVICE", "auto") + model = TransNetV2(device=device) + model.eval() + _tn2_model = model + return _tn2_model + + +def _extract_frames_small(video_path): + """Decode the whole clip as 48x27 RGB frames via ffmpeg (~4KB/frame).""" + cmd = [ + "ffmpeg", "-nostdin", "-i", video_path, + "-vf", f"scale={_TN2_W}:{_TN2_H}", + "-pix_fmt", "rgb24", "-f", "rawvideo", "-", + ] + proc = subprocess.run(cmd, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, check=True, timeout=900) + frame_bytes = _TN2_H * _TN2_W * 3 + n = len(proc.stdout) // frame_bytes + if n == 0: + raise RuntimeError("ffmpeg produced no frames") + return np.frombuffer(proc.stdout[:n * frame_bytes], + dtype=np.uint8).reshape(n, _TN2_H, _TN2_W, 3) + + +def _detect_transnetv2(video_path): + import torch + + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or 30.0 + total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + cap.release() + + frames = _extract_frames_small(video_path) + model = _get_tn2_model() + threshold = float(os.environ.get("TRANSNETV2_THRESHOLD", "0.5")) + + with _TN2_LOCK, torch.no_grad(): + tensor = torch.from_numpy(np.ascontiguousarray(frames)).to(model.device) + single_frame_pred, _ = model.predict_frames(tensor, quiet=True) + + # predictions_to_scenes returns [[start, end], ...] with INCLUSIVE ends; + # downstream expects PySceneDetect's exclusive ends. + raw = model.predictions_to_scenes(single_frame_pred.numpy(), threshold=threshold) + bounds = [(int(s), int(e) + 1) for s, e in raw] + + # cv2's frame count can differ by a few frames from what ffmpeg decodes; + # downstream loops run to the decoder's count, so cover the gap. + if total_frames > bounds[-1][1]: + bounds[-1] = (bounds[-1][0], total_frames) + + min_sec = float(os.environ.get("SCENE_MIN_SEC", "1.0")) + bounds = _merge_short_scenes(bounds, fps, min_sec) + + scene_list = [(FrameTimecode(s, fps), FrameTimecode(e, fps)) + for s, e in bounds] + print(f" 🎬 Scene engine: TransNetV2 — {len(scene_list)} scenes") + return scene_list, fps + + +def _merge_short_scenes(bounds, fps, min_sec): + """Absorb scenes shorter than min_sec into a neighbor. Ultra-short scenes + cause camera-snap bursts and starve the per-scene strategy sampling.""" + if len(bounds) <= 1 or min_sec <= 0: + return bounds + min_frames = max(1, int(round(min_sec * float(fps)))) + + merged = [] + for s, e in bounds: + if merged and (e - s) < min_frames: + merged[-1] = (merged[-1][0], e) + else: + merged.append((s, e)) + # The first scene can still be short — fold it into the one after it. + if len(merged) > 1 and (merged[0][1] - merged[0][0]) < min_frames: + merged[1] = (merged[0][0], merged[1][1]) + merged.pop(0) + return merged From 36cf6d33b110b362d003667e8626ab9ac3e5b9b1 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Sat, 18 Jul 2026 03:51:50 +0200 Subject: [PATCH 2/4] fix(reframe): robustify per-scene TRACK/GENERAL strategy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Sample 5 evenly-spread frames clamped inside the scene (old start+5/end-5 fell outside scenes shorter than ~10 frames) - Skip near-black frames so fades stop dragging single-person scenes to GENERAL - Hysteresis: a sub-2s scene flanked by agreeing neighbors adopts their strategy — each TRACK<->GENERAL flip is a full layout change on screen --- main.py | 48 ++++++++++++++++++++++++++++++++++-------------- 1 file changed, 34 insertions(+), 14 deletions(-) diff --git a/main.py b/main.py index 873b7e6..91fb468 100644 --- a/main.py +++ b/main.py @@ -426,45 +426,65 @@ def analyze_scenes_strategy(video_path, scenes): """ cap = cv2.VideoCapture(video_path) strategies = [] - + if not cap.isOpened(): return ['TRACK'] * len(scenes) - + + fps = cap.get(cv2.CAP_PROP_FPS) or 30.0 + for start, end in tqdm(scenes, desc=" Analyzing Scenes"): - # Sample 3 frames (start, middle, end) - frames_to_check = [ - start.get_frames() + 5, - int((start.get_frames() + end.get_frames()) / 2), - end.get_frames() - 5 - ] - + s_f, e_f = start.get_frames(), end.get_frames() + # Sample 5 frames spread across the scene, clamped inside it (the old + # start+5/end-5 samples landed outside scenes shorter than ~10 frames). + margin = min(2, max(0, (e_f - s_f - 1) // 2)) + frames_to_check = sorted(set( + int(round(f)) for f in np.linspace(s_f + margin, e_f - 1 - margin, 5) + )) + face_counts = [] for f_idx in frames_to_check: cap.set(cv2.CAP_PROP_POS_FRAMES, f_idx) ret, frame = cap.read() if not ret: continue - + + # Near-black frames (fades, cut-to-black) carry no faces and used + # to drag single-person scenes into GENERAL. Skip them. + if frame.mean() < 16: + continue + # Detect faces candidates = detect_face_candidates(frame) face_counts.append(len(candidates)) - + # Decision Logic if not face_counts: avg_faces = 0 else: avg_faces = sum(face_counts) / len(face_counts) - + # Strategy: # 0 faces -> GENERAL (Landscape/B-roll) # 1 face -> TRACK # > 1.2 faces -> GENERAL (Group) - + if avg_faces > 1.2 or avg_faces < 0.5: strategies.append('GENERAL') else: strategies.append('TRACK') - + cap.release() + + # Hysteresis: a short scene whose two neighbors agree on the opposite + # strategy is almost always a sampling miss (profile face, insert shot). + # Each TRACK<->GENERAL flip is a full on-screen layout change, so flapping + # is worse than an occasional wrong-but-stable choice. + max_flip_frames = int(2.0 * fps) + for i in range(1, len(strategies) - 1): + dur = scenes[i][1].get_frames() - scenes[i][0].get_frames() + if (dur < max_flip_frames + and strategies[i - 1] == strategies[i + 1] != strategies[i]): + strategies[i] = strategies[i - 1] + return strategies def detect_scenes(video_path): From ef43c282c7830e398af48da76a17bfb2fd48b96b Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Sat, 18 Jul 2026 04:39:15 +0200 Subject: [PATCH 3/4] fix(reframe): lower SCENE_MIN_SEC default 1.0s -> 0.4s A/B audit on 10 topic-diverse clips showed the 1s merge deleted real sub-second shots in fast-cut content (10/13 lost real cuts in gaming, 9/10 in anime, 5/8 in music videos were present in the raw TransNetV2 output and removed by the merge). 0.4s still kills flash/single-frame scenes and snap bursts without eating real fast cuts. --- scene_detection.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scene_detection.py b/scene_detection.py index e7de575..e584376 100644 --- a/scene_detection.py +++ b/scene_detection.py @@ -13,7 +13,7 @@ case can never kill a job. Environment variables: SCENE_ENGINE "transnetv2" (default) | "pyscenedetect" (legacy) SCENE_MIN_SEC minimum scene length in seconds; shorter scenes are - merged into a neighbor (default 1.0, TransNetV2 path + merged into a neighbor (default 0.4, TransNetV2 path only — the legacy path stays untouched) TRANSNETV2_THRESHOLD shot-boundary probability threshold (default 0.5) TRANSNETV2_DEVICE torch device: "auto" (default) | "cpu" | "cuda" | "mps" @@ -119,7 +119,7 @@ def _detect_transnetv2(video_path): if total_frames > bounds[-1][1]: bounds[-1] = (bounds[-1][0], total_frames) - min_sec = float(os.environ.get("SCENE_MIN_SEC", "1.0")) + min_sec = float(os.environ.get("SCENE_MIN_SEC", "0.4")) bounds = _merge_short_scenes(bounds, fps, min_sec) scene_list = [(FrameTimecode(s, fps), FrameTimecode(e, fps)) From 40a6427c7193d8b4973445d3b7a3ace8a416eab0 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Sat, 18 Jul 2026 13:43:00 +0200 Subject: [PATCH 4/4] fix: retry whisper on CPU when CUDA fails (OOM on shared GPU killed jobs) --- transcribe_backends.py | 40 +++++++++++++++++++++++++++++++++------- 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/transcribe_backends.py b/transcribe_backends.py index 15d9bc6..644ffef 100644 --- a/transcribe_backends.py +++ b/transcribe_backends.py @@ -22,6 +22,8 @@ TRANSCRIBE_BACKEND env: "whisper" (default) | "parakeet". The parakeet path falls back to whisper automatically when the model errors, produces no usable words, or the detected language is outside its 25 supported European languages (e.g. Japanese/Chinese/Arabic uploads). +GPU whisper in turn falls back to CPU whisper on CUDA errors (VRAM is shared +with other models on the host, so loads can OOM under load). """ import os import subprocess @@ -87,6 +89,9 @@ class _TranscribeProgress: _whisper_model = None _whisper_key = None _whisper_lock = threading.Lock() +# Set after a CUDA failure (e.g. VRAM exhausted by other models on the GPU) +# so every later transcription goes straight to CPU instead of re-failing. +_whisper_force_cpu = False def _get_whisper_model(): @@ -97,6 +102,9 @@ def _get_whisper_model(): """ global _whisper_model, _whisper_key cfg = get_whisper_config() + if _whisper_force_cpu: + cfg["device"] = "cpu" + cfg["compute_type"] = "int8" key = (cfg["model_size"], cfg["device"], cfg["compute_type"]) with _whisper_lock: if _whisper_model is None or _whisper_key != key: @@ -106,13 +114,7 @@ def _get_whisper_model(): return _whisper_model, cfg["device"] -def run_whisper_transcription(media_path, **params): - """Transcribe and FULLY materialize the segments inside the GPU gate. - - faster-whisper returns a lazy generator — decoding happens while - iterating, so the gate must wrap list(segments), not just transcribe(). - Returns (segments_list, info). - """ +def _run_whisper_once(media_path, **params): model, device = _get_whisper_model() gate = _ASR_GATE if device != "cpu" else _NULL_GATE with gate: @@ -128,6 +130,30 @@ def run_whisper_transcription(media_path, **params): return materialized, info +def run_whisper_transcription(media_path, **params): + """Transcribe and FULLY materialize the segments inside the GPU gate. + + faster-whisper returns a lazy generator — decoding happens while + iterating, so the gate must wrap list(segments), not just transcribe(). + Returns (segments_list, info). + + A CUDA failure (model load OOM or mid-decode) retries once on CPU and + pins CPU for the rest of the process — the GPU is shared with other + models, so a job must degrade instead of dying when VRAM runs out. + """ + global _whisper_model, _whisper_force_cpu + try: + return _run_whisper_once(media_path, **params) + except RuntimeError as e: + if _whisper_force_cpu or "cuda" not in str(e).lower(): + raise + print(f"⚠️ [ASR] whisper GPU failed ({e}) — retrying on CPU", flush=True) + _whisper_force_cpu = True + with _whisper_lock: + _whisper_model = None # drop the GPU model to release its VRAM + return _run_whisper_once(media_path, **params) + + def _transcribe_with_whisper(media_path): segments, info = run_whisper_transcription(media_path, **WHISPER_TRANSCRIBE_PARAMS)