feat(reframe): parallel clip processing (CLIP_WORKERS, default 3) with detector lock; fix v2 Fraction fps
This commit is contained in:
parent
7ff41735a6
commit
dd867f098a
2 changed files with 49 additions and 29 deletions
77
main.py
77
main.py
|
|
@ -5,6 +5,8 @@ import subprocess
|
||||||
import argparse
|
import argparse
|
||||||
import re
|
import re
|
||||||
import sys
|
import sys
|
||||||
|
import threading
|
||||||
|
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||||
from scenedetect import open_video, SceneManager
|
from scenedetect import open_video, SceneManager
|
||||||
from scenedetect.detectors import ContentDetector
|
from scenedetect.detectors import ContentDetector
|
||||||
from ultralytics import YOLO
|
from ultralytics import YOLO
|
||||||
|
|
@ -286,6 +288,10 @@ class SpeakerTracker:
|
||||||
# coords and YOLO boxes are scaled back up. Running them on a ≤640px copy cuts
|
# coords and YOLO boxes are scaled back up. Running them on a ≤640px copy cuts
|
||||||
# per-frame preprocessing cost hard, which is what dominates CPU-only renders.
|
# per-frame preprocessing cost hard, which is what dominates CPU-only renders.
|
||||||
DETECT_MAX_WIDTH = 640
|
DETECT_MAX_WIDTH = 640
|
||||||
|
# The global MediaPipe graph and YOLO model are NOT thread-safe; clips render
|
||||||
|
# in parallel, so every inference goes through this lock. Contention is small
|
||||||
|
# (a few ms per call) — the ffmpeg renders are where the parallel time goes.
|
||||||
|
DETECT_LOCK = threading.Lock()
|
||||||
# Detect every Nth frame; SmoothedCameraman interpolates between updates.
|
# Detect every Nth frame; SmoothedCameraman interpolates between updates.
|
||||||
DETECT_STRIDE = max(int(os.environ.get("DETECT_STRIDE", "4")), 1)
|
DETECT_STRIDE = max(int(os.environ.get("DETECT_STRIDE", "4")), 1)
|
||||||
# YOLO fallback (no face found) is far heavier than MediaPipe — extra throttle.
|
# YOLO fallback (no face found) is far heavier than MediaPipe — extra throttle.
|
||||||
|
|
@ -313,7 +319,8 @@ def detect_face_candidates(frame):
|
||||||
height, width, _ = frame.shape
|
height, width, _ = frame.shape
|
||||||
small, _scale = _detection_frame(frame)
|
small, _scale = _detection_frame(frame)
|
||||||
rgb_frame = cv2.cvtColor(small, cv2.COLOR_BGR2RGB)
|
rgb_frame = cv2.cvtColor(small, cv2.COLOR_BGR2RGB)
|
||||||
results = face_detection.process(rgb_frame)
|
with DETECT_LOCK:
|
||||||
|
results = face_detection.process(rgb_frame)
|
||||||
|
|
||||||
candidates = []
|
candidates = []
|
||||||
|
|
||||||
|
|
@ -342,7 +349,8 @@ def detect_person_yolo(frame):
|
||||||
"""
|
"""
|
||||||
small, scale = _detection_frame(frame)
|
small, scale = _detection_frame(frame)
|
||||||
# Use the globally loaded model
|
# Use the globally loaded model
|
||||||
results = model(small, verbose=False, classes=[0]) # class 0 is person
|
with DETECT_LOCK:
|
||||||
|
results = model(small, verbose=False, classes=[0]) # class 0 is person
|
||||||
|
|
||||||
if not results:
|
if not results:
|
||||||
return None
|
return None
|
||||||
|
|
@ -1091,40 +1099,51 @@ if __name__ == '__main__':
|
||||||
json.dump(clips_data, f, indent=2)
|
json.dump(clips_data, f, indent=2)
|
||||||
print(f" Saved metadata to {metadata_file}")
|
print(f" Saved metadata to {metadata_file}")
|
||||||
|
|
||||||
# 5. Process each clip
|
# 5. Process clips in parallel: each worker cuts + renders one
|
||||||
for i, clip in enumerate(clips_data['shorts']):
|
# clip. Renders are mostly ffmpeg subprocesses (parallelize well);
|
||||||
|
# detector inference is serialized internally via DETECT_LOCK.
|
||||||
|
def _process_one_clip(i, clip):
|
||||||
start = clip['start']
|
start = clip['start']
|
||||||
end = clip['end']
|
end = clip['end']
|
||||||
print(f"\n🎬 Processing Clip {i+1}: {start}s - {end}s")
|
print(f"\n🎬 Processing Clip {i+1}: {start}s - {end}s")
|
||||||
print(f" Title: {clip.get('video_title_for_youtube_short', 'No Title')}")
|
print(f" Title: {clip.get('video_title_for_youtube_short', 'No Title')}")
|
||||||
|
|
||||||
# Cut clip
|
|
||||||
clip_filename = f"{video_title}_clip_{i+1}.mp4"
|
clip_filename = f"{video_title}_clip_{i+1}.mp4"
|
||||||
clip_temp_path = os.path.join(output_dir, f"temp_{clip_filename}")
|
clip_temp_path = os.path.join(output_dir, f"temp_{clip_filename}")
|
||||||
clip_final_path = os.path.join(output_dir, clip_filename)
|
clip_final_path = os.path.join(output_dir, clip_filename)
|
||||||
|
|
||||||
# ffmpeg cut
|
try:
|
||||||
# Using re-encoding for precision as requested by strict seconds
|
# ffmpeg cut — re-encoding for precision on strict seconds
|
||||||
cut_command = [
|
cut_command = [
|
||||||
'ffmpeg', '-y',
|
'ffmpeg', '-y',
|
||||||
'-ss', str(start),
|
'-ss', str(start),
|
||||||
'-to', str(end),
|
'-to', str(end),
|
||||||
'-i', input_video,
|
'-i', input_video,
|
||||||
*video_encode_args(QUALITY_FAST),
|
*video_encode_args(QUALITY_FAST),
|
||||||
'-c:a', 'aac',
|
'-c:a', 'aac',
|
||||||
clip_temp_path
|
clip_temp_path
|
||||||
]
|
]
|
||||||
subprocess.run(cut_command, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
|
subprocess.run(cut_command, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
|
||||||
|
|
||||||
# Process vertical
|
success = render_clip(clip_temp_path, clip_final_path, output_format)
|
||||||
success = render_clip(clip_temp_path, clip_final_path, output_format)
|
if success:
|
||||||
|
print(f" ✅ Clip {i+1} ready: {clip_final_path}")
|
||||||
if success:
|
return success
|
||||||
print(f" ✅ Clip {i+1} ready: {clip_final_path}")
|
finally:
|
||||||
|
if os.path.exists(clip_temp_path):
|
||||||
# Clean up temp cut
|
os.remove(clip_temp_path)
|
||||||
if os.path.exists(clip_temp_path):
|
|
||||||
os.remove(clip_temp_path)
|
clip_workers = max(int(os.environ.get("CLIP_WORKERS", "3")), 1)
|
||||||
|
shorts = clips_data['shorts']
|
||||||
|
with ThreadPoolExecutor(max_workers=min(clip_workers, len(shorts))) as pool:
|
||||||
|
futures = {pool.submit(_process_one_clip, i, clip): i
|
||||||
|
for i, clip in enumerate(shorts)}
|
||||||
|
for future in as_completed(futures):
|
||||||
|
i = futures[future]
|
||||||
|
try:
|
||||||
|
future.result()
|
||||||
|
except Exception as e:
|
||||||
|
print(f" ❌ Clip {i+1} failed: {type(e).__name__}: {e}")
|
||||||
|
|
||||||
# Clean up original if requested
|
# Clean up original if requested
|
||||||
if args.url and not args.keep_original and os.path.exists(input_video):
|
if args.url and not args.keep_original and os.path.exists(input_video):
|
||||||
|
|
|
||||||
|
|
@ -162,6 +162,7 @@ def render(input_video, final_output_video, aspect_ratio):
|
||||||
|
|
||||||
print(" 🚀 Reframe engine v2 (ffmpeg-native render)")
|
print(" 🚀 Reframe engine v2 (ffmpeg-native render)")
|
||||||
scenes, fps = m.detect_scenes(input_video)
|
scenes, fps = m.detect_scenes(input_video)
|
||||||
|
fps = float(fps) # PySceneDetect can hand back a Fraction
|
||||||
orig_w, orig_h = m.get_video_resolution(input_video)
|
orig_w, orig_h = m.get_video_resolution(input_video)
|
||||||
|
|
||||||
out_h = orig_h
|
out_h = orig_h
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue