import gradio as gr import os import shutil import cv2 from scenedetect import VideoManager, SceneManager from scenedetect.detectors import ContentDetector from scenedetect.scene_manager import save_images from moviepy.editor import VideoFileClip # ---------- UTILS ---------- def clear_temp(): if os.path.exists("scenes"): shutil.rmtree("scenes") os.makedirs("scenes", exist_ok=True) def detect_scenes(video_path): video_manager = VideoManager([video_path]) scene_manager = SceneManager() scene_manager.add_detector(ContentDetector(threshold=30.0)) video_manager.set_downscale_factor() video_manager.start() scene_manager.detect_scenes(frame_source=video_manager) scene_list = scene_manager.get_scene_list() video_manager.release() return scene_list def sample_frame(video_path, start_time, end_time, output_path): cap = cv2.VideoCapture(video_path) if not cap.isOpened(): print("Error: Cannot open video.") return midpoint_time = (start_time.get_seconds() + end_time.get_seconds()) / 2 fps = cap.get(cv2.CAP_PROP_FPS) target_frame = int(midpoint_time * fps) cap.set(cv2.CAP_PROP_POS_FRAMES, target_frame) ret, frame = cap.read() if ret: cv2.imwrite(output_path, frame) cap.release() def process_video(video_file): clear_temp() video_path = video_file scenes = detect_scenes(video_path) scene_descriptions = [] for idx, (start, end) in enumerate(scenes): scene_num = idx + 1 filename = f"scenes/scene_{scene_num:02d}.jpg" sample_frame(video_path, start, end, filename) scene_descriptions.append(f"[Scene {scene_num}] {start} → {end}") return scene_descriptions, [f"scenes/{img}" for img in sorted(os.listdir("scenes"))] # ---------- UI ---------- with gr.Blocks() as demo: gr.Markdown("# 🎬 Scene Sampler") gr.Markdown("Upload a video → Get sampled scene frames + timestamps") with gr.Row(): video_input = gr.Video() run_button = gr.Button("Process Video") output_text = gr.Textbox(label="Scene Timestamps", lines=15) output_gallery = gr.Gallery(label="Scene Frames").style(grid=3) run_button.click(fn=process_video, inputs=video_input, outputs=[output_text, output_gallery]) demo.launch()