File size: 10,929 Bytes
0cbed7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
"""
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_{obj_id}>: {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))