import cv2 import os import tempfile def process_video(video_path, clip_duration=10, target_fps=25): """ Processes the input video: - Trims the last `clip_duration` seconds - Samples frames at `target_fps` Returns: frames: List of BGR frames metadata: Dict with original FPS, trimmed duration, frame count """ cap = cv2.VideoCapture(video_path) if not cap.isOpened(): raise IOError("Cannot open video file.") orig_fps = cap.get(cv2.CAP_PROP_FPS) total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) duration = total_frames / orig_fps # Calculate starting point for last `clip_duration` seconds start_time = max(0, duration - clip_duration) start_frame = int(start_time * orig_fps) # Set video to start point cap.set(cv2.CAP_PROP_POS_FRAMES, start_frame) # Read and sample frames frames = [] frame_interval = int(orig_fps // target_fps) if target_fps < orig_fps else 1 frame_idx = 0 while True: ret, frame = cap.read() if not ret: break if frame_idx % frame_interval == 0: frames.append(frame) frame_idx += 1 cap.release() metadata = { "original_fps": orig_fps, "sampled_fps": target_fps, "clip_duration": clip_duration, "sampled_frames": len(frames) } return frames, metadata