Download dataloader.py from bethgelab/video_saliency: direct link, hf CLI and curl.
- Browser
- Download file 16.5 kB
-
https://huggingface.co/datasets/bethgelab/video_saliency/resolve/main/dataloader.py
- Command line
-
hf download hf://datasets/bethgelab/video_saliency/dataloader.py
-
curl -L -o dataloader.py https://huggingface.co/datasets/bethgelab/video_saliency/resolve/main/dataloader.py
16.5 kB
| #!/usr/bin/env python3 | |
| """ | |
| PyTorch DataLoader for eye tracking dataset using Decord-GPU. | |
| Features: | |
| - Efficient video loading using Decord with GPU acceleration | |
| - Per-frame fixation loading from the published CSV layout | |
| (data/eyetracking/video_XXXX/video_XXXX_subject_Y.csv) | |
| - Flexible frame indexing (start, end, negative indexing) | |
| - Automatic padding for variable number of fixations per frame | |
| """ | |
| import os | |
| import numpy as np | |
| import torch | |
| from torch.utils.data import Dataset, DataLoader | |
| from pathlib import Path | |
| from typing import Tuple, Optional, List | |
| import pandas as pd | |
| try: | |
| from decord import VideoReader, gpu | |
| except ImportError: | |
| raise ImportError("Please install decord: pip install decord") | |
| class EyeTrackingDataset(Dataset): | |
| """ | |
| PyTorch Dataset for Eye tracking data with Decord-GPU video loading. | |
| Args: | |
| data_dir: Path to data directory (containing videos/, eyetracking/, and the split CSVs) | |
| split: 'train', 'val', or 'test' | |
| use_gpu: Whether to use GPU for video decoding (default: True) | |
| gpu_id: GPU device ID (default: 0) | |
| subject_mode: 'combined' to pool fixations from all subjects who viewed the video, | |
| or 'subject_X' (e.g. 'subject_3') to keep only one subject's stream | |
| cumulative_fixations: If True, load fixations from frame 0 to end_frame | |
| (e.g., for frames 15-20, return fixations 0-20) | |
| If False, only return fixations for requested frames (15-20) | |
| Useful for temporal models that need historical context | |
| """ | |
| def __init__( | |
| self, | |
| data_dir: str, | |
| split: str = 'train', | |
| use_gpu: bool = True, | |
| gpu_id: int = 0, | |
| subject_mode: str = 'combined', | |
| cumulative_fixations: bool = False, | |
| video_dir: str = None, | |
| csv_base_dir: str = None, | |
| ): | |
| self.data_dir = Path(data_dir) | |
| self.split = split | |
| self.use_gpu = use_gpu | |
| self.gpu_id = gpu_id | |
| self.subject_mode = subject_mode | |
| self.cumulative_fixations = cumulative_fixations | |
| self.video_dir = Path(video_dir) if video_dir else self.data_dir / 'videos' | |
| self.csv_base_dir = Path(csv_base_dir) if csv_base_dir else self.data_dir / 'eyetracking' | |
| # Get list of videos from CSV file (not from directories!) | |
| split_csv = self.data_dir / f"{split}_videos.csv" | |
| if not split_csv.exists(): | |
| raise FileNotFoundError(f"Split CSV file not found: {split_csv}") | |
| split_df = pd.read_csv(split_csv) | |
| self.video_names = split_df['video'].tolist() | |
| # Store video paths for easy access | |
| self.video_paths = [self.video_dir / f"{name}.mp4" for name in self.video_names] | |
| # Create video reader context (GPU or CPU) | |
| if use_gpu: | |
| self.ctx = gpu(gpu_id) | |
| else: | |
| self.ctx = None | |
| print(f"Loaded {len(self.video_names)} videos from {split} split") | |
| print(f"Using {'GPU' if use_gpu else 'CPU'} for video decoding") | |
| print(f"Subject mode: {subject_mode}") | |
| def __len__(self) -> int: | |
| return len(self.video_names) | |
| def _get_video_reader(self, video_idx: int) -> VideoReader: | |
| """Create a VideoReader for the given video index.""" | |
| video_path = self.video_paths[video_idx] | |
| if not video_path.exists(): | |
| raise FileNotFoundError(f"Video not found: {video_path}") | |
| if self.use_gpu: | |
| vr = VideoReader(str(video_path), ctx=self.ctx) | |
| else: | |
| vr = VideoReader(str(video_path)) | |
| return vr | |
| def _load_fixations( | |
| self, | |
| video_idx: int, | |
| start_frame: int, | |
| end_frame: int | |
| ) -> np.ndarray: | |
| """ | |
| Load fixations for the specified frame range from the per-subject CSVs at | |
| ``{csv_base_dir}/{video_name}/{video_name}_subject_*.csv``. | |
| Empty cells in the gaze-coordinate columns are read as NaN by pandas; out-of-screen | |
| samples (x outside [0, 1920] or y outside [0, 1080]) are also dropped. Both kinds of | |
| invalid samples are excluded from the returned tensor. | |
| If cumulative_fixations=True, loads from frame 0 to end_frame. | |
| If cumulative_fixations=False, loads from start_frame to end_frame. | |
| Returns: | |
| np.ndarray of shape (num_frames, max_fixations, 2) | |
| Padded with -1 where there are fewer fixations | |
| """ | |
| video_name = self.video_names[video_idx] | |
| csv_dir = self.csv_base_dir / video_name | |
| if not csv_dir.exists(): | |
| raise FileNotFoundError(f"CSV directory not found: {csv_dir}") | |
| # Determine actual frame range to load | |
| if self.cumulative_fixations: | |
| actual_start = 0 | |
| actual_end = end_frame | |
| else: | |
| actual_start = start_frame | |
| actual_end = end_frame | |
| # Get CSV files | |
| csv_files = sorted(csv_dir.glob("*.csv")) | |
| # Filter by subject_mode if needed | |
| if self.subject_mode != 'combined': | |
| subject_id = self.subject_mode.split('_')[-1] | |
| csv_files = [f for f in csv_files if f.stem.endswith(f'_{subject_id}')] | |
| if len(csv_files) == 0: | |
| # No CSV files, return empty fixations | |
| num_frames = actual_end - actual_start | |
| return np.full((num_frames, 1, 2), -1.0, dtype=np.float32) | |
| # Process each CSV file | |
| all_fixations_per_frame = {} | |
| RESOLUTION = (1920, 1080) | |
| for csv_file in csv_files: | |
| try: | |
| df = pd.read_csv(csv_file) | |
| df['left_x'] = df['left_x'].astype(float) | |
| df['left_y'] = df['left_y'].astype(float) | |
| df['frames'] = df['frames'].astype(float) | |
| # Filter invalid coordinates | |
| df.loc[(df['left_x'] <= 0) | (df['left_x'] >= RESOLUTION[0]), 'left_x'] = np.nan | |
| df.loc[(df['left_y'] <= 0) | (df['left_y'] >= RESOLUTION[1]), 'left_y'] = np.nan | |
| # Group by frame | |
| for frame_idx in range(actual_start, actual_end): | |
| frame_samples = df[(df['frames'] >= frame_idx) & (df['frames'] < frame_idx + 1)] | |
| for _, row in frame_samples.iterrows(): | |
| if not np.isnan(row['left_x']) and not np.isnan(row['left_y']): | |
| if frame_idx not in all_fixations_per_frame: | |
| all_fixations_per_frame[frame_idx] = [] | |
| all_fixations_per_frame[frame_idx].append((row['left_x'], row['left_y'])) | |
| except Exception as e: | |
| print(f"Warning: Error loading CSV {csv_file}: {e}") | |
| continue | |
| # Convert to padded array | |
| frame_fixations = [] | |
| max_num_fixations = 0 | |
| for frame_idx in range(actual_start, actual_end): | |
| if frame_idx in all_fixations_per_frame: | |
| fixations = np.array(all_fixations_per_frame[frame_idx], dtype=np.float32) | |
| frame_fixations.append(fixations) | |
| max_num_fixations = max(max_num_fixations, len(fixations)) | |
| else: | |
| frame_fixations.append(np.array([]).reshape(0, 2)) | |
| # Ensure at least 1 fixation slot | |
| if max_num_fixations == 0: | |
| max_num_fixations = 1 | |
| # Pad to max fixations | |
| num_frames = len(frame_fixations) | |
| padded_fixations = np.full((num_frames, max_num_fixations, 2), -1.0, dtype=np.float32) | |
| for i, fixations in enumerate(frame_fixations): | |
| if len(fixations) > 0: | |
| padded_fixations[i, :len(fixations), :] = fixations | |
| return padded_fixations | |
| def __getitem__( | |
| self, | |
| index: Tuple[int, Optional[int], Optional[int]] | |
| ) -> Tuple[torch.Tensor, torch.Tensor]: | |
| """ | |
| Get video frames and fixations for the specified range. | |
| Args: | |
| index: Tuple of (video_idx, start_frame, end_frame) | |
| - video_idx: Index of video in dataset | |
| - start_frame: Starting frame (None = 0, negative = from end) | |
| - end_frame: Ending frame (None = last frame, negative = from end) | |
| Returns: | |
| video: Tensor of shape (num_frames, channels, height, width) | |
| fixations: Tensor of shape (num_frames, max_fixations, 2) | |
| Padded with -1 where there are no fixations | |
| """ | |
| if isinstance(index, int): | |
| # If just an integer, return the entire video | |
| video_idx = index | |
| start_frame = None | |
| end_frame = None | |
| else: | |
| video_idx, start_frame, end_frame = index | |
| # Create video reader | |
| vr = self._get_video_reader(video_idx) | |
| total_frames = len(vr) | |
| # Handle None and negative indexing | |
| if start_frame is None: | |
| start_frame = 0 | |
| elif start_frame < 0: | |
| start_frame = total_frames + start_frame | |
| if end_frame is None: | |
| end_frame = total_frames | |
| elif end_frame < 0: | |
| end_frame = total_frames + end_frame | |
| # Clamp to valid range | |
| start_frame = max(0, min(start_frame, total_frames - 1)) | |
| end_frame = max(start_frame + 1, min(end_frame, total_frames)) | |
| # Load video frames | |
| frame_indices = list(range(start_frame, end_frame)) | |
| frames = vr.get_batch(frame_indices).asnumpy() # Shape: (num_frames, H, W, C) | |
| # Convert to torch tensor and permute to (num_frames, C, H, W) | |
| video = torch.from_numpy(frames).permute(0, 3, 1, 2).float() | |
| # Normalize to [0, 1] | |
| video = video / 255.0 | |
| # Load fixations | |
| fixations_np = self._load_fixations(video_idx, start_frame, end_frame) | |
| fixations = torch.from_numpy(fixations_np).float() | |
| return video, fixations | |
| def get_video_info(self, video_idx: int) -> dict: | |
| """Get metadata about a video.""" | |
| vr = self._get_video_reader(video_idx) | |
| return { | |
| 'video_name': self.video_names[video_idx], | |
| 'num_frames': len(vr), | |
| 'fps': vr.get_avg_fps(), | |
| 'width': vr[0].shape[1], | |
| 'height': vr[0].shape[0], | |
| } | |
| class EyeTrackingCollator: | |
| """ | |
| Custom collate function for batching videos with different lengths. | |
| Pads videos and fixations to the same length within a batch. | |
| """ | |
| def __init__(self, padding_value: float = 0.0): | |
| self.padding_value = padding_value | |
| def __call__(self, batch: List[Tuple[torch.Tensor, torch.Tensor]]) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: | |
| """ | |
| Collate a batch of videos and fixations. | |
| Args: | |
| batch: List of (video, fixations) tuples | |
| Returns: | |
| videos: Tensor of shape (batch_size, max_frames, C, H, W) | |
| fixations: Tensor of shape (batch_size, max_frames, max_fixations, 2) | |
| lengths: Tensor of shape (batch_size,) with actual lengths | |
| """ | |
| videos = [item[0] for item in batch] | |
| fixations = [item[1] for item in batch] | |
| # Get maximum dimensions | |
| max_frames = max(v.shape[0] for v in videos) | |
| max_fixations = max(f.shape[1] for f in fixations) | |
| # Get video dimensions (assuming all videos have same H, W, C) | |
| C, H, W = videos[0].shape[1], videos[0].shape[2], videos[0].shape[3] | |
| batch_size = len(videos) | |
| # Pad videos | |
| padded_videos = torch.full( | |
| (batch_size, max_frames, C, H, W), | |
| self.padding_value, | |
| dtype=videos[0].dtype | |
| ) | |
| # Pad fixations | |
| padded_fixations = torch.full( | |
| (batch_size, max_frames, max_fixations, 2), | |
| -1.0, | |
| dtype=fixations[0].dtype | |
| ) | |
| # Store actual lengths | |
| lengths = torch.zeros(batch_size, dtype=torch.long) | |
| for i, (video, fix) in enumerate(zip(videos, fixations)): | |
| num_frames = video.shape[0] | |
| num_fix = fix.shape[1] | |
| padded_videos[i, :num_frames] = video | |
| padded_fixations[i, :num_frames, :num_fix] = fix | |
| lengths[i] = num_frames | |
| return padded_videos, padded_fixations, lengths | |
| def create_dataloader( | |
| data_dir: str, | |
| split: str = 'train', | |
| batch_size: int = 1, | |
| use_gpu: bool = True, | |
| gpu_id: int = 0, | |
| subject_mode: str = 'combined', | |
| num_workers: int = 4, | |
| shuffle: bool = True, | |
| collate_fn: Optional[callable] = None | |
| ) -> DataLoader: | |
| """ | |
| Create a DataLoader for the Eye tracking dataset. | |
| Args: | |
| data_dir: Path to transformed_data directory | |
| split: 'train', 'val', or 'test' | |
| batch_size: Batch size (default: 1) | |
| use_gpu: Whether to use GPU for video decoding | |
| gpu_id: GPU device ID | |
| subject_mode: 'combined' or 'subject_X' for per-subject fixations | |
| num_workers: Number of worker processes | |
| shuffle: Whether to shuffle data | |
| collate_fn: Custom collate function (default: EyeTrackingCollator) | |
| Returns: | |
| DataLoader instance | |
| """ | |
| dataset = EyeTrackingDataset( | |
| data_dir=data_dir, | |
| split=split, | |
| use_gpu=use_gpu, | |
| gpu_id=gpu_id, | |
| subject_mode=subject_mode | |
| ) | |
| if collate_fn is None: | |
| collate_fn = EyeTrackingCollator() | |
| dataloader = DataLoader( | |
| dataset, | |
| batch_size=batch_size, | |
| shuffle=shuffle, | |
| num_workers=num_workers, | |
| collate_fn=collate_fn, | |
| pin_memory=True if use_gpu else False | |
| ) | |
| return dataloader | |
| if __name__ == "__main__": | |
| # Example usage | |
| print("=" * 80) | |
| print("Eye Tracking Dataset - Example Usage") | |
| print("=" * 80) | |
| data_dir = Path(__file__).parent / "data" | |
| # Create dataset | |
| dataset = EyeTrackingDataset( | |
| data_dir=data_dir, | |
| split='train', | |
| use_gpu=False, | |
| gpu_id=0, | |
| subject_mode='combined' | |
| ) | |
| print(f"\nDataset size: {len(dataset)}") | |
| # Get info about first video | |
| info = dataset.get_video_info(0) | |
| print(f"\nFirst video info:") | |
| for key, value in info.items(): | |
| print(f" {key}: {value}") | |
| # Example 1: Load entire video | |
| print("\n" + "=" * 80) | |
| print("Example 1: Load entire video") | |
| print("=" * 80) | |
| video, fixations = dataset[0] | |
| print(f"Video shape: {video.shape}") # (num_frames, C, H, W) | |
| print(f"Fixations shape: {fixations.shape}") # (num_frames, max_fixations, 2) | |
| print(f"Video dtype: {video.dtype}, range: [{video.min():.3f}, {video.max():.3f}]") | |
| # Example 2: Load frame range (frames 0-30) | |
| print("\n" + "=" * 80) | |
| print("Example 2: Load frames 10-40") | |
| print("=" * 80) | |
| video, fixations = dataset[(0, 10, 40)] | |
| print(f"Video shape: {video.shape}") | |
| print(f"Fixations shape: {fixations.shape}") | |
| # Example 3: Load last 50 frames (negative indexing) | |
| print("\n" + "=" * 80) | |
| print("Example 3: Load last 50 frames (negative indexing)") | |
| print("=" * 80) | |
| video, fixations = dataset[(0, -50, None)] | |
| print(f"Video shape: {video.shape}") | |
| print(f"Fixations shape: {fixations.shape}") | |
| # Example 4: Create DataLoader with batching | |
| print("\n" + "=" * 80) | |
| print("Example 4: DataLoader with batching") | |
| print("=" * 80) | |
| # Custom dataset that returns tuples for the collator | |
| class TupleDataset(EyeTrackingDataset): | |
| def __init__(self, *args, frame_range=(0, 30), **kwargs): | |
| super().__init__(*args, **kwargs) | |
| self.frame_range = frame_range | |
| def __getitem__(self, idx): | |
| return super().__getitem__((idx, *self.frame_range)) | |
| tuple_dataset = TupleDataset( | |
| data_dir=data_dir, | |
| split='train', | |
| use_gpu=False, | |
| gpu_id=0, | |
| subject_mode='combined', | |
| frame_range=(10, 40) | |
| ) | |
| dataloader = DataLoader( | |
| tuple_dataset, | |
| batch_size=2, | |
| shuffle=False, | |
| num_workers=0, | |
| collate_fn=EyeTrackingCollator() | |
| ) | |
| # Get one batch | |
| for videos, fixations, lengths in dataloader: | |
| print(f"Batch videos shape: {videos.shape}") # (batch_size, max_frames, C, H, W) | |
| print(f"Batch fixations shape: {fixations.shape}") # (batch_size, max_frames, max_fixations, 2) | |
| print(f"Actual lengths: {lengths}") | |
| break | |
| print("\n" + "=" * 80) | |
| print("Examples completed successfully!") | |
| print("=" * 80) | |