import cv2 import os from typing import List # Base directory for all frame data BASE_FRAMES_DATA_DIR = os.path.join("data", "frames") def segment_video(video_path: str, task_id: str, frames_per_second: int = 1) -> List[str]: """Extracts key frames from a video, organized by task_id and video_id, and returns a list of frame paths.""" if not task_id: raise ValueError("task_id must be provided to segment_video for path organization.") if not os.path.exists(video_path): # This video_path should already be task_id specific if download_video was used correctly raise FileNotFoundError(f"Video file not found: {video_path}") video_id = os.path.splitext(os.path.basename(video_path))[0] # frames_output_folder: data/frames/// task_video_frames_dir = os.path.join(BASE_FRAMES_DATA_DIR, task_id, video_id) os.makedirs(task_video_frames_dir, exist_ok=True) frame_paths = [] try: cap = cv2.VideoCapture(video_path) if not cap.isOpened(): raise IOError(f"Could not open video file: {video_path}") fps = cap.get(cv2.CAP_PROP_FPS) if fps == 0: print(f"Warning: Could not get FPS for {video_path}. Assuming 30 FPS.") fps = 30 # Default if FPS is not available frame_interval = int(fps / frames_per_second) if frame_interval == 0: frame_interval = 1 # Ensure at least one frame is processed if frames_per_second > fps frame_count = 0 saved_frame_count = 0 while True: ret, frame = cap.read() if not ret: break if frame_count % frame_interval == 0: frame_filename = os.path.join(task_video_frames_dir, f"frame_{saved_frame_count:04d}.png") cv2.imwrite(frame_filename, frame) frame_paths.append(frame_filename) saved_frame_count += 1 frame_count += 1 except cv2.error as e: print(f"OpenCV error processing video {video_path} for task {task_id}: {e}") raise except Exception as e: print(f"Error segmenting video {video_path} for task {task_id}: {e}") raise finally: if 'cap' in locals() and cap.isOpened(): cap.release() if not frame_paths: print(f"Warning: No frames were extracted from {video_path} (Task ID: {task_id}).") print(f"Segmented video {video_path} (Task ID: {task_id}). Extracted {len(frame_paths)} frames to {task_video_frames_dir}") return frame_paths