File size: 6,759 Bytes
463a80f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97b37cd
 
 
463a80f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97b37cd
 
 
463a80f
97b37cd
463a80f
 
 
 
97b37cd
 
 
 
 
 
 
463a80f
 
 
 
 
 
 
 
0105ea4
463a80f
 
 
97b37cd
 
 
 
 
 
0105ea4
97b37cd
463a80f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
IPAD Dataset Loader for HuggingFace Infrastructure
Loads data from HF Hub and provides PyTorch DataLoader compatible interface
"""
import torch
from torch.utils.data import Dataset, DataLoader
import cv2
import numpy as np
from pathlib import Path
import zipfile
from huggingface_hub import hf_hub_download
import os
from typing import List, Tuple, Optional
import random

class IPADVideoDataset(Dataset):
    """
    IPAD Video Anomaly Detection Dataset

    Args:
        root_dir: Path to extracted dataset
        device_name: Device ID (e.g., "S01", "S02", ..., "S12")
        split: "train" or "test"
        clip_length: Number of frames per clip (default: 16)
        frame_size: Tuple of (height, width) for resizing (default: (256, 256))
        stride: Frame sampling stride (default: 1)
        normalize: Whether to normalize frames to [-1, 1]
    """

    def __init__(
        self,
        root_dir: str,
        device_name: str = "S01",
        split: str = "train",
        clip_length: int = 16,
        frame_size: Tuple[int, int] = (256, 256),
        stride: int = 1,
        normalize: bool = True
    ):
        self.root_dir = Path(root_dir)
        self.device_name = device_name
        self.split = split
        self.clip_length = clip_length
        self.frame_size = frame_size
        self.stride = stride
        self.normalize = normalize

        # Construct path to device frames
        # Note: The dataset uses "training" and "testing", not "train" and "test"
        split_folder = "training" if split == "train" else "testing"
        self.device_path = self.root_dir / device_name / split_folder / "frames"

        if not self.device_path.exists():
            raise ValueError(f"Dataset path not found: {self.device_path}")

        # Get all video directories
        self.video_dirs = sorted([d for d in self.device_path.iterdir() if d.is_dir()])

        # Build index of all valid clips
        self.clips = []
        for video_dir in self.video_dirs:
            frames = sorted(list(video_dir.glob("*.jpg")) + list(video_dir.glob("*.png")))
            num_frames = len(frames)

            # Create clips with stride
            for start_idx in range(0, num_frames - clip_length + 1, stride):
                self.clips.append({
                    'video_dir': video_dir,
                    'start_idx': start_idx,
                    'frames': frames[start_idx:start_idx + clip_length]
                })

        print(f"Loaded {len(self.clips)} clips from {device_name}/{split}")

    def __len__(self) -> int:
        return len(self.clips)

    def __getitem__(self, idx: int) -> torch.Tensor:
        clip_info = self.clips[idx]
        frames = []

        # Load and process each frame
        for frame_path in clip_info['frames']:
            frame = cv2.imread(str(frame_path))
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            frame = cv2.resize(frame, self.frame_size)

            # Normalize to [0, 1]
            frame = frame.astype(np.float32) / 255.0

            # Normalize to [-1, 1] if requested
            if self.normalize:
                frame = (frame - 0.5) / 0.5

            frames.append(frame)

        # Convert to tensor: [T, H, W, C] -> [C, T, H, W]
        frames = np.stack(frames, axis=0)  # [T, H, W, C]
        frames = torch.from_numpy(frames).permute(3, 0, 1, 2)  # [C, T, H, W]

        return frames


def download_and_extract_dataset(cache_dir: str = "./cache") -> Path:
    """
    Download IPAD dataset from HF Hub and extract it

    The zip contains: IPAD_dataset/S01/training/frames/...
    We return the path to IPAD_dataset directory

    Returns:
        Path to extracted dataset directory (IPAD_dataset)
    """
    cache_dir = Path(cache_dir)
    cache_dir.mkdir(exist_ok=True, parents=True)

    extracted_path = cache_dir / "IPAD_dataset"

    # Check if already extracted
    if extracted_path.exists() and (extracted_path / "S01" / "training" / "frames").exists():
        print(f"✅ Dataset already extracted at {extracted_path}")
        return extracted_path

    print("📥 Downloading dataset from HF Hub...")
    zip_path = hf_hub_download(
        repo_id="MSherbinii/ipad-industrial-anomaly",
        filename="ipad_dataset.zip",
        repo_type="dataset",
        cache_dir=str(cache_dir)
    )

    print(f"📦 Extracting dataset to {cache_dir}...")
    with zipfile.ZipFile(zip_path, 'r') as zip_ref:
        zip_ref.extractall(cache_dir)

    # Verify extraction
    if not extracted_path.exists():
        raise ValueError(f"Expected {extracted_path} after extraction, but not found")

    if not (extracted_path / "S01" / "training" / "frames").exists():
        raise ValueError(f"Dataset structure incorrect. Missing S01/training/frames in {extracted_path}")

    print(f"✅ Dataset extracted to {extracted_path}")
    return extracted_path


def create_dataloaders(
    dataset_path: str,
    device_name: str = "S01",
    batch_size: int = 4,
    num_workers: int = 4,
    clip_length: int = 16,
    frame_size: Tuple[int, int] = (256, 256)
) -> Tuple[DataLoader, DataLoader]:
    """
    Create train and test DataLoaders for a specific device

    Args:
        dataset_path: Path to extracted IPAD dataset
        device_name: Device ID (e.g., "S01")
        batch_size: Batch size for DataLoader
        num_workers: Number of worker processes
        clip_length: Frames per clip
        frame_size: Frame dimensions

    Returns:
        Tuple of (train_loader, test_loader)
    """
    train_dataset = IPADVideoDataset(
        root_dir=dataset_path,
        device_name=device_name,
        split="train",
        clip_length=clip_length,
        frame_size=frame_size,
        stride=clip_length // 2  # 50% overlap for training
    )

    test_dataset = IPADVideoDataset(
        root_dir=dataset_path,
        device_name=device_name,
        split="test",
        clip_length=clip_length,
        frame_size=frame_size,
        stride=clip_length  # No overlap for testing
    )

    train_loader = DataLoader(
        train_dataset,
        batch_size=batch_size,
        shuffle=True,
        num_workers=num_workers,
        pin_memory=True,
        drop_last=True
    )

    test_loader = DataLoader(
        test_dataset,
        batch_size=batch_size,
        shuffle=False,
        num_workers=num_workers,
        pin_memory=True,
        drop_last=False
    )

    return train_loader, test_loader


# Device name mappings
DEVICE_NAMES = [
    "S01", "S02", "S03", "S04", "S05", "S06",
    "S07", "S08", "S09", "S10", "S11", "S12",
    "R01", "R02", "R03", "R04"
]

SYNTHETIC_DEVICES = [f"S{i:02d}" for i in range(1, 13)]
REAL_DEVICES = [f"R{i:02d}" for i in range(1, 5)]