"""Uniform frame sampling from a video into base64-encoded JPEG strings.""" from __future__ import annotations import base64 import io import os import cv2 from PIL import Image DEFAULT_NUM_SAMPLE_FRAMES: int = 8 def extract_frames_from_video( video_path: str, num_frames: int = DEFAULT_NUM_SAMPLE_FRAMES, jpeg_quality: int = 90, verbose: bool = True, ) -> list[str]: """Uniformly sample frames from a video and return them as base64 JPEGs. Returns ------- list[str] Base64-encoded JPEG strings, in temporal order (frame 1 = earliest, frame N = latest). """ cap = cv2.VideoCapture(video_path) if not cap.isOpened(): raise RuntimeError(f"Cannot open video: {video_path}") fps = cap.get(cv2.CAP_PROP_FPS) total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) if fps <= 0 or total_frames <= 0: cap.release() raise RuntimeError( f"Invalid video metadata: fps={fps}, total_frames={total_frames}" ) duration = total_frames / fps num_to_sample = max(1, min(int(num_frames), total_frames)) if num_to_sample == 1: sample_indices = [0] else: sample_indices = [ int(round(i * (total_frames - 1) / (num_to_sample - 1))) for i in range(num_to_sample) ] frame_b64_list: list[str] = [] for frame_idx in sample_indices: cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx) ret, frame = cap.read() if not ret: continue frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) img = Image.fromarray(frame_rgb) buf = io.BytesIO() img.save(buf, format="JPEG", quality=int(jpeg_quality)) frame_b64_list.append(base64.b64encode(buf.getvalue()).decode("utf-8")) cap.release() if not frame_b64_list: raise RuntimeError(f"Failed to extract any frames from {video_path}") if verbose: print( f" [frames] Extracted {len(frame_b64_list)} frames from " f"{os.path.basename(video_path)} " f"(duration={duration:.1f}s, fps={fps:.1f})" ) return frame_b64_list