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.
seglint/maskthumb.py ADDED
@@ -0,0 +1,53 @@
1
+ """Small class-index thumbnails of masks, kept in the SampleRecord for the L004 comparison.
2
+
3
+ The mask is sampled with nearest neighbour at the centres of a THUMB x THUMB grid (symmetric under
4
+ flips and rotations, so a thumbnail of a flipped mask is the flipped thumbnail) and stored
5
+ zlib-compressed (a few hundred bytes for typical masks). Two masks of different sizes are
6
+ compared on this common grid.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import zlib
12
+
13
+ import numpy as np
14
+
15
+ THUMB = 128
16
+
17
+
18
+ def make_thumb(mask: np.ndarray) -> bytes:
19
+ """Compressed THUMB x THUMB int32 class-index thumbnail of an HxW mask (b"" if empty)."""
20
+ if mask.ndim != 2 or mask.size == 0:
21
+ return b""
22
+ h, w = mask.shape
23
+ rows = np.minimum(((np.arange(THUMB) + 0.5) * h / THUMB).astype(np.int64), h - 1)
24
+ cols = np.minimum(((np.arange(THUMB) + 0.5) * w / THUMB).astype(np.int64), w - 1)
25
+ return zlib.compress(
26
+ np.ascontiguousarray(mask[np.ix_(rows, cols)]).astype(np.int32).tobytes(), 3
27
+ )
28
+
29
+
30
+ def load_thumb(data: bytes) -> np.ndarray | None:
31
+ if not data:
32
+ return None
33
+ return np.frombuffer(zlib.decompress(data), np.int32).reshape(THUMB, THUMB)
34
+
35
+
36
+ def mask_iou(
37
+ a: np.ndarray, b: np.ndarray, background: int, ignore: int
38
+ ) -> tuple[float | None, dict[int, float]]:
39
+ """(micro IoU over the foreground classes, IoU per class) of two same-size thumbnails.
40
+
41
+ Foreground = every class except `background` and `ignore`. Micro IoU = sum of the per-class
42
+ intersections / sum of the per-class unions, so for one foreground class it is the ordinary
43
+ IoU. None when neither mask has foreground.
44
+ """
45
+ classes = sorted((set(np.unique(a)) | set(np.unique(b))) - {background, ignore})
46
+ inter = union = 0
47
+ per_class: dict[int, float] = {}
48
+ for c in classes:
49
+ ma, mb = a == c, b == c
50
+ i, u = int(np.count_nonzero(ma & mb)), int(np.count_nonzero(ma | mb))
51
+ inter, union = inter + i, union + u
52
+ per_class[int(c)] = i / u if u else 1.0
53
+ return (inter / union if union else None), per_class
seglint/models.py ADDED
@@ -0,0 +1,122 @@
1
+ """Core data model shared by loaders, checks, pipeline and reports."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from enum import IntEnum
7
+ from pathlib import Path
8
+
9
+
10
+ class Severity(IntEnum):
11
+ INFO = 0
12
+ WARNING = 1
13
+ ERROR = 2
14
+
15
+ @classmethod
16
+ def parse(cls, value: str) -> Severity:
17
+ try:
18
+ return cls[value.strip().upper()]
19
+ except KeyError:
20
+ raise ValueError(f"unknown severity: {value!r}") from None
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class Sample:
25
+ id: str # unique; relative stem, prefixed with "<split>/" when a split exists
26
+ split: str | None
27
+ image_path: Path | None
28
+ mask_path: Path | None
29
+ ann_ref: object | None = None
30
+
31
+
32
+ @dataclass
33
+ class Issue:
34
+ check_id: str
35
+ severity: Severity
36
+ sample_id: str
37
+ split: str | None
38
+ message: str
39
+ score: float = 1.0 # 0..1 suspicion degree, used for ranking
40
+ data: dict = field(default_factory=dict)
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class ComponentStat:
45
+ area: int
46
+ bbox: tuple[int, int, int, int] # x, y, w, h
47
+ perimeter: float # cv2.arcLength of the closed outer contour, in analysis-grid pixels
48
+ n_holes: int = 0
49
+ # pixel area of each hole: an enclosed non-class region that holds no ignore pixel
50
+ hole_areas: tuple[int, ...] = ()
51
+ # Length of the outer contour that runs along the image border (same unit as `perimeter`);
52
+ # border_perimeter / perimeter is the share of the outline that is cut by the image edge.
53
+ border_perimeter: float = 0.0
54
+ # True when a pixel of the component is next to (8-neighbourhood) an ignore pixel: a piece the
55
+ # ignore band cut off, not counted as a speck by G002.
56
+ touches_ignore: bool = False
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class ClassFeatures:
61
+ """Mask-only features of one foreground class in one sample (image independent).
62
+
63
+ All values are dimensionless/normalised, so they do not depend on the mask resolution:
64
+ `area_frac` = class pixels / image pixels (true-size mask); `cx`, `cy` = centroid of all class
65
+ pixels in [0, 1] (pixel centres, x to the right, y downwards); `n_objects` = connected
66
+ components larger than the speckle limit (speckles are G002, not objects). The shape values
67
+ describe the LARGEST component only (a fragment's convex hull says "fragmented", which is
68
+ G001's job) and are None when the class has no component above the speckle limit:
69
+ `solidity` = area / convex hull area (0..1), `elongation` = sqrt(l1/l2) of the coordinate
70
+ covariance (PCA axis ratio, >= 1), `circularity` = 4*pi*A/P^2 clipped to 0..1 (P = the
71
+ cv2.arcLength of the outer contour, same as ComponentStat.perimeter).
72
+ """
73
+
74
+ area_frac: float
75
+ cx: float
76
+ cy: float
77
+ n_objects: int
78
+ solidity: float | None = None
79
+ elongation: float | None = None
80
+ circularity: float | None = None
81
+
82
+
83
+ @dataclass
84
+ class SampleRecord:
85
+ """Features extracted in pass 1 so pass 2 never touches the disk."""
86
+
87
+ sample_id: str
88
+ split: str | None
89
+ height: int
90
+ width: int
91
+ class_pixel_counts: dict[int, int]
92
+ components: dict[int, list[ComponentStat]]
93
+ sha256: str
94
+ phash: int = 0
95
+ dhash: int = 0
96
+ # (pHash, dHash) of the 7 non-identity dihedral variants (hashing.DIHEDRAL_NAMES[1:])
97
+ hash_variants: tuple[tuple[int, int], ...] = ()
98
+ # class-index thumbnail of the mask (zlib, see maskthumb.py), for the L004 mask comparison
99
+ mask_thumb: bytes = b""
100
+ # Components are measured on an analysis grid (the mask downscaled with nearest-neighbour when
101
+ # its longer side exceeds `analysis_max_side`); 0 means "same as height/width".
102
+ comp_height: int = 0
103
+ comp_width: int = 0
104
+ # Components at the TRUE mask resolution, only filled when the analysis grid is a downscale
105
+ # and the grid showed a speckle or a small hole (candidate). G002/G003 then use these instead
106
+ # of the grid components, because nearest-neighbour downscaling splits connected masks into
107
+ # fragments (artifact). None: the grid components are used as they are.
108
+ fine_components: dict[int, list[ComponentStat]] | None = None
109
+ # False for multichannel masks without a palette: pixel counts/components are meaningless.
110
+ valid_labels: bool = True
111
+ # class id -> mask-only features of every foreground class present (see ClassFeatures)
112
+ class_features: dict[int, ClassFeatures] = field(default_factory=dict)
113
+
114
+ @property
115
+ def fine_area(self) -> int:
116
+ """Pixel count of the true-resolution mask."""
117
+ return self.height * self.width
118
+
119
+ @property
120
+ def grid_area(self) -> int:
121
+ """Pixel count of the grid the component areas are expressed in."""
122
+ return (self.comp_height or self.height) * (self.comp_width or self.width)
seglint/pipeline.py ADDED
@@ -0,0 +1,319 @@
1
+ """Two-pass runner: pass 1 (per sample, optional process pool), pass 2 (dataset scope)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import time
7
+ from collections.abc import Callable, Collection, Sequence
8
+ from concurrent.futures import ProcessPoolExecutor
9
+ from dataclasses import dataclass, field
10
+
11
+ import cv2
12
+ import numpy as np
13
+
14
+ from seglint.checks._limits import has_small_features
15
+ from seglint.checks.base import Check, CheckContext, checks_by_id
16
+ from seglint.config import Config
17
+ from seglint.features import extract_class_features
18
+ from seglint.hashing import image_hash_set
19
+ from seglint.loaders.coco import rasterize
20
+ from seglint.loaders.png_masks import load_image, load_mask
21
+ from seglint.maskthumb import make_thumb
22
+ from seglint.models import ComponentStat, Issue, Sample, SampleRecord, Severity
23
+
24
+
25
+ @dataclass
26
+ class PipelineResult:
27
+ samples: list[Sample]
28
+ records: list[SampleRecord] = field(default_factory=list)
29
+ issues: list[Issue] = field(default_factory=list)
30
+ # wall-clock seconds per stage (time.perf_counter); never part of a comparison
31
+ timing: dict[str, float] = field(default_factory=dict, compare=False, repr=False)
32
+
33
+
34
+ def _sha256(path) -> str:
35
+ h = hashlib.sha256()
36
+ with open(path, "rb") as f:
37
+ for chunk in iter(lambda: f.read(1 << 20), b""):
38
+ h.update(chunk)
39
+ return h.hexdigest()
40
+
41
+
42
+ def _present_classes(mask: np.ndarray) -> list[int]:
43
+ if mask.dtype == np.uint8:
44
+ return np.flatnonzero(np.bincount(mask.ravel(), minlength=1)).tolist()
45
+ return [int(v) for v in np.unique(mask)]
46
+
47
+
48
+ def class_counts(mask: np.ndarray, ignore_index: int) -> dict[int, int]:
49
+ """Pixel count per class id (ignore_index excluded)."""
50
+ if mask.size and int(mask.min()) >= 0 and int(mask.max()) < 1 << 16:
51
+ bc = np.bincount(mask.ravel())
52
+ return {int(k): int(bc[k]) for k in np.flatnonzero(bc) if int(k) != ignore_index}
53
+ vals, counts = np.unique(mask, return_counts=True)
54
+ return {int(v): int(c) for v, c in zip(vals, counts, strict=True) if int(v) != ignore_index}
55
+
56
+
57
+ def downscale_mask(mask: np.ndarray, max_side: int) -> np.ndarray:
58
+ """Nearest-neighbour downscale so the longer side is <= max_side (0 = disabled)."""
59
+ h, w = mask.shape
60
+ if max_side <= 0 or max(h, w) <= max_side:
61
+ return mask
62
+ f = max_side / max(h, w)
63
+ nw, nh = max(1, round(w * f)), max(1, round(h * f))
64
+ if mask.dtype not in (np.uint8, np.uint16, np.int16, np.int32):
65
+ mask = mask.astype(np.int32)
66
+ return cv2.resize(mask, (nw, nh), interpolation=cv2.INTER_NEAREST)
67
+
68
+
69
+ def _border_length(contour: np.ndarray, w: int, h: int) -> float:
70
+ """Arc length of the closed contour that runs along one image edge (both ends on that edge)."""
71
+ p = contour[:, 0, :].astype(np.int64)
72
+ if p[:, 0].min() > 0 and p[:, 1].min() > 0 and p[:, 0].max() < w - 1 and p[:, 1].max() < h - 1:
73
+ return 0.0
74
+ q = np.roll(p, -1, axis=0)
75
+ seg = np.hypot(*(q - p).T.astype(np.float64))
76
+ on_edge = np.zeros(len(p), bool)
77
+ for axis, edge in ((0, 0), (0, w - 1), (1, 0), (1, h - 1)):
78
+ on_edge |= (p[:, axis] == edge) & (q[:, axis] == edge)
79
+ return float(seg[on_edge].sum())
80
+
81
+
82
+ def extract_components(
83
+ mask: np.ndarray, ignore_index: int, skip: Collection[int] = ()
84
+ ) -> dict[int, list[ComponentStat]]:
85
+ """Per-class connected components (8-connectivity): area, bbox, perimeter, holes.
86
+
87
+ Perimeter is cv2.arcLength of the closed outer contour (contour points are boundary pixel
88
+ centres, so a w x h filled rectangle has perimeter 2*((w-1)+(h-1))). A hole is a 4-connected
89
+ non-class region that does not touch the image border and holds no ignore pixel (a void
90
+ region is not a gap in the annotation); its area is exact. `touches_ignore` marks components
91
+ next to an ignore pixel (8-neighbourhood).
92
+ """
93
+ out: dict[int, list[ComponentStat]] = {}
94
+ h, w = mask.shape
95
+ ignore = mask == ignore_index
96
+ has_ignore = bool(ignore.any())
97
+ near_ignore = (
98
+ cv2.dilate(ignore.astype(np.uint8), np.ones((3, 3), np.uint8)).astype(bool)
99
+ if has_ignore
100
+ else None
101
+ )
102
+ for cls in _present_classes(mask):
103
+ if cls == ignore_index or cls in skip:
104
+ continue
105
+ binm = (mask == cls).astype(np.uint8)
106
+ n, labels, stats, _ = cv2.connectedComponentsWithStats(binm, connectivity=8)
107
+ perim = [0.0] * n
108
+ bperim = [0.0] * n
109
+ holes: list[list[int]] = [[] for _ in range(n)]
110
+ contours, hier = cv2.findContours(binm, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
111
+ has_holes = False
112
+ for i, c in enumerate(contours):
113
+ if hier[0][i][3] == -1: # outer contour
114
+ x, y = c[0][0]
115
+ lab = int(labels[y, x])
116
+ perim[lab] += float(cv2.arcLength(c, True))
117
+ bperim[lab] += _border_length(c, w, h)
118
+ else:
119
+ has_holes = True
120
+ if has_holes:
121
+ nb, lb, sb, _ = cv2.connectedComponentsWithStats(1 - binm, connectivity=4)
122
+ void = np.bincount(lb[ignore], minlength=nb) > 0 if has_ignore else None
123
+ for j in range(1, nb):
124
+ x, y, bw, bh, area = (int(v) for v in sb[j])
125
+ if x == 0 or y == 0 or x + bw == w or y + bh == h:
126
+ continue # open to the outside: background, not a hole
127
+ if void is not None and void[j]:
128
+ continue # holds ignore pixels: a void region, not a hole
129
+ x0 = x + int(np.argmax(lb[y, x : x + bw] == j)) # first pixel of the top row
130
+ holes[int(labels[y - 1, x0])].append(area)
131
+ touch = np.bincount(labels[near_ignore], minlength=n) > 0 if has_ignore else None
132
+ out[cls] = [
133
+ ComponentStat(
134
+ int(stats[i, cv2.CC_STAT_AREA]),
135
+ tuple(int(stats[i, k]) for k in (0, 1, 2, 3)), # type: ignore[arg-type]
136
+ perim[i],
137
+ len(holes[i]),
138
+ tuple(holes[i]),
139
+ bperim[i],
140
+ bool(touch[i]) if touch is not None else False,
141
+ )
142
+ for i in range(1, n)
143
+ ]
144
+ return out
145
+
146
+
147
+ def build_record(
148
+ sample: Sample, mask: np.ndarray, cfg: Config, image: np.ndarray | None = None
149
+ ) -> SampleRecord:
150
+ """Extract shared features once; pHash/dHash come from `image` when it is given.
151
+
152
+ Class pixel counts use the true-size mask; components use the downscaled analysis grid.
153
+ """
154
+ multichannel = mask.ndim != 2
155
+ m2 = mask[..., 0] if multichannel else mask
156
+ pix = class_counts(m2, cfg.ignore_index)
157
+ comps: dict[int, list[ComponentStat]] = {}
158
+ fine: dict[int, list[ComponentStat]] | None = None
159
+ feats = {}
160
+ gh, gw = m2.shape
161
+ if not multichannel:
162
+ grid = downscale_mask(m2, cfg.analysis_max_side)
163
+ gh, gw = grid.shape
164
+ skip = () if cfg.background_index < 0 else (cfg.background_index,)
165
+ comps = extract_components(grid, cfg.ignore_index, skip)
166
+ feats = extract_class_features(grid, comps, cfg, pix, m2.shape[0] * m2.shape[1])
167
+ if grid.shape != m2.shape and has_small_features(cfg, comps, gh * gw):
168
+ # Confirm speckle/hole candidates at true resolution (the downscale can fragment a
169
+ # connected mask); only ~1 in 5 ISIC masks needs this extra pass.
170
+ fine = extract_components(m2, cfg.ignore_index, skip)
171
+ sha = _sha256(sample.image_path) if sample.image_path else ""
172
+ ph, dh, variants = image_hash_set(image) if image is not None else (0, 0, ())
173
+ thumb = make_thumb(m2) if not multichannel else b""
174
+ return SampleRecord(
175
+ sample.id, sample.split, m2.shape[0], m2.shape[1], pix, comps, sha, ph, dh, variants, thumb,
176
+ comp_height=gh, comp_width=gw, fine_components=fine, valid_labels=not multichannel,
177
+ class_features=feats,
178
+ ) # fmt: skip
179
+
180
+
181
+ def _process_sample(
182
+ s: Sample,
183
+ sample_checks: Sequence[Check],
184
+ cfg: Config,
185
+ ctx: CheckContext,
186
+ report_load_errors: bool,
187
+ ) -> tuple[SampleRecord | None, list[Issue]]:
188
+ issues: list[Issue] = []
189
+ image = mask = None
190
+ errs: list[str] = []
191
+ if s.image_path is not None:
192
+ try:
193
+ image = load_image(s.image_path)
194
+ except Exception as e: # corrupt file must not stop the scan
195
+ errs.append(f"image {s.image_path.name}: {e}")
196
+ if s.mask_path is None and s.ann_ref is not None: # COCO: rasterize the annotations
197
+ try:
198
+ mask = rasterize(s.ann_ref, cfg.ignore_index)
199
+ except Exception as e:
200
+ errs.append(f"annotations of {s.id}: {e}")
201
+ if s.mask_path is not None:
202
+ try:
203
+ mask = load_mask(s.mask_path, cfg.binary, cfg.palette or None, cfg.ignore_index)
204
+ except Exception as e:
205
+ errs.append(f"mask {s.mask_path.name}: {e}")
206
+ if errs:
207
+ ctx.load_errors[s.id] = "; ".join(errs)
208
+ if report_load_errors:
209
+ issues.append(
210
+ Issue(
211
+ "S004",
212
+ Severity.ERROR,
213
+ s.id,
214
+ s.split,
215
+ f"unreadable file: {errs[0]}",
216
+ 1.0,
217
+ {"errors": errs},
218
+ ) # fmt: skip
219
+ )
220
+ complete = image is not None and mask is not None
221
+ record = None
222
+ if complete:
223
+ try:
224
+ record = build_record(s, mask, cfg, image)
225
+ except Exception as e:
226
+ ctx.load_errors[s.id] = f"feature extraction failed: {e}"
227
+ for c in sample_checks:
228
+ if complete or c.run_on_incomplete:
229
+ issues.extend(c.run_sample(ctx, s, image, mask))
230
+ if record is not None and record.valid_labels:
231
+ issues.extend(c.run_record(ctx, record))
232
+ return record, issues
233
+
234
+
235
+ def _run_chunk(
236
+ samples: Sequence[Sample], check_ids: list[str], cfg: Config, report_load_errors: bool
237
+ ) -> tuple[list[SampleRecord], list[Issue], dict[str, str]]:
238
+ """Worker entry point (module level so it pickles under the Windows spawn start method)."""
239
+ ctx = CheckContext(cfg)
240
+ checks = checks_by_id(check_ids)
241
+ records: list[SampleRecord] = []
242
+ issues: list[Issue] = []
243
+ for s in samples:
244
+ rec, iss = _process_sample(s, checks, cfg, ctx, report_load_errors)
245
+ if rec is not None:
246
+ records.append(rec)
247
+ issues.extend(iss)
248
+ return records, issues, ctx.load_errors
249
+
250
+
251
+ def _poolable(checks: Sequence[Check]) -> bool:
252
+ """Workers re-import checks by id, so only built-in checks can run in a process pool."""
253
+ return all(type(c).__module__.startswith("seglint.checks.") for c in checks)
254
+
255
+
256
+ def run_pass1(
257
+ samples: Sequence[Sample],
258
+ checks: Sequence[Check],
259
+ cfg: Config,
260
+ report_load_errors: bool = True,
261
+ progress: Callable[[], None] | None = None,
262
+ workers: int = 1,
263
+ ) -> tuple[list[SampleRecord], list[Issue], CheckContext]:
264
+ """Per-sample pass. With workers > 1 samples go to a process pool in contiguous chunks and
265
+ results are concatenated in input order, so output is identical to workers=1."""
266
+ ctx = CheckContext(cfg)
267
+ sample_checks = [c for c in checks if c.scope == "sample"]
268
+ records: list[SampleRecord] = []
269
+ issues: list[Issue] = []
270
+ if workers > 1 and len(samples) > 1 and _poolable(sample_checks):
271
+ size = max(1, min(64, -(-len(samples) // (workers * 4))))
272
+ chunks = [samples[i : i + size] for i in range(0, len(samples), size)]
273
+ ids = [c.id for c in sample_checks]
274
+ with ProcessPoolExecutor(max_workers=workers) as pool:
275
+ futures = [pool.submit(_run_chunk, ch, ids, cfg, report_load_errors) for ch in chunks]
276
+ for fut in futures: # consumed in submission order => deterministic
277
+ r, i, errs = fut.result()
278
+ records += r
279
+ issues += i
280
+ ctx.load_errors.update(errs)
281
+ if progress:
282
+ progress()
283
+ return records, issues, ctx
284
+ for s in samples:
285
+ rec, iss = _process_sample(s, sample_checks, cfg, ctx, report_load_errors)
286
+ if rec is not None:
287
+ records.append(rec)
288
+ issues += iss
289
+ if progress:
290
+ progress()
291
+ return records, issues, ctx
292
+
293
+
294
+ def run_pass2(
295
+ records: Sequence[SampleRecord], checks: Sequence[Check], ctx: CheckContext
296
+ ) -> list[Issue]:
297
+ """Dataset-scope checks over SampleRecords only (no disk access)."""
298
+ issues: list[Issue] = []
299
+ for c in checks:
300
+ if c.scope == "dataset":
301
+ issues.extend(c.run_dataset(ctx, list(records)))
302
+ return issues
303
+
304
+
305
+ def run_pipeline(
306
+ samples: Sequence[Sample],
307
+ checks: Sequence[Check],
308
+ cfg: Config,
309
+ report_load_errors: bool = True,
310
+ workers: int = 1,
311
+ ) -> PipelineResult:
312
+ """Run pass 1 then pass 2; issues come back sorted by severity, then score (desc)."""
313
+ t0 = time.perf_counter()
314
+ records, issues, ctx = run_pass1(samples, checks, cfg, report_load_errors, workers=workers)
315
+ t1 = time.perf_counter()
316
+ issues += run_pass2(records, checks, ctx)
317
+ t2 = time.perf_counter()
318
+ issues.sort(key=lambda i: (-int(i.severity), -i.score, i.check_id, i.sample_id))
319
+ return PipelineResult(list(samples), records, issues, {"pass1_s": t1 - t0, "pass2_s": t2 - t1})
seglint/profile.py ADDED
@@ -0,0 +1,64 @@
1
+ """Dataset profile: facts about the dataset that are not mask-quality judgements.
2
+
3
+ Border contact (formerly the G004 finding) and the image-resolution spread (formerly T003) are
4
+ reported here as information. On Oxford-IIIT Pet G004 flagged 69.6% of the masks (pets are often
5
+ cropped by the frame), which is normal for that dataset and says nothing about the masks.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections import Counter
11
+ from typing import Any
12
+
13
+ import numpy as np
14
+
15
+ from seglint.checks.geometric import border_touch
16
+ from seglint.checks.statistical import resolution_outliers
17
+
18
+ BORDER_NOTE_FRAC = 0.5
19
+
20
+
21
+ def dataset_profile(records, cfg) -> dict[str, Any]:
22
+ recs = [r for r in records if r.valid_labels]
23
+ n = len(recs)
24
+ touching = sum(1 for r in recs if border_touch(cfg, r)[0])
25
+ frac = touching / n if n else 0.0
26
+ sizes = Counter((r.width, r.height) for r in records)
27
+ mp = np.array([r.width * r.height / 1e6 for r in records]) if records else np.array([0.0])
28
+ flagged, _, med = resolution_outliers(records, cfg.thresholds)
29
+ notes = []
30
+ if n and frac > BORDER_NOTE_FRAC:
31
+ notes.append(
32
+ f"{100 * frac:.0f}% of the masks touch the image border: objects may be cropped by "
33
+ "the frame; this can be normal for this dataset."
34
+ )
35
+ return {
36
+ "border_touch": {"n_samples": n, "n_touching": touching, "fraction": frac},
37
+ "resolution": {
38
+ "n_images": len(records),
39
+ "n_distinct_sizes": len(sizes),
40
+ "most_common": [[w, h, c] for (w, h), c in sizes.most_common(5)],
41
+ "median_size": list(med),
42
+ "megapixels": {
43
+ "min": float(mp.min()),
44
+ "median": float(np.median(mp)),
45
+ "max": float(mp.max()),
46
+ }, # fmt: skip
47
+ "n_outliers": len(flagged),
48
+ },
49
+ "notes": notes,
50
+ }
51
+
52
+
53
+ def profile_lines(profile: dict[str, Any]) -> list[str]:
54
+ """Plain-language lines for the CLI and the report."""
55
+ bt, res = profile["border_touch"], profile["resolution"]
56
+ lines = [
57
+ f"{100 * bt['fraction']:.1f}% of the masks touch the image border "
58
+ f"({bt['n_touching']} of {bt['n_samples']}).",
59
+ f"Resolution: {res['n_distinct_sizes']} distinct size(s) over {res['n_images']} images; "
60
+ f"median {res['median_size'][0]}x{res['median_size'][1]}, "
61
+ f"{res['megapixels']['min']:.2f}-{res['megapixels']['max']:.2f} MP; "
62
+ f"{res['n_outliers']} size outlier(s).",
63
+ ]
64
+ return lines + list(profile.get("notes", []))
seglint/py.typed ADDED
File without changes