File size: 4,485 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
from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
from typing import Iterable

import torch
from PIL import Image
from torchvision import transforms

from .base import FingerprintSample


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


@dataclass
class NIST302Paths:
    """Root folders for three NIST SD302 subsets."""

    root_302a: str
    root_302b: str
    root_302d: str


class NIST302Loader:
    """Unified loader for NIST SD302 A/B/D variants.

    The loader parses metadata from path and filename patterns currently present
    under the workspace dataset tree.
    """

    def __init__(self, image_size: int = 224):
        self.transform = transforms.Compose(
            [
                transforms.Resize((image_size, image_size)),
                transforms.ToTensor(),
            ]
        )

    def discover(self, paths: NIST302Paths) -> list[dict[str, str]]:
        records: list[dict[str, str]] = []
        for root_str, dataset_name in [
            (paths.root_302a, "nist_sd302a"),
            (paths.root_302b, "nist_sd302b"),
            (paths.root_302d, "nist_sd302d"),
        ]:
            if not root_str:  # skip empty roots — Path("") resolves to cwd and scans everything
                continue
            records.extend(self._scan_subset(Path(root_str), dataset_name))
        return records

    def iter_samples(
        self, records: Iterable[dict[str, str]]
    ) -> Iterable[FingerprintSample]:
        for rec in records:
            image = Image.open(rec["image_path"]).convert("L")
            tensor = self.transform(image)
            yield {
                "image": tensor,
                "identity_id": rec["identity_id"],
                "finger_id": rec["finger_id"],
                "sensor_id": rec["sensor_id"],
                "dataset": rec["dataset"],
                "image_path": rec["image_path"],
            }

    def _scan_subset(self, subset_root: Path, dataset_name: str) -> list[dict[str, str]]:
        if not subset_root.exists():
            return []

        records: list[dict[str, str]] = []
        for path in sorted(subset_root.rglob("*")):
            if not path.is_file() or path.suffix.lower() not in IMAGE_EXTS:
                continue
            meta = self._parse_metadata(path, subset_root, dataset_name)
            if meta is not None:
                records.append(meta)
        return records

    @staticmethod
    def _parse_metadata(
        file_path: Path,
        subset_root: Path,
        dataset_name: str,
    ) -> dict[str, str] | None:
        rel_parts = file_path.relative_to(subset_root).parts
        stem_tokens = file_path.stem.split("_")
        # SD302-A filenames have 4 tokens: {subject}_{sensor}_{captype}_{finger}
        # SD302-B/D filenames have 5 tokens: {subject}_{sensor}_{dpi}_{captype}_{finger}
        if len(stem_tokens) < 4:
            return None

        identity_id = stem_tokens[0]
        # NIST SD302 identity IDs are 8-digit numbers; reject non-fingerprint files early
        if not (identity_id.isdigit() and len(identity_id) == 8):
            return None

        # Heuristic finger id from filename tail. This should be audited before
        # strict cross-sensor experiments, matching the plan's risk note.
        finger_token = stem_tokens[-1]
        finger_id = f"F{int(finger_token):02d}" if finger_token.isdigit() else finger_token

        # Sensor token is stabilized from the first 1-3 directory markers that
        # capture device/capture style differences.
        sensor_tokens = rel_parts[:-1]
        sensor_id = "_".join(sensor_tokens[:3]) if sensor_tokens else "unknown"

        return {
            "identity_id": identity_id,
            "finger_id": finger_id,
            "sensor_id": sensor_id,
            "dataset": dataset_name,
            "image_path": str(file_path),
        }


def to_batch(samples: list[FingerprintSample]) -> dict[str, torch.Tensor | list[str]]:
    """Collate helper for lists emitted by NIST302Loader.iter_samples."""

    images = torch.stack([s["image"] for s in samples], dim=0)
    return {
        "images": images,
        "identity_ids": [s["identity_id"] for s in samples],
        "finger_ids": [s["finger_id"] for s in samples],
        "sensor_ids": [s["sensor_id"] for s in samples],
        "datasets": [s["dataset"] for s in samples],
        "image_paths": [s["image_path"] for s in samples],
    }