File size: 8,899 Bytes
dadf189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
252
253
254
255
256
257
258
259
260
261
262
from __future__ import annotations

"""Image-only dataset for the V2 (ViT + TRAM + GNN) pipeline.

Unlike ``FingerprintDataset`` which requires paired minutiae files,
this dataset loads only images + identity labels.  No minutiae extractor
is needed — the ViT backbone learns features end-to-end.

Supports directory layouts:
    1. ImageFolder:  ``root/identity_name/sample.{ext}``
    2. PolyU:        ``root/{first,second}_session/finger_sample.{ext}``
       (identity parsed from filename prefix before last underscore)
"""

import os
import random
from collections import defaultdict
from pathlib import Path

import torch
from torch.utils.data import Dataset, Sampler
from PIL import Image

from .augmentation import build_train_transform, build_val_transform


IMAGE_EXTS = {".bmp", ".png", ".tif", ".tiff", ".jpg", ".jpeg"}


def infer_device_from_name(path_or_name: str) -> str | None:
    stem = Path(path_or_name).stem
    parts = stem.split("_")
    if len(parts) < 4:
        return None
    token = parts[1]
    token_lower = token.lower()
    if token_lower in {"roll", "plain"}:
        return token_lower
    if token.isalpha() and len(token) <= 3:
        return token
    return None


class ImageDataset(Dataset):
    """Load fingerprint images with identity labels for metric learning.

    Returns:
        image: ``(1, H, W)`` normalised [0, 1]
        label: int
    """

    def __init__(
        self,
        image_dir: str,
        image_size: int = 224,
        augment: bool = True,
        repeat_factor: int = 1,
        augment_profile: str = "standard",
    ):
        super().__init__()
        self.transform = (
            build_train_transform(image_size, profile=augment_profile) if augment
            else build_val_transform(image_size)
        )
        self.repeat_factor = max(1, int(repeat_factor))

        self.samples: list[tuple[str, int]] = []   # (path, label)
        self.labels: list[int] = []
        self.devices: list[str | None] = []
        self.label_map: dict[str, int] = {}

        self._discover(image_dir)

    # ------------------------------------------------------------------
    def _discover(self, image_dir: str):
        root = Path(image_dir)
        if not root.exists():
            return

        subdirs = sorted([d for d in root.iterdir() if d.is_dir()])
        session_like = subdirs and all("session" in d.name.lower() for d in subdirs)

        if subdirs and not session_like:
            has_images = any(
                any(f.suffix.lower() in IMAGE_EXTS for f in d.iterdir() if f.is_file())
                for d in subdirs[:5]
            )
            if has_images:
                self._discover_imagefolder(root, subdirs)
                return

        self._discover_flat(root)

    def _append_sample(self, img_path: Path, label: int):
        self.samples.append((str(img_path), label))
        self.labels.append(label)
        self.devices.append(infer_device_from_name(img_path.name))

    def _discover_imagefolder(self, root: Path, subdirs: list[Path]):
        """``root/identity/sample.ext`` layout."""
        for idx, identity_dir in enumerate(subdirs):
            identity = identity_dir.name
            self.label_map[identity] = idx
            for img_file in sorted(identity_dir.iterdir()):
                if img_file.suffix.lower() in IMAGE_EXTS:
                    self._append_sample(img_file, idx)

    def _discover_flat(self, root: Path):
        """Flat/PolyU layout — parse identity from filename."""
        all_images: list[Path] = []
        for ext in IMAGE_EXTS:
            all_images.extend(root.rglob(f"*{ext}"))
        all_images = sorted(all_images)

        identity_of: dict[str, str] = {}
        for img in all_images:
            stem = img.stem
            parts = stem.rsplit("_", 1)
            identity = parts[0] if len(parts) > 1 else stem
            identity_of[str(img)] = identity

        unique_ids = sorted(set(identity_of.values()))
        id_to_label = {name: idx for idx, name in enumerate(unique_ids)}
        self.label_map = id_to_label

        for img in all_images:
            identity = identity_of[str(img)]
            label = id_to_label[identity]
            self._append_sample(img, label)

    # ------------------------------------------------------------------
    @property
    def num_classes(self) -> int:
        return len(self.label_map)

    def __len__(self) -> int:
        return len(self.samples) * self.repeat_factor

    def __getitem__(self, idx: int) -> dict[str, object]:
        idx = idx % len(self.samples)
        path, label = self.samples[idx]
        pil_img = Image.open(path).convert("L")
        image = self.transform(pil_img)
        return {"image": image, "label": label}


class ImageListDataset(Dataset):
    """Image dataset backed by an explicit list of ``(path, label)`` samples.

    Useful for continual learning where the effective training set is assembled
    dynamically from the current stage plus replay exemplars from previous stages.
    """

    def __init__(
        self,
        samples: list[tuple[str, int]],
        image_size: int = 224,
        augment: bool = True,
        augment_profile: str = "standard",
    ):
        super().__init__()
        self.transform = (
            build_train_transform(image_size, profile=augment_profile) if augment
            else build_val_transform(image_size)
        )
        self.samples = [(str(path), int(label)) for path, label in samples]
        self.labels = [label for _path, label in self.samples]
        self.devices = [infer_device_from_name(path) for path, _label in self.samples]
        unique_labels = sorted(set(self.labels))
        self.label_map = {str(label): label for label in unique_labels}

    @property
    def num_classes(self) -> int:
        return len(self.label_map)

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

    def __getitem__(self, idx: int) -> dict[str, object]:
        path, label = self.samples[idx]
        pil_img = Image.open(path).convert("L")
        image = self.transform(pil_img)
        return {"image": image, "label": label}


class PKSamplerV2(Sampler):
    """P identities × K samples per batch for metric learning."""

    def __init__(self, dataset: ImageDataset, p: int = 8, k: int = 4, device_aware: bool = False):
        self.p = p
        self.k = k
        self.device_aware = device_aware
        self._len = len(dataset) // (p * k)

        self.label_to_indices: dict[int, list[int]] = defaultdict(list)
        self.label_to_device_indices: dict[int, dict[str | None, list[int]]] = defaultdict(lambda: defaultdict(list))
        for idx, label in enumerate(dataset.labels):
            self.label_to_indices[label].append(idx)
            self.label_to_device_indices[label][dataset.devices[idx]].append(idx)

        self.labels = sorted(self.label_to_indices.keys())

    def _sample_indices(self, label: int) -> list[int]:
        indices = self.label_to_indices[label]
        if not self.device_aware:
            return (
                random.sample(indices, self.k)
                if len(indices) >= self.k
                else random.choices(indices, k=self.k)
            )

        by_device = self.label_to_device_indices[label]
        distinct_devices = [dev for dev in by_device if dev is not None]
        if len(distinct_devices) <= 1:
            return (
                random.sample(indices, self.k)
                if len(indices) >= self.k
                else random.choices(indices, k=self.k)
            )

        chosen: list[int] = []
        device_keys = distinct_devices.copy()
        random.shuffle(device_keys)
        for dev in device_keys:
            if len(chosen) >= self.k:
                break
            chosen.append(random.choice(by_device[dev]))

        remaining_pool = [idx for idx in indices if idx not in chosen]
        needed = self.k - len(chosen)
        if needed > 0:
            if len(remaining_pool) >= needed:
                chosen.extend(random.sample(remaining_pool, needed))
            else:
                chosen.extend(remaining_pool)
                if len(chosen) < self.k:
                    chosen.extend(random.choices(indices, k=self.k - len(chosen)))

        return chosen

    def __iter__(self):
        pool = self.labels.copy()
        random.shuffle(pool)
        ptr = 0

        for _ in range(self._len):
            if ptr + self.p > len(pool):
                pool = self.labels.copy()
                random.shuffle(pool)
                ptr = 0

            batch_labels = pool[ptr:ptr + self.p]
            ptr += self.p

            batch: list[int] = []
            for lbl in batch_labels:
                batch.extend(self._sample_indices(lbl))
            yield batch

    def __len__(self) -> int:
        return max(1, self._len)