File size: 9,075 Bytes
bb5e4ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Leak-free Kermany Pediatric Chest X-Ray dataset loader with Union-Find patient/MD5 grouping."""
from __future__ import annotations

import hashlib
import os
import re
from pathlib import Path
from typing import Iterator

import albumentations as A
import cv2
import numpy as np
import pandas as pd
from albumentations.pytorch import ToTensorV2
from PIL import Image
from sklearn.model_selection import StratifiedGroupKFold
from torch.utils.data import Dataset, WeightedRandomSampler

CLASS_NAMES = ["NORMAL", "PNEUMONIA"]
LABEL_MAP = {name: idx for idx, name in enumerate(CLASS_NAMES)}
IMG_SIZE = 224
IMAGENET_MEAN = [0.485, 0.456, 0.406]
IMAGENET_STD = [0.229, 0.224, 0.225]

DEFAULT_DATA_CANDIDATES = [
    r"D:\kaggle_cache\datasets\paultimothymooney\chest-xray-pneumonia\versions\2\chest_xray",
    r"D:\kaggle_cache\datasets\paultimothymooney\chest-xray-pneumonia\versions\1\chest_xray",
    r"D:\kaggle_cache\datasets\paultimothymooney\chest-xray-pneumonia\chest_xray",
]


def resolve_kermany_root(data_dir: str | os.PathLike[str] | None = None) -> Path:
    """Locate the `chest_xray` folder containing `train/`, `val/`, and `test/`."""
    candidates: list[Path] = []
    if data_dir:
        candidates.append(Path(data_dir))
    env_dir = os.environ.get("BIOHCL_DATA_DIR")
    if env_dir:
        candidates.append(Path(env_dir))
    candidates.extend(Path(p) for p in DEFAULT_DATA_CANDIDATES)

    for cand in candidates:
        if (cand / "train").is_dir() and (cand / "test").is_dir():
            return cand
        nested = cand / "chest_xray"
        if (nested / "train").is_dir() and (nested / "test").is_dir():
            return nested

    raise FileNotFoundError(
        "Could not locate Kermany `chest_xray` root with `train/` and `test/`. "
        "Pass `--data-dir` or set `BIOHCL_DATA_DIR`."
    )


def extract_base_patient_token(split: str, cls: str, filename: str) -> str:
    """Extract canonical patient token preserving Kermany split/series disambiguation.

    Kermany `test/PNEUMONIA/` restarts `person1..` numbering independently of `train/`,
    so `person` IDs are prefixed by `{split}_` while `NORMAL` `IM-` vs `NORMAL2-IM-`
    prefixes are already disjoint across splits.
    """
    m_person = re.match(r"^person(\d+)_", filename)
    if m_person:
        return f"{split}_person_{int(m_person.group(1))}"
    m_n2 = re.match(r"^NORMAL2-IM-(\d+)", filename)
    if m_n2:
        return f"NORMAL2-IM-{int(m_n2.group(1)):04d}"
    m_im = re.match(r"^IM-(\d+)", filename)
    if m_im:
        return f"IM-{int(m_im.group(1)):04d}"
    raise ValueError(f"Unrecognized Kermany filename pattern: {split}/{cls}/{filename}")


def compute_md5(path: Path) -> str:
    h = hashlib.md5()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(65536), b""):
            h.update(chunk)
    return h.hexdigest()


class _UnionFind:
    def __init__(self, n: int):
        self.parent = list(range(n))

    def find(self, x: int) -> int:
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]
            x = self.parent[x]
        return x

    def union(self, a: int, b: int) -> None:
        ra, rb = self.find(a), self.find(b)
        if ra != rb:
            self.parent[rb] = ra


def _gather_raw_split(root: Path, split: str) -> pd.DataFrame:
    rows = []
    exts = {".jpeg", ".jpg", ".png"}
    for cls in CLASS_NAMES:
        cls_dir = root / split / cls
        if not cls_dir.is_dir():
            continue
        for p in sorted(cls_dir.iterdir()):
            if p.is_file() and p.suffix.lower() in exts:
                rows.append(
                    {
                        "path": str(p),
                        "filename": p.name,
                        "split_orig": split,
                        "label_name": cls,
                        "label": LABEL_MAP[cls],
                        "raw_patient": extract_base_patient_token(split, cls, p.name),
                        "md5": compute_md5(p),
                    }
                )
    return pd.DataFrame(rows)


def assign_union_find_groups(df: pd.DataFrame) -> pd.DataFrame:
    """Merge records sharing either `raw_patient` OR exact byte `md5` before splitting."""
    df = df.reset_index(drop=True).copy()
    uf = _UnionFind(len(df))
    seen_patient: dict[str, int] = {}
    seen_md5: dict[str, int] = {}
    for idx, row in df.iterrows():
        pat = row["raw_patient"]
        md5 = row["md5"]
        if pat in seen_patient:
            uf.union(idx, seen_patient[pat])
        else:
            seen_patient[pat] = idx
        if md5 in seen_md5:
            uf.union(idx, seen_md5[md5])
        else:
            seen_md5[md5] = idx

    roots = [uf.find(i) for i in range(len(df))]
    root_to_gid = {r: f"G{i:04d}" for i, r in enumerate(sorted(set(roots)))}
    df["group_id"] = [root_to_gid[r] for r in roots]
    return df


def load_kermany_dataframes(
    data_dir: str | os.PathLike[str] | None = None,
) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, int]]:
    """Load `train+val` (grouped via Union-Find) and untouched official `test/`."""
    root = resolve_kermany_root(data_dir)
    df_train_raw = _gather_raw_split(root, "train")
    df_val_raw = _gather_raw_split(root, "val")
    df_trainval = pd.concat([df_train_raw, df_val_raw], ignore_index=True)
    df_trainval = assign_union_find_groups(df_trainval)

    df_test = _gather_raw_split(root, "test")
    df_test = assign_union_find_groups(df_test)

    assert len(set(df_trainval["md5"]) & set(df_test["md5"])) == 0, (
        "DATA LEAKAGE: Cross-split exact MD5 collision detected between train+val and test!"
    )
    meta = {
        "trainval_images": len(df_trainval),
        "trainval_groups": df_trainval["group_id"].nunique(),
        "test_images": len(df_test),
        "test_groups": df_test["group_id"].nunique(),
    }
    return df_trainval, df_test, meta


def iter_patient_grouped_folds(
    df_trainval: pd.DataFrame, n_splits: int = 5, shuffle: bool = True, random_state: int = 42
) -> Iterator[tuple[int, pd.DataFrame, pd.DataFrame]]:
    """Yield `(fold_idx, df_tr, df_va)` with strict patient-group & MD5 non-overlap assertions."""
    sgkf = StratifiedGroupKFold(n_splits=n_splits, shuffle=shuffle, random_state=random_state)
    for fold_idx, (tr_idx, va_idx) in enumerate(
        sgkf.split(df_trainval, df_trainval["label"], df_trainval["group_id"])
    ):
        df_tr = df_trainval.iloc[tr_idx].reset_index(drop=True)
        df_va = df_trainval.iloc[va_idx].reset_index(drop=True)
        assert len(set(df_tr["group_id"]) & set(df_va["group_id"])) == 0, (
            f"Fold {fold_idx} patient group overlap detected!"
        )
        assert len(set(df_tr["md5"]) & set(df_va["md5"])) == 0, (
            f"Fold {fold_idx} exact MD5 duplicate overlap detected!"
        )
        yield fold_idx, df_tr, df_va


def get_transforms(img_size: int = IMG_SIZE) -> tuple[A.Compose, A.Compose]:
    train_transform = A.Compose(
        [
            A.Resize(img_size, img_size),
            A.HorizontalFlip(p=0.5),
            A.Rotate(limit=10, p=0.5, border_mode=cv2.BORDER_CONSTANT),
            A.Affine(
                scale=(0.95, 1.05),
                translate_percent=(-0.05, 0.05),
                rotate=0,
                p=0.3,
                border_mode=cv2.BORDER_CONSTANT,
            ),
            A.RandomBrightnessContrast(brightness_limit=0.15, contrast_limit=0.15, p=0.3),
            A.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD),
            ToTensorV2(),
        ]
    )
    eval_transform = A.Compose(
        [
            A.Resize(img_size, img_size),
            A.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD),
            ToTensorV2(),
        ]
    )
    return train_transform, eval_transform


def build_weighted_sampler(df_train: pd.DataFrame) -> WeightedRandomSampler:
    counts = np.bincount(df_train["label"].to_numpy(), minlength=2)
    class_weights = 1.0 / np.maximum(counts, 1)
    sample_weights = class_weights[df_train["label"].to_numpy()]
    return WeightedRandomSampler(
        weights=sample_weights.tolist(), num_samples=len(df_train), replacement=True
    )


def compute_inverse_class_weights(df_train: pd.DataFrame) -> list[float]:
    counts = np.bincount(df_train["label"].to_numpy(), minlength=2).astype(np.float64)
    total = counts.sum()
    weights = total / (2.0 * np.maximum(counts, 1.0))
    return weights.tolist()


class ChestXrayDataset(Dataset):
    """RGB Chest X-Ray PyTorch dataset backed by Albumentations transforms."""

    def __init__(self, df: pd.DataFrame, transform: A.Compose | None = None):
        self.df = df.reset_index(drop=True)
        self.transform = transform

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

    def __getitem__(self, idx: int):
        row = self.df.iloc[idx]
        img = np.array(Image.open(row["path"]).convert("RGB"))
        if self.transform is not None:
            img = self.transform(image=img)["image"]
        return img, int(row["label"])