""" PVSG dataset processing utilities """ import json import pickle import os import numpy as np from PIL import Image, ImageDraw from pathlib import Path from typing import List, Dict, Any, Tuple, Optional import cv2 PVSG_DATASETS = ["vidor", "ego4d", "epic_kitchen"] PVSG_ROOT = "/weka-train/jamesp/data/PVSG_dataset/" # PVSG_VIDEO_PATHS = { # "vidor": "/weka-train/jamesp/data/PVSG_dataset/vidor/frames", # "ego4d": "/weka-train/jamesp/data/PVSG_dataset/ego4d/frames", # "epic_kitchen": "/weka-train/jamesp/data/PVSG_dataset/epic_kitchen/frames" # } PVSG_ANNOTATIONS = "/weka-train/jamesp/data/PVSG_dataset/pvsg.json" PVSG_BBOX_DATA = "/weka-train/royg/pvsg/pvsg_bbox_data" class PVSGDataProcessor: """Process PVSG dataset for model evaluation""" def __init__(self): self.annotations = self._load_annotations() self.test_videos = self._get_test_split() self.train_videos = self._get_train_split() self.all_videos = self.test_videos + self.train_videos def _load_annotations(self) -> Dict: """Load PVSG annotations""" with open(PVSG_ANNOTATIONS, 'r') as f: return json.load(f) def _get_test_split(self) -> List[str]: """Get test video IDs""" return_ids = [] for vid_split in self.annotations['split']: return_ids.extend(self.annotations['split'][vid_split]['val']) return return_ids def _get_train_split(self) -> List[str]: """Get train video IDs""" return_ids = [] for vid_split in self.annotations['split']: return_ids.extend(self.annotations['split'][vid_split]['train']) return return_ids def get_video_data(self, video_id: str) -> Dict: """Get annotation data for a specific video""" data_dict = {item['video_id']: item for item in self.annotations['data']} ### ['video_id', 'meta', 'objects', 'relations', 'captions', 'qa_pairs', 'summary']) return data_dict.get(video_id, {}) def get_dataset_name(self, video_id: str) -> str: """Determine dataset name from video ID""" if video_id.startswith('P'): return 'epic_kitchen' elif len(video_id.split('_')) == 2 and video_id.split('_')[0].isdigit(): return 'vidor' else: return 'ego4d' def parse_video_id_by_split(self, dataset_name: str, split: str="test") -> List[str]: """given epic_kitchen, vidor, or ego4d, return the video ids from self.test_videos """ if split != "test": if dataset_name == "epic_kitchen": return [vid for vid in self.all_videos if vid.startswith('P')] elif dataset_name == "vidor": return [vid for vid in self.all_videos if len(vid.split('_')) == 2 and vid.split('_')[0].isdigit()] else: return [vid for vid in self.all_videos if not vid.startswith('P') and not ( len(vid.split('_')) == 2 and vid.split('_')[0].isdigit()) ] else: if dataset_name == "epic_kitchen": return [vid for vid in self.test_videos if vid.startswith('P')] elif dataset_name == "vidor": return [vid for vid in self.test_videos if len(vid.split('_')) == 2 and vid.split('_')[0].isdigit()] else: return [vid for vid in self.test_videos if not vid.startswith('P') and not ( len(vid.split('_')) == 2 and vid.split('_')[0].isdigit()) ] def load_bbox_data(self, video_id: str) -> Dict: """Load bounding box data for video""" dataset_name = self.get_dataset_name(video_id) bbox_file = os.path.join(PVSG_BBOX_DATA, dataset_name, f"{video_id}.pkl") if not os.path.exists(bbox_file): print(f"Warning: Bbox file not found: {bbox_file}") return {} with open(bbox_file, 'rb') as f: return pickle.load(f) def get_video_paths(self, video_ids: List[str]) -> List[str]: """Get paths to video files based on video IDs""" video_paths = [] for video_id in video_ids: dataset_name = self.get_dataset_name(video_id) if dataset_name == "epic_kitchen": video_dir = os.path.join(PVSG_ROOT, dataset_name, "videos") video_file = os.path.join(video_dir, f"{video_id}.MP4") else: # vidor or ego4d video_dir = os.path.join(PVSG_ROOT, dataset_name, "videos") video_file = os.path.join(video_dir, f"{video_id}.mp4") if os.path.exists(video_file): video_paths.append(video_file) else: print(f"Warning: Video file not found: {video_file}") return video_paths # def sample_frames(self, video_data: Dict, max_frames: int = None) -> List[int]: # """Sample frames from video based on strategy""" # if max_frames is None: # max_frames = MAX_FRAMES_PER_VIDEO # total_frames = video_data['meta']['num_frames'] # if total_frames <= max_frames: # return list(range(total_frames)) # if FRAME_SAMPLING_STRATEGY == "uniform": # step = total_frames // max_frames # return list(range(0, total_frames, step))[:max_frames] # elif FRAME_SAMPLING_STRATEGY == "random": # return sorted(np.random.choice(total_frames, max_frames, replace=False)) # else: # # Default to uniform # step = total_frames // max_frames # return list(range(0, total_frames, step))[:max_frames] # def get_frame_path(self, video_id: str, frame_idx: int) -> str: # """Get path to frame image""" # dataset_name = self.get_dataset_name(video_id) # video_dir = PVSG_VIDEO_PATHS[dataset_name] # frame_file = f"{str(frame_idx).zfill(4)}.png" # return os.path.join(video_dir, video_id, frame_file) # def create_bbox_overlay(self, image_path: str, bbox_data: Dict, frame_key: str, # objects_info: Dict) -> Image.Image: # """Create image with bounding box overlays""" # if not os.path.exists(image_path): # print(f"Warning: Image not found: {image_path}") # return None # image = Image.open(image_path).convert("RGB") # draw = ImageDraw.Draw(image) # if frame_key not in bbox_data: # return image # # Draw bounding boxes # for obj_id, bbox in bbox_data[frame_key].items(): # if obj_id in objects_info: # obj_category = objects_info[obj_id]['category'] # # Draw rectangle # draw.rectangle([bbox[0], bbox[1], bbox[2], bbox[3]], # outline='red', width=2) # # Add label # label = f"{obj_id}: {obj_category}" # draw.text((bbox[0], bbox[1] - 20), label, fill='red') # return image # def prepare_video_input(self, video_id: str, model_variant: str) -> Dict: # """Prepare video input for model inference""" # video_data = self.get_video_data(video_id) # if not video_data: # return None # bbox_data = self.load_bbox_data(video_id) # frame_indices = self.sample_frames(video_data) # # Create objects info mapping # objects_info = {obj['object_id']: obj for obj in video_data['objects']} # # Prepare frames with bounding boxes # frames = [] # valid_frames = [] # for frame_idx in frame_indices: # frame_path = self.get_frame_path(video_id, frame_idx) # frame_key = str(frame_idx).zfill(4) # if os.path.exists(frame_path): # frame_with_bbox = self.create_bbox_overlay( # frame_path, bbox_data, frame_key, objects_info # ) # if frame_with_bbox: # frames.append(frame_with_bbox) # valid_frames.append(frame_idx) # if not frames: # return None # # Prepare objects information text # objects_text = self._format_objects_info(objects_info, model_variant) # return { # 'video_id': video_id, # 'frames': frames, # 'frame_indices': valid_frames, # 'objects_info': objects_text, # 'raw_objects': objects_info, # 'relations': video_data.get('relations', []), # 'video_data': video_data, # 'bbox_data': bbox_data # } # def _format_objects_info(self, objects_info: Dict, model_variant: str) -> str: # """Format objects information based on model variant""" # if model_variant == "with_id": # # Include object IDs explicitly # objects_list = [] # for obj_id, obj_data in objects_info.items(): # objects_list.append(f"Object {obj_id}: {obj_data['category']}") # return "\\n".join(objects_list) # elif model_variant == "special_tokens": # # Use special token format # objects_list = [] # for obj_id, obj_data in objects_info.items(): # objects_list.append(f": {obj_data['category']}") # return "\\n".join(objects_list) # else: # without_id # # Just list categories without explicit IDs # categories = [obj_data['category'] for obj_data in objects_info.values()] # unique_categories = list(set(categories)) # return ", ".join(unique_categories) # def get_test_videos_subset(self, max_videos: int = None) -> List[str]: # """Get subset of test videos for evaluation""" # test_videos = self.test_videos.copy() # if max_videos: # test_videos = test_videos[:max_videos] # return test_videos # def create_video_tensor(self, frames: List[Image.Image]) -> List[Image.Image]: # """Convert frames to format expected by model""" # # For Qwen-VL, we can pass list of PIL images directly # return frames def extract_bbox_coordinates(mask_array: np.ndarray, object_id: int) -> Optional[Tuple[int, int, int, int]]: """Extract bounding box coordinates from mask""" object_mask = (mask_array == object_id) if not np.any(object_mask): return None coords = np.where(object_mask) y_coords, x_coords = coords[0], coords[1] x_min, x_max = x_coords.min(), x_coords.max() y_min, y_max = y_coords.min(), y_coords.max() return (int(x_min), int(y_min), int(x_max), int(y_max))