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
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
#!/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)