seglint 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,316 @@
1
+ """Statistical checks T001-T004.
2
+
3
+ T001 runs per sample on the extracted features; T002-T004 are dataset scope (pass 2) and only
4
+ read SampleRecords. Dataset-level findings are not tied to one file, so their `sample_id` is a
5
+ pseudo id: `split:<name>` or `split:<name>/class:<id>` (`dataset/class:<id>` without splits).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import math
11
+ from collections import Counter
12
+
13
+ import numpy as np
14
+
15
+ from seglint.checks._robust import robust_z
16
+ from seglint.checks.base import BaseCheck, register
17
+ from seglint.models import Issue, Severity
18
+
19
+
20
+ def _split_name(split: str | None) -> str:
21
+ return split if split else ""
22
+
23
+
24
+ def _pseudo_id(split: str, cls: int | None = None) -> str:
25
+ base = f"split:{split}" if split else "dataset"
26
+ return base if cls is None else f"{base}/class:{cls}"
27
+
28
+
29
+ def _pseudo(check: BaseCheck, split: str, message: str, score: float, cls=None, **data) -> Issue:
30
+ return Issue(
31
+ check.id,
32
+ check.default_severity,
33
+ _pseudo_id(split, cls),
34
+ split or None,
35
+ message,
36
+ max(0.0, min(1.0, score)),
37
+ data,
38
+ )
39
+
40
+
41
+ @register
42
+ class T001(BaseCheck):
43
+ id = "T001"
44
+ default_severity = Severity.WARNING
45
+
46
+ def run_record(self, ctx, record):
47
+ if ctx.config.allow_empty_masks:
48
+ return []
49
+ bg = ctx.config.background_index
50
+ if any(n > 0 and c != bg for c, n in record.class_pixel_counts.items()):
51
+ return []
52
+ return [
53
+ self.issue(
54
+ record,
55
+ "mask has no foreground pixels (only background/ignore); suspicious unless "
56
+ "negative samples are intentional (allow_empty_masks)",
57
+ 1.0,
58
+ )
59
+ ]
60
+
61
+
62
+ def _fg_share(ctx, record) -> float | None:
63
+ """Share of the image covered by foreground classes (everything except background and
64
+ ignore); None when there is no background class (dense labelling: not meaningful)."""
65
+ bg = ctx.config.background_index
66
+ if bg < 0 or not record.valid_labels:
67
+ return None
68
+ fg = sum(n for c, n in record.class_pixel_counts.items() if c != bg)
69
+ return fg / record.fine_area if record.fine_area else None
70
+
71
+
72
+ @register
73
+ class T005(BaseCheck):
74
+ """Near-empty mask: foreground covers 0 < share < near_empty_info_frac of the image.
75
+ WARNING below near_empty_warn_frac, else INFO. Absolute (fixed) thresholds; T001 covers 0."""
76
+
77
+ id = "T005"
78
+ default_severity = Severity.WARNING
79
+
80
+ def run_record(self, ctx, record):
81
+ share = _fg_share(ctx, record)
82
+ th = ctx.config.thresholds
83
+ if share is None or share <= 0 or share >= th.near_empty_info_frac:
84
+ return []
85
+ fg_px = round(share * record.fine_area)
86
+ return [
87
+ self.issue(
88
+ record,
89
+ f"mask is almost empty: foreground covers {share:.4%} of the image "
90
+ f"({fg_px} px); suspicious unless tiny objects are expected",
91
+ 1 - share / th.near_empty_info_frac,
92
+ severity=Severity.WARNING if share < th.near_empty_warn_frac else Severity.INFO,
93
+ foreground_frac=share,
94
+ foreground_px=fg_px,
95
+ threshold=th.near_empty_info_frac,
96
+ warn_threshold=th.near_empty_warn_frac,
97
+ )
98
+ ]
99
+
100
+
101
+ @register
102
+ class T006(BaseCheck):
103
+ """Mask covers (almost) the whole image: foreground share >= full_mask_info_frac. WARNING from
104
+ full_mask_warn_frac, else INFO. Absolute (fixed) thresholds."""
105
+
106
+ id = "T006"
107
+ default_severity = Severity.WARNING
108
+
109
+ def run_record(self, ctx, record):
110
+ share = _fg_share(ctx, record)
111
+ th = ctx.config.thresholds
112
+ if share is None or share < th.full_mask_info_frac:
113
+ return []
114
+ return [
115
+ self.issue(
116
+ record,
117
+ f"mask covers {share:.1%} of the image; suspicious (is the background missing?)",
118
+ 0.5
119
+ + 0.5
120
+ * min(
121
+ 1.0, (share - th.full_mask_info_frac) / max(1e-9, 1 - th.full_mask_info_frac)
122
+ ),
123
+ severity=Severity.WARNING if share >= th.full_mask_warn_frac else Severity.INFO,
124
+ foreground_frac=share,
125
+ threshold=th.full_mask_info_frac,
126
+ warn_threshold=th.full_mask_warn_frac,
127
+ )
128
+ ]
129
+
130
+
131
+ def _class_universe(ctx, records) -> list[int]:
132
+ seen = {c for r in records for c in r.class_pixel_counts}
133
+ return sorted(seen | set(ctx.config.classes))
134
+
135
+
136
+ @register
137
+ class T002(BaseCheck):
138
+ id = "T002"
139
+ default_severity = Severity.WARNING
140
+ scope = "dataset"
141
+
142
+ def run_dataset(self, ctx, records):
143
+ recs = [r for r in records if r.valid_labels]
144
+ if not recs:
145
+ return []
146
+ th = ctx.config.thresholds
147
+ per_split: dict[str, Counter] = {}
148
+ for r in recs:
149
+ per_split.setdefault(_split_name(r.split), Counter()).update(r.class_pixel_counts)
150
+ classes = _class_universe(ctx, recs)
151
+ issues: list[Issue] = []
152
+ for c in classes: # declared classes that never appear anywhere: one finding
153
+ if all(o.get(c, 0) == 0 for o in per_split.values()):
154
+ msg = f"declared class {c} never appears in the dataset (suspicious)"
155
+ issues.append(_pseudo(self, "", msg, 1.0, c, pixels=0, fraction=0.0))
156
+ for split, counts in sorted(per_split.items()):
157
+ total = sum(counts.values())
158
+ for c in classes:
159
+ px = counts.get(c, 0)
160
+ elsewhere = [s for s, o in per_split.items() if s != split and o.get(c, 0) > 0]
161
+ where = f"split {split!r}" if split else "the dataset"
162
+ if px == 0:
163
+ if elsewhere:
164
+ names = ", ".join(repr(s) for s in sorted(elsewhere))
165
+ msg = f"class {c} never appears in {where} (present in: {names})"
166
+ issues.append(
167
+ _pseudo(
168
+ self, split, msg + " (suspicious)", 1.0, c, pixels=0, fraction=0.0
169
+ ) # fmt: skip
170
+ )
171
+ continue
172
+ frac = px / total if total else 0.0
173
+ limit = th.for_class(c, "rare_class_pixel_frac")
174
+ if frac < limit:
175
+ score = 0.5 + 0.5 * min(1.0, 1 - frac / limit)
176
+ issues.append(
177
+ _pseudo(
178
+ self,
179
+ split,
180
+ f"class {c} is very rare in {where}: {frac:.3%} of labelled pixels "
181
+ f"(limit {limit:.3%}) (suspicious)",
182
+ score,
183
+ c,
184
+ pixels=px,
185
+ fraction=frac,
186
+ )
187
+ )
188
+ return issues
189
+
190
+
191
+ def resolution_outliers(records, th) -> tuple[dict[int, list[str]], dict[int, float], tuple]:
192
+ """Indices of records whose image size/aspect is a robust outlier, the features that made
193
+ them one, their worst |z|, and the median (width, height)."""
194
+ if len(records) < 3:
195
+ return {}, {}, (0, 0)
196
+ h = np.array([r.height for r in records], dtype=np.float64)
197
+ w = np.array([r.width for r in records], dtype=np.float64)
198
+ feats = {"area": np.log(h * w), "aspect": np.log(w / h)}
199
+ min_dev = math.log1p(th.resolution_min_rel_dev)
200
+ flagged: dict[int, list[str]] = {}
201
+ worst: dict[int, float] = {}
202
+ for name, x in feats.items():
203
+ z = robust_z(x)
204
+ dev = np.abs(x - np.median(x))
205
+ for i in np.flatnonzero((np.abs(z) > th.resolution_mad_z) & (dev >= min_dev)):
206
+ flagged.setdefault(int(i), []).append(name)
207
+ worst[int(i)] = max(worst.get(int(i), 0.0), float(abs(z[i])))
208
+ return flagged, worst, (int(np.median(w)), int(np.median(h)))
209
+
210
+
211
+ @register
212
+ class T003(BaseCheck):
213
+ """Resolution outliers. A PROFILE check: off by default; the resolution spread is reported
214
+ as a dataset-profile fact instead (image size says nothing about mask quality)."""
215
+
216
+ id = "T003"
217
+ default_severity = Severity.INFO
218
+ scope = "dataset"
219
+ profile = True
220
+
221
+ def run_dataset(self, ctx, records):
222
+ if len(records) < 3:
223
+ return []
224
+ th = ctx.config.thresholds
225
+ flagged, worst, med = resolution_outliers(records, th)
226
+ return [
227
+ self.issue(
228
+ records[i],
229
+ f"resolution {records[i].width}x{records[i].height} is an outlier "
230
+ f"({'/'.join(names)}; median {med[0]}x{med[1]})",
231
+ worst[i] / (2 * th.resolution_mad_z),
232
+ width=records[i].width,
233
+ height=records[i].height,
234
+ median_size=list(med),
235
+ robust_z=worst[i],
236
+ )
237
+ for i, names in sorted(flagged.items())
238
+ ]
239
+
240
+
241
+ @register
242
+ class T004(BaseCheck):
243
+ """Class-mix drift of a split against `train` (or, without a train split, the other splits).
244
+
245
+ A split is reported when a Welch z-test on per-sample class fractions is significant for some
246
+ class (|z| > split_drift_z) and the pooled class distributions also differ by more than
247
+ split_drift_min_tv in total variation, so huge datasets do not flag trivial shifts.
248
+ """
249
+
250
+ id = "T004"
251
+ default_severity = Severity.INFO
252
+ scope = "dataset"
253
+
254
+ def run_dataset(self, ctx, records):
255
+ th = ctx.config.thresholds
256
+ recs = [
257
+ r for r in records if r.valid_labels and r.split and sum(r.class_pixel_counts.values())
258
+ ]
259
+ by_split: dict[str, list] = {}
260
+ for r in recs:
261
+ by_split.setdefault(r.split, []).append(r)
262
+ if len(by_split) < 2:
263
+ return []
264
+ classes = sorted({c for r in recs for c in r.class_pixel_counts})
265
+
266
+ def fractions(rs) -> np.ndarray:
267
+ f = np.zeros((len(rs), len(classes)))
268
+ for i, r in enumerate(rs):
269
+ tot = sum(r.class_pixel_counts.values())
270
+ for j, c in enumerate(classes):
271
+ f[i, j] = r.class_pixel_counts.get(c, 0) / tot
272
+ return f
273
+
274
+ issues = []
275
+ for split, rs in sorted(by_split.items()):
276
+ if split == "train" and "train" in by_split:
277
+ continue # train is the reference
278
+ ref_names = (
279
+ ["train"] if "train" in by_split else sorted(s for s in by_split if s != split)
280
+ )
281
+ ref = [r for s in ref_names for r in by_split[s]]
282
+ if len(rs) < th.min_split_samples or len(ref) < th.min_split_samples:
283
+ continue
284
+ fa, fb = fractions(rs), fractions(ref)
285
+ se = np.sqrt(fa.var(axis=0, ddof=1) / len(fa) + fb.var(axis=0, ddof=1) / len(fb))
286
+ diff = fa.mean(axis=0) - fb.mean(axis=0)
287
+ with np.errstate(divide="ignore", invalid="ignore"):
288
+ z = np.where(se > 0, diff / se, np.where(diff != 0, np.inf, 0.0))
289
+ pooled_a = np.array(
290
+ [sum(r.class_pixel_counts.get(c, 0) for r in rs) for c in classes], float
291
+ )
292
+ pooled_b = np.array(
293
+ [sum(r.class_pixel_counts.get(c, 0) for r in ref) for c in classes], float
294
+ )
295
+ p, q = pooled_a / pooled_a.sum(), pooled_b / pooled_b.sum()
296
+ tv = float(np.abs(p - q).sum() / 2)
297
+ top = int(np.argmax(np.abs(z)))
298
+ zmax = float(abs(z[top]))
299
+ if zmax <= th.split_drift_z or tv <= th.split_drift_min_tv:
300
+ continue
301
+ issues.append(
302
+ _pseudo(
303
+ self,
304
+ split,
305
+ f"class distribution of split {split!r} differs from "
306
+ f"{'/'.join(repr(s) for s in ref_names)} (total variation {tv:.3f}; largest "
307
+ f"shift: class {classes[top]}, {q[top]:.2%} -> {p[top]:.2%}, z={zmax:.1f})",
308
+ min(1.0, zmax / (2 * th.split_drift_z)),
309
+ tv=tv,
310
+ z=zmax,
311
+ reference=ref_names,
312
+ fractions={str(c): float(p[i]) for i, c in enumerate(classes)},
313
+ reference_fractions={str(c): float(q[i]) for i, c in enumerate(classes)},
314
+ )
315
+ )
316
+ return issues
@@ -0,0 +1,175 @@
1
+ """Structural checks S001-S008 (S004 is emitted by the pipeline itself, see pipeline.py).
2
+
3
+ All of them report facts about files (presence, size, mode, format, class ids), phrased as
4
+ "suspicious" because the dataset may be using an unusual-but-intentional convention.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import numpy as np
10
+
11
+ from seglint.checks.base import BaseCheck, register
12
+ from seglint.loaders.png_masks import LOSSY_FORMATS, inspect_mask, read_exif_orientation
13
+ from seglint.models import Severity
14
+
15
+ # PIL modes that carry class ids directly in a single channel.
16
+ SINGLE_CHANNEL_MODES = {"P", "L", "1", "I", "I;16", "I;16L", "I;16B"}
17
+ COLOR_MODES = {"RGB", "RGBA"}
18
+ MAX_LISTED_VALUES = 20
19
+
20
+
21
+ def _header(sample):
22
+ """Mask header info, or None when it cannot be read (S004 already covers that)."""
23
+ try:
24
+ return inspect_mask(sample.mask_path)
25
+ except Exception:
26
+ return None
27
+
28
+
29
+ @register
30
+ class S001(BaseCheck):
31
+ id = "S001"
32
+ default_severity = Severity.ERROR
33
+ run_on_incomplete = True
34
+
35
+ def run_sample(self, ctx, sample, image, mask):
36
+ if sample.mask_path is None and sample.ann_ref is None and sample.image_path is not None:
37
+ msg = "image has no matching mask file (suspicious; other naming? see --mask-suffix)"
38
+ return [self.issue(sample, msg, 1.0)]
39
+ return []
40
+
41
+
42
+ @register
43
+ class S002(BaseCheck):
44
+ id = "S002"
45
+ default_severity = Severity.ERROR
46
+ run_on_incomplete = True
47
+
48
+ def run_sample(self, ctx, sample, image, mask):
49
+ if sample.image_path is None and (sample.mask_path or sample.ann_ref) is not None:
50
+ msg = "mask has no matching image file (orphan; other naming? see --mask-suffix)"
51
+ return [self.issue(sample, msg, 1.0)]
52
+ return []
53
+
54
+
55
+ @register
56
+ class S003(BaseCheck):
57
+ id = "S003"
58
+ default_severity = Severity.ERROR
59
+
60
+ def run_sample(self, ctx, sample, image, mask):
61
+ ih, iw = image.shape[:2]
62
+ mh, mw = mask.shape[:2]
63
+ if (ih, iw) == (mh, mw):
64
+ return []
65
+ data = {"image_size": [iw, ih], "mask_size": [mw, mh]}
66
+ msg = f"image is {iw}x{ih} but mask is {mw}x{mh} (suspicious size mismatch)"
67
+ if (mh, mw) == (iw, ih):
68
+ msg += "; mask matches the image with width and height swapped (rotation/EXIF?)"
69
+ data["transposed"] = True
70
+ return [self.issue(sample, msg, 1.0, **data)]
71
+
72
+
73
+ @register
74
+ class S005(BaseCheck):
75
+ id = "S005"
76
+ default_severity = Severity.ERROR
77
+
78
+ def run_sample(self, ctx, sample, image, mask):
79
+ known = ctx.config.known_classes
80
+ if known is None or mask.ndim != 2: # no class list, or multichannel (see S006)
81
+ return []
82
+ info = _header(sample)
83
+ if info is not None and info.format in LOSSY_FORMATS:
84
+ return [] # compression noise creates bogus values; S008 already reports it
85
+ vals, counts = np.unique(mask, return_counts=True)
86
+ bad = {
87
+ int(v): int(c)
88
+ for v, c in zip(vals, counts, strict=True)
89
+ if int(v) != ctx.config.ignore_index and int(v) not in known
90
+ }
91
+ if not bad:
92
+ return []
93
+ shown = sorted(bad)[:MAX_LISTED_VALUES]
94
+ return [
95
+ self.issue(
96
+ sample,
97
+ f"mask contains values outside the declared classes: {shown} (suspicious)",
98
+ 1.0,
99
+ values=shown,
100
+ pixels={str(v): bad[v] for v in shown},
101
+ fraction=sum(bad.values()) / mask.size,
102
+ )
103
+ ]
104
+
105
+
106
+ @register
107
+ class S006(BaseCheck):
108
+ id = "S006"
109
+ default_severity = Severity.WARNING
110
+
111
+ def run_sample(self, ctx, sample, image, mask):
112
+ info = _header(sample)
113
+ mode = info.mode if info else None
114
+ if mode in COLOR_MODES and ctx.config.palette:
115
+ return [] # color mask mapped through the palette
116
+ if mask.ndim == 3 or (mode is not None and mode not in SINGLE_CHANNEL_MODES):
117
+ shown = mode or f"{mask.shape[-1]} channels"
118
+ hint = "pass --palette to map colors to classes" if mode in COLOR_MODES else ""
119
+ return [
120
+ self.issue(
121
+ sample,
122
+ f"unexpected mask mode {shown}; expected a single-channel/indexed mask. "
123
+ f"{hint}".strip(),
124
+ 1.0,
125
+ mode=mode,
126
+ )
127
+ ]
128
+ return []
129
+
130
+
131
+ @register
132
+ class S007(BaseCheck):
133
+ id = "S007"
134
+ default_severity = Severity.WARNING
135
+
136
+ def run_sample(self, ctx, sample, image, mask):
137
+ ih, iw = image.shape[:2]
138
+ if ih == iw or mask.shape[:2] != (ih, iw):
139
+ return [] # square images never change size; a mismatch is S003's business
140
+ try:
141
+ orientation = read_exif_orientation(sample.image_path)
142
+ except Exception:
143
+ return []
144
+ if orientation not in (5, 6, 7, 8):
145
+ return []
146
+ return [
147
+ self.issue(
148
+ sample,
149
+ f"image has EXIF orientation {orientation} (swaps width/height) but the mask "
150
+ f"only matches the raw {iw}x{ih} size; mask may be misaligned (suspicious)",
151
+ 1.0,
152
+ orientation=orientation,
153
+ raw_size=[iw, ih],
154
+ )
155
+ ]
156
+
157
+
158
+ @register
159
+ class S008(BaseCheck):
160
+ id = "S008"
161
+ default_severity = Severity.WARNING
162
+
163
+ def run_sample(self, ctx, sample, image, mask):
164
+ info = _header(sample)
165
+ if info is not None and info.format in LOSSY_FORMATS:
166
+ return [
167
+ self.issue(
168
+ sample,
169
+ f"mask is stored as {info.format}; lossy compression can corrupt class ids "
170
+ "(suspicious)",
171
+ 1.0,
172
+ format=info.format,
173
+ )
174
+ ]
175
+ return []