File size: 9,321 Bytes
7c9838c
 
 
 
 
 
5b5d469
0b0f04e
7c9838c
79fd89b
5b5d469
79fd89b
0b0f04e
 
 
5b5d469
7c9838c
5b5d469
79fd89b
5b5d469
7c9838c
5b5d469
 
 
7c9838c
 
0b0f04e
7c9838c
0b0f04e
7c9838c
0b0f04e
7c9838c
 
 
 
 
 
0b0f04e
7c9838c
 
 
0b0f04e
 
7c9838c
 
eba6f07
7c9838c
0b0f04e
 
 
 
7c9838c
 
 
 
 
 
 
 
 
0b0f04e
7c9838c
0b0f04e
7c9838c
 
eba6f07
7c9838c
eba6f07
7c9838c
 
 
 
 
79fd89b
7c9838c
79fd89b
 
0b0f04e
7c9838c
 
 
0b0f04e
7c9838c
 
 
 
 
 
 
 
 
 
 
 
 
 
5b5d469
7c9838c
 
5b5d469
 
7c9838c
 
 
 
 
 
 
 
 
 
 
 
 
5b5d469
 
7c9838c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79fd89b
5b5d469
79fd89b
7c9838c
 
 
 
 
 
 
 
 
 
 
79fd89b
5b5d469
7c9838c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79fd89b
7c9838c
 
 
 
 
 
5b5d469
7c9838c
 
0b0f04e
eba6f07
7c9838c
eba6f07
7c9838c
 
eba6f07
 
7c9838c
 
 
 
 
 
5b5d469
 
7c9838c
 
 
79fd89b
 
 
 
7c9838c
79fd89b
 
7c9838c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79fd89b
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
# ksdd2.py — KSDD2 loader (manual-download)
# Configs:
#  - image_only
#  - classification_from_masks       (recommended)
#  - classification_from_pyb         (auto-fallback to masks if all-positive)
#  - classification_from_pyb_any     (union, K=1)

from pathlib import Path
from typing import Dict, Iterable, Tuple, Optional, Set, List
import os
import re
import collections

import datasets

try:
    import pickletools  # safe scan
except Exception:
    pickletools = None
try:
    import pickle  # fallback
except Exception:
    pickle = None

IMG_EXTS = {".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff"}
MASK_DIR_CANDS = ["masks", "masks_defect", "ground_truth", "gt", "label", "labels"]

_DESCRIPTION = "KSDD2: Kolektor Surface-Defect Dataset 2. Binary classification via GT masks or weak splits."
_HOMEPAGE = "https://www.vicos.si/resources/kolektorsdd2/"
_CITATION = "KSDD2 by ViCoS Lab / Kolektor Group. See official page for citation."

def _is_gt_file(p: Path) -> bool:
    s = p.stem.lower()
    return s.endswith("_gt") or s.endswith("_mask")

def _to_num(s: str) -> Optional[int]:
    return int(s) if s.isdigit() else None

def _extract_numbers(stem: str):
    for m in re.finditer(r"\d+", stem):
        yield int(m.group(0))

class KSDD2Config(datasets.BuilderConfig):
    def __init__(self, mode="masks", min_votes: Optional[int]=None, **kw):
        super().__init__(version=datasets.Version("2.0.0"), **kw)
        self.mode = mode
        self.min_votes = min_votes  # used for pyb/pyb_any

class KSDD2(datasets.GeneratorBasedBuilder):
    BUILDER_CONFIG_CLASS = KSDD2Config
    BUILDER_CONFIGS = [
        KSDD2Config(name="image_only", description="Flat train/test, images only", mode="image_only"),
        KSDD2Config(name="classification_from_masks",
                    description="Label via *_GT.* masks (non-black=>defect). Excludes *_GT.* from inputs.",
                    mode="masks"),
        KSDD2Config(name="classification_from_pyb",
                    description="Weak splits via split_weakly_*.pyb (vote; fallback to masks on all-positive).",
                    mode="pyb", min_votes=2),
        KSDD2Config(name="classification_from_pyb_any",
                    description="Weak splits union (K=1).", mode="pyb_any", min_votes=1),
    ]
    DEFAULT_CONFIG_NAME = "classification_from_masks"

    # ---------- info ----------
    def _info(self):
        if self.config.mode == "image_only":
            feats = {"image": datasets.Image(), "path": datasets.Value("string")}
        else:
            feats = {
                "image": datasets.Image(),
                "label": datasets.ClassLabel(names=["good", "defect"]),
                "path": datasets.Value("string"),
            }
        return datasets.DatasetInfo(description=_DESCRIPTION,
                                    features=datasets.Features(feats),
                                    citation=_CITATION,
                                    homepage=_HOMEPAGE)

    # ---------- splits ----------
    def _split_generators(self, dl_manager):
        root = Path(self.config.data_dir or "")
        if not root.exists():
            raise FileNotFoundError(f"Please download KSDD2 and set data_dir. Looked for: {root}")
        gens = []
        for sp in ("train", "test"):
            if (root/sp).exists():
                gens.append(datasets.SplitGenerator(
                    name=getattr(datasets.Split, sp.upper()),
                    gen_kwargs={"root": root, "split": sp}))
        if not gens:
            gens.append(datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"root": root, "split": None}))
        return gens

    # ---------- helpers ----------
    def _iter_images(self, base: Path):
        for p in sorted(base.rglob("*")):
            if p.is_file() and p.suffix.lower() in IMG_EXTS:
                if _is_gt_file(p):
                    continue
                yield p

    def _find_mask_for(self, img_path: Path) -> Optional[Path]:
        for ext in IMG_EXTS:
            cand = img_path.with_name(img_path.stem + "_GT" + ext)
            if cand.exists():
                return cand
        parent = img_path.parent
        for d in MASK_DIR_CANDS:
            mdir = parent / d
            if mdir.exists():
                for ext in IMG_EXTS:
                    cand = mdir / (img_path.stem + "_GT" + ext)
                    if cand.exists():
                        return cand
        return None

    def _mask_is_defect(self, mask_path: Optional[Path]) -> int:
        if not mask_path or not mask_path.exists():
            return 0
        try:
            from PIL import Image
            with Image.open(mask_path) as im:
                im = im.convert("L")
                ex = im.getextrema()
                if not ex:
                    return 0
                lo, hi = ex
                return 1 if hi > 0 else 0
        except Exception:
            return 0

    # ---- PYB parsing (list of IDs) ----
    def _pyb_vote_defects(self, base: Path, min_votes: int, only_files: Optional[List[str]] = None) -> Set[str]:
        root = base.parent
        pybs = sorted(root.glob("split_weakly_*.pyb"))
        if only_files:
            allow = {x.lower().strip() for x in only_files}
            pybs = [p for p in pybs if p.name.lower() in allow]
        names_present: Set[str] = set()
        num_map: Dict[int, Set[str]] = {}
        for img in self._iter_images(base):
            bn = img.name.lower()
            names_present.add(bn)
            n = _to_num(img.stem)
            if n is not None and n >= 1000:
                num_map.setdefault(n, set()).add(bn)

        votes = collections.Counter()
        for f in pybs:
            data = f.read_bytes()
            ids: Set[int] = set()
            used_pickletools = False
            if pickletools is not None:
                try:
                    tmp: List[int] = []
                    cur = []
                    for op, arg, pos in pickletools.genops(data):
                        if op.name in ("BININT", "BININT1", "BININT2", "LONG1", "LONG4"):
                            try:
                                x = int(arg)
                                if x >= 1000:
                                    tmp.append(x)
                            except Exception:
                                pass
                        elif op.name in ("EMPTY_LIST", "APPENDS", "LIST"):
                            pass
                    used_pickletools = True
                except Exception:
                    used_pickletools = False
            if not used_pickletools and pickle is not None:
                try:
                    obj = pickle.loads(data)   # [ [(id, True), ...], [(id, True), ...] ]
                    for part in obj:
                        for pair in part:
                            if isinstance(pair, (list, tuple)) and pair:
                                n = int(pair[0])
                                if n >= 1000:
                                    ids.add(n)
                except Exception:
                    pass
            hit = set()
            for n in ids:
                hit.update(num_map.get(n, []))
            for bn in hit:
                votes[bn] += 1

        return {bn for bn, v in votes.items() if v >= max(1, min_votes)}

    # ---------- generator ----------
    def _generate_examples(self, root: Path, split: Optional[str]):
        base = root / split if split else root

        # A) images only
        if self.config.mode == "image_only":
            for p in self._iter_images(base):
                yield str(p), {"image": str(p), "path": str(p)}
            return

        # B) classification from masks
        if self.config.mode == "masks":
            for img in self._iter_images(base):
                mask = self._find_mask_for(img)
                label = self._mask_is_defect(mask)
                yield str(img), {"image": str(img), "label": label, "path": str(img)}
            return

        # C1) from pyb
        if self.config.mode in ("pyb", "pyb_any"):
            min_votes = self.config.min_votes or (2 if self.config.mode == "pyb" else 1)
            try:
                min_votes = int(os.getenv("KSDD2_MIN_VOTES", min_votes))
            except Exception:
                pass
            only = os.getenv("KSDD2_PYB_FILES", "")
            only_files = [s for s in only.split(",") if s.strip()] if only else None

            defect_names = self._pyb_vote_defects(base, min_votes=min_votes, only_files=only_files)


            total = good = defect = 0
            cache = []
            for img in self._iter_images(base):
                bn = img.name.lower()
                y = 1 if bn in defect_names else 0
                cache.append((img, y))
                total += 1; defect += y; good += (1 - y)

            if total > 0 and defect / total > 0.95:
                for img, _ in cache:
                    mask = self._find_mask_for(img)
                    y = self._mask_is_defect(mask)
                    yield str(img), {"image": str(img), "label": y, "path": str(img)}
            else:
                for img, y in cache:
                    yield str(img), {"image": str(img), "label": y, "path": str(img)}
            return