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/__init__.py +29 -0
- seglint/_toml.py +12 -0
- seglint/api.py +524 -0
- seglint/calibrate.py +270 -0
- seglint/checks/__init__.py +0 -0
- seglint/checks/_limits.py +41 -0
- seglint/checks/_robust.py +30 -0
- seglint/checks/base.py +174 -0
- seglint/checks/catalog.py +306 -0
- seglint/checks/geometric.py +309 -0
- seglint/checks/leakage.py +265 -0
- seglint/checks/relative.py +185 -0
- seglint/checks/statistical.py +316 -0
- seglint/checks/structural.py +175 -0
- seglint/cli.py +715 -0
- seglint/config.py +297 -0
- seglint/demo.py +152 -0
- seglint/features.py +86 -0
- seglint/hashing.py +226 -0
- seglint/loaders/__init__.py +0 -0
- seglint/loaders/base.py +29 -0
- seglint/loaders/coco.py +158 -0
- seglint/loaders/png_masks.py +274 -0
- seglint/maskthumb.py +53 -0
- seglint/models.py +122 -0
- seglint/pipeline.py +319 -0
- seglint/profile.py +64 -0
- seglint/py.typed +0 -0
- seglint/relative.py +274 -0
- seglint/report/__init__.py +0 -0
- seglint/report/html.py +1462 -0
- seglint/report/json_out.py +83 -0
- seglint/report/templates/mask_note.j2 +1 -0
- seglint/report/templates/pair_panels.j2 +12 -0
- seglint/report/templates/panels.j2 +12 -0
- seglint/report/templates/report.html.j2 +665 -0
- seglint/report/text.py +226 -0
- seglint/review.py +380 -0
- seglint-0.2.0.dist-info/METADATA +217 -0
- seglint-0.2.0.dist-info/RECORD +43 -0
- seglint-0.2.0.dist-info/WHEEL +4 -0
- seglint-0.2.0.dist-info/entry_points.txt +2 -0
- seglint-0.2.0.dist-info/licenses/LICENSE +21 -0
seglint/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""seglint: an image-independent health check for segmentation masks.
|
|
2
|
+
|
|
3
|
+
Python API (the same checks and defaults as the command line)::
|
|
4
|
+
|
|
5
|
+
import seglint
|
|
6
|
+
|
|
7
|
+
result = seglint.check("data/", budget=30)
|
|
8
|
+
print(result.summary["by_check"])
|
|
9
|
+
result.write_report("report.html")
|
|
10
|
+
|
|
11
|
+
seglint.calibrate("data/").write_toml("seglint.toml")
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
__version__ = "0.2.0"
|
|
15
|
+
|
|
16
|
+
from seglint.api import Calibration, Result, SeglintError, calibrate, check # noqa: E402
|
|
17
|
+
from seglint.models import Issue as Finding # noqa: E402
|
|
18
|
+
from seglint.models import Severity # noqa: E402
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"Calibration",
|
|
22
|
+
"Finding",
|
|
23
|
+
"Result",
|
|
24
|
+
"SeglintError",
|
|
25
|
+
"Severity",
|
|
26
|
+
"__version__",
|
|
27
|
+
"calibrate",
|
|
28
|
+
"check",
|
|
29
|
+
]
|
seglint/_toml.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""The one place that picks a TOML reader: stdlib ``tomllib`` on Python 3.11+, the ``tomli``
|
|
2
|
+
backport on Python 3.10 (a core dependency there, see pyproject.toml). Import it from here:
|
|
3
|
+
|
|
4
|
+
from seglint._toml import tomllib
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
import tomllib
|
|
9
|
+
except ModuleNotFoundError: # Python 3.10
|
|
10
|
+
import tomli as tomllib
|
|
11
|
+
|
|
12
|
+
__all__ = ["tomllib"]
|
seglint/api.py
ADDED
|
@@ -0,0 +1,524 @@
|
|
|
1
|
+
"""Python API: the same checks as the command line, returned as objects.
|
|
2
|
+
|
|
3
|
+
Example:
|
|
4
|
+
>>> import seglint
|
|
5
|
+
>>> result = seglint.check("data/", sensitivity="strict", budget=30)
|
|
6
|
+
>>> result.summary["by_check"]
|
|
7
|
+
>>> result.write_report("report.html")
|
|
8
|
+
|
|
9
|
+
The CLI (`seglint check`, `seglint calibrate`) is a thin layer over :func:`check` and
|
|
10
|
+
:func:`calibrate`; both share defaults, configuration precedence (arguments > user seglint.toml >
|
|
11
|
+
calibrated values > built-in defaults) and findings.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
import time
|
|
18
|
+
from collections.abc import Sequence
|
|
19
|
+
from dataclasses import dataclass, field
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from seglint.calibrate import render as _render_calibration
|
|
24
|
+
from seglint.calibrate import split_head
|
|
25
|
+
from seglint.checks.base import get_checks, id_selected
|
|
26
|
+
from seglint.config import (
|
|
27
|
+
Config,
|
|
28
|
+
ConfigError,
|
|
29
|
+
apply_sensitivity,
|
|
30
|
+
effective_values,
|
|
31
|
+
load_config,
|
|
32
|
+
parse_classes,
|
|
33
|
+
parse_palette,
|
|
34
|
+
)
|
|
35
|
+
from seglint.loaders.base import DatasetNotFoundError
|
|
36
|
+
from seglint.loaders.coco import discover_coco
|
|
37
|
+
from seglint.loaders.png_masks import discover
|
|
38
|
+
from seglint.models import Issue, SampleRecord, Severity
|
|
39
|
+
from seglint.pipeline import PipelineResult, run_pipeline
|
|
40
|
+
from seglint.report.html import dataset_label as _dataset_label
|
|
41
|
+
from seglint.report.html import export_examples as _export_examples
|
|
42
|
+
from seglint.report.html import write_report as _write_report
|
|
43
|
+
from seglint.report.json_out import build_report
|
|
44
|
+
from seglint.review import (
|
|
45
|
+
absolute_counts,
|
|
46
|
+
binary_hint,
|
|
47
|
+
budget_summary,
|
|
48
|
+
dataset_normal,
|
|
49
|
+
duplicate_notes,
|
|
50
|
+
majority_warnings,
|
|
51
|
+
rank_samples,
|
|
52
|
+
stats_for,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
PathLike = str | Path
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class SeglintError(Exception):
|
|
59
|
+
"""A usage or input problem (unknown option value, dataset or config not found/unreadable).
|
|
60
|
+
|
|
61
|
+
The command line reports it and exits with code 2."""
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
# ------------------------------------------------------------------------------ internals
|
|
65
|
+
@dataclass
|
|
66
|
+
class _Run:
|
|
67
|
+
cfg: Config
|
|
68
|
+
layout: str
|
|
69
|
+
result: PipelineResult
|
|
70
|
+
check_ids: tuple[str, ...] = ()
|
|
71
|
+
skipped_junk: int = 0
|
|
72
|
+
duplicates: list[dict] = field(default_factory=list) # unused same-name files (notice)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _p(x: PathLike | None) -> Path | None:
|
|
76
|
+
return None if x is None else Path(x)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _ids(value: str | Sequence[str] | None) -> list[str]:
|
|
80
|
+
if value is None:
|
|
81
|
+
return []
|
|
82
|
+
parts = value.split(",") if isinstance(value, str) else list(value)
|
|
83
|
+
return [p.strip() for p in parts if p and p.strip()]
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _json_path(path: Path | None) -> Path | None:
|
|
87
|
+
return path if path is not None and path.suffix.lower() == ".json" else None
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _build_config(
|
|
91
|
+
path: Path | None,
|
|
92
|
+
config_file: Path | None,
|
|
93
|
+
mask_suffix: str | None,
|
|
94
|
+
ignore_index: int | None,
|
|
95
|
+
binary: bool,
|
|
96
|
+
background: int | None,
|
|
97
|
+
analysis_max_side: int | None,
|
|
98
|
+
classes: Path | None,
|
|
99
|
+
palette: Path | None,
|
|
100
|
+
sensitivity: str | None,
|
|
101
|
+
) -> Config:
|
|
102
|
+
"""Config file layers (see config.py) with the arguments on top; sources are recorded."""
|
|
103
|
+
cfg = load_config(path, config_file)
|
|
104
|
+
src = cfg.sources
|
|
105
|
+
if mask_suffix is not None:
|
|
106
|
+
cfg.mask_suffix, src["mask_suffix"] = mask_suffix, "cli"
|
|
107
|
+
if ignore_index is not None:
|
|
108
|
+
cfg.ignore_index, src["ignore_index"] = ignore_index, "cli"
|
|
109
|
+
if binary:
|
|
110
|
+
cfg.binary, src["binary"] = True, "cli"
|
|
111
|
+
if background is not None:
|
|
112
|
+
cfg.background_index, src["background_index"] = background, "cli"
|
|
113
|
+
if analysis_max_side is not None:
|
|
114
|
+
cfg.analysis_max_side, src["analysis_max_side"] = max(0, analysis_max_side), "cli"
|
|
115
|
+
if classes is not None:
|
|
116
|
+
cfg.classes = parse_classes(json.loads(classes.read_text(encoding="utf-8")))
|
|
117
|
+
src["classes"] = "cli"
|
|
118
|
+
if palette is not None:
|
|
119
|
+
cfg.palette = parse_palette(json.loads(palette.read_text(encoding="utf-8")))
|
|
120
|
+
if sensitivity is not None:
|
|
121
|
+
apply_sensitivity(cfg, sensitivity)
|
|
122
|
+
return cfg
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _run(
|
|
126
|
+
path: Path | None,
|
|
127
|
+
fmt: str,
|
|
128
|
+
images: Path | None,
|
|
129
|
+
masks: Path | None,
|
|
130
|
+
layout: str | None,
|
|
131
|
+
mask_suffix: str | None,
|
|
132
|
+
classes: Path | None,
|
|
133
|
+
ignore_index: int | None,
|
|
134
|
+
binary: bool,
|
|
135
|
+
palette: Path | None,
|
|
136
|
+
select: str | Sequence[str] | None,
|
|
137
|
+
ignore: str | Sequence[str] | None,
|
|
138
|
+
experimental: bool,
|
|
139
|
+
config_file: Path | None,
|
|
140
|
+
run_checks: bool,
|
|
141
|
+
workers: int = 1,
|
|
142
|
+
background: int | None = None,
|
|
143
|
+
analysis_max_side: int | None = None,
|
|
144
|
+
coco_json: Path | None = None,
|
|
145
|
+
sensitivity: str | None = None,
|
|
146
|
+
include_profile: bool = False,
|
|
147
|
+
) -> _Run:
|
|
148
|
+
if fmt not in ("png", "coco"):
|
|
149
|
+
raise SeglintError(f"unknown format {fmt!r} (png or coco)")
|
|
150
|
+
try:
|
|
151
|
+
cfg = _build_config(path, config_file, mask_suffix, ignore_index, binary, background,
|
|
152
|
+
analysis_max_side, classes, palette, sensitivity) # fmt: skip
|
|
153
|
+
t0 = time.perf_counter()
|
|
154
|
+
if fmt == "coco":
|
|
155
|
+
found = discover_coco(coco_json or _json_path(path), images)
|
|
156
|
+
if not cfg.classes:
|
|
157
|
+
cfg.classes = dict(found.classes)
|
|
158
|
+
else:
|
|
159
|
+
found = discover(path, layout, images, masks, cfg.mask_suffix)
|
|
160
|
+
discovery_s = time.perf_counter() - t0
|
|
161
|
+
except (ConfigError, DatasetNotFoundError) as e:
|
|
162
|
+
raise SeglintError(str(e)) from e
|
|
163
|
+
except (OSError, ValueError) as e: # unreadable / malformed classes or palette JSON
|
|
164
|
+
raise SeglintError(f"cannot read input file: {e}") from e
|
|
165
|
+
if include_profile:
|
|
166
|
+
cfg.include_profile_checks, cfg.sources["include_profile_checks"] = True, "cli"
|
|
167
|
+
if experimental:
|
|
168
|
+
cfg.experimental, cfg.sources["experimental"] = True, "cli"
|
|
169
|
+
sel, ign = _ids(select), _ids(ignore)
|
|
170
|
+
checks = (
|
|
171
|
+
get_checks(sel, ign, cfg.experimental, cfg.include_profile_checks) if run_checks else []
|
|
172
|
+
)
|
|
173
|
+
report_s004 = id_selected("S004", sel, ign) and run_checks
|
|
174
|
+
result = run_pipeline(found.samples, checks, cfg, report_s004, workers=workers)
|
|
175
|
+
result.timing = {"discovery_s": discovery_s, **result.timing}
|
|
176
|
+
# S004 is not a registered check: the pipeline emits it while loading files, so it ran
|
|
177
|
+
# whenever it was selected (it must still be listed with the checks that ran)
|
|
178
|
+
ids = sorted({c.id for c in checks} | ({"S004"} if report_s004 else set()))
|
|
179
|
+
return _Run(cfg, found.layout, result, tuple(ids), found.skipped_junk, found.duplicates)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
# ------------------------------------------------------------------------------ public API
|
|
183
|
+
@dataclass
|
|
184
|
+
class Result:
|
|
185
|
+
"""The outcome of :func:`check`.
|
|
186
|
+
|
|
187
|
+
Attributes:
|
|
188
|
+
findings: Every finding (``Finding`` = :class:`seglint.models.Issue`): ``check_id``,
|
|
189
|
+
``severity``, ``sample_id``, ``split``, ``message``, ``score``, ``data``.
|
|
190
|
+
config: The effective configuration (with the source of every value).
|
|
191
|
+
layout: Detected dataset layout ("A", "B" or "C"; "coco" input reports its own).
|
|
192
|
+
dataset: The dataset path as given (used in the JSON output).
|
|
193
|
+
checks_run: Ids of the checks that ran.
|
|
194
|
+
skipped_junk: Number of hidden/OS junk files that were ignored.
|
|
195
|
+
fail_on: The severity from which :attr:`failed` is true.
|
|
196
|
+
dataset_normal: "What is normal in this dataset" (statistics per measure and class,
|
|
197
|
+
k, reference, dataset profile).
|
|
198
|
+
warnings: Notices such as the majority notice, the 0/255 note and unused same-name
|
|
199
|
+
files ("duplicate_files"); findings, counts and the budget are not affected.
|
|
200
|
+
budget: The ``--budget`` block, or None when no budget was requested.
|
|
201
|
+
timing: Wall-clock seconds (``time.perf_counter``) per stage: ``discovery_s``,
|
|
202
|
+
``pass1_s``, ``pass2_s``, ``total_s`` (the whole :func:`check` call), plus
|
|
203
|
+
``workers`` and ``n_samples``; :meth:`write_report` adds ``report_s``. It never
|
|
204
|
+
changes the findings and is not part of a comparison.
|
|
205
|
+
"""
|
|
206
|
+
|
|
207
|
+
findings: list[Issue]
|
|
208
|
+
config: Config
|
|
209
|
+
layout: str
|
|
210
|
+
dataset: str
|
|
211
|
+
checks_run: tuple[str, ...]
|
|
212
|
+
skipped_junk: int
|
|
213
|
+
fail_on: Severity
|
|
214
|
+
dataset_normal: dict[str, Any]
|
|
215
|
+
warnings: list[dict[str, Any]]
|
|
216
|
+
budget: dict[str, Any] | None = None
|
|
217
|
+
timing: dict[str, Any] = field(default_factory=dict, compare=False)
|
|
218
|
+
_pipeline: PipelineResult = field(default=None, repr=False) # type: ignore[assignment]
|
|
219
|
+
_label: str = field(default="", repr=False)
|
|
220
|
+
_full_label: str = field(default="", repr=False)
|
|
221
|
+
|
|
222
|
+
@property
|
|
223
|
+
def records(self) -> list[SampleRecord]:
|
|
224
|
+
"""Pass-1 summaries of the samples that were read."""
|
|
225
|
+
return self._pipeline.records
|
|
226
|
+
|
|
227
|
+
@property
|
|
228
|
+
def n_samples(self) -> int:
|
|
229
|
+
return len(self._pipeline.samples)
|
|
230
|
+
|
|
231
|
+
@property
|
|
232
|
+
def failed(self) -> bool:
|
|
233
|
+
"""True when a finding reaches ``fail_on`` (the CLI then exits with code 1)."""
|
|
234
|
+
return any(i.severity >= self.fail_on for i in self.findings)
|
|
235
|
+
|
|
236
|
+
@property
|
|
237
|
+
def dataset_profile(self) -> dict[str, Any]:
|
|
238
|
+
"""Border contact and resolution spread (information, not findings)."""
|
|
239
|
+
return dict(self.dataset_normal.get("profile") or {})
|
|
240
|
+
|
|
241
|
+
@property
|
|
242
|
+
def summary(self) -> dict[str, Any]:
|
|
243
|
+
"""Counts: samples, findings by check and severity, absolute findings by kind,
|
|
244
|
+
warnings, skipped junk files, fail_on and whether it was reached."""
|
|
245
|
+
by_check: dict[str, int] = {}
|
|
246
|
+
by_sev = {s.name: 0 for s in Severity}
|
|
247
|
+
for i in self.findings:
|
|
248
|
+
by_check[i.check_id] = by_check.get(i.check_id, 0) + 1
|
|
249
|
+
by_sev[i.severity.name] += 1
|
|
250
|
+
return {
|
|
251
|
+
"n_samples": self.n_samples,
|
|
252
|
+
"n_records": len(self._pipeline.records),
|
|
253
|
+
"n_findings": len(self.findings),
|
|
254
|
+
"by_check": dict(sorted(by_check.items())),
|
|
255
|
+
"by_severity": by_sev,
|
|
256
|
+
"absolute_by_kind": absolute_counts(self.findings),
|
|
257
|
+
"warnings": list(self.warnings),
|
|
258
|
+
"skipped_junk": self.skipped_junk,
|
|
259
|
+
"fail_on": self.fail_on.name,
|
|
260
|
+
"failed": self.failed,
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
def to_dict(self) -> dict[str, Any]:
|
|
264
|
+
"""The JSON document written by ``seglint check --json`` (same schema)."""
|
|
265
|
+
data = build_report(self._pipeline, self.config, self.dataset, self.layout, self.fail_on)
|
|
266
|
+
data["summary"]["skipped_junk"] = self.skipped_junk
|
|
267
|
+
data["warnings"] = list(self.warnings)
|
|
268
|
+
data["dataset_normal"] = self.dataset_normal
|
|
269
|
+
if self.budget:
|
|
270
|
+
data["budget"] = self.budget
|
|
271
|
+
return data
|
|
272
|
+
|
|
273
|
+
def to_json(self, path: PathLike | None = None) -> str:
|
|
274
|
+
"""The JSON document as text; also written to ``path`` when given."""
|
|
275
|
+
text = json.dumps(self.to_dict(), indent=2, default=str)
|
|
276
|
+
if path is not None:
|
|
277
|
+
Path(path).write_text(text, encoding="utf-8")
|
|
278
|
+
return text
|
|
279
|
+
|
|
280
|
+
def write_report(
|
|
281
|
+
self,
|
|
282
|
+
path: PathLike,
|
|
283
|
+
*,
|
|
284
|
+
max_examples: int | None = None,
|
|
285
|
+
review_checks: Sequence[str] = (),
|
|
286
|
+
review_limit: int | None = 30,
|
|
287
|
+
full_path: bool = False,
|
|
288
|
+
command: str | None = None,
|
|
289
|
+
) -> dict[str, int]:
|
|
290
|
+
"""Write the self-contained HTML report.
|
|
291
|
+
|
|
292
|
+
Args:
|
|
293
|
+
path: Output file.
|
|
294
|
+
max_examples: Example cards per check (default: ``config.max_examples``, 50 unless
|
|
295
|
+
seglint.toml sets ``max_examples``).
|
|
296
|
+
review_checks: Check ids for the merged "samples to verify by hand" list.
|
|
297
|
+
review_limit: Rows of that list (None: all).
|
|
298
|
+
full_path: Show the full dataset path in the header (default: folder name only).
|
|
299
|
+
command: Command line shown in the report footer (default: rebuilt from the
|
|
300
|
+
settings, as `seglint check <dataset> ...`).
|
|
301
|
+
|
|
302
|
+
Returns:
|
|
303
|
+
Report statistics (cards, bytes, ...).
|
|
304
|
+
"""
|
|
305
|
+
label = self._full_label if full_path else self._label
|
|
306
|
+
if max_examples is None:
|
|
307
|
+
max_examples = self.config.max_examples
|
|
308
|
+
t0 = time.perf_counter()
|
|
309
|
+
info = _write_report(
|
|
310
|
+
self._pipeline,
|
|
311
|
+
self.config,
|
|
312
|
+
label,
|
|
313
|
+
Path(path),
|
|
314
|
+
max_examples,
|
|
315
|
+
list(review_checks),
|
|
316
|
+
checks_run=self.checks_run,
|
|
317
|
+
review_limit=review_limit,
|
|
318
|
+
dataset_normal=self.dataset_normal,
|
|
319
|
+
budget=self.budget,
|
|
320
|
+
provenance=effective_values(self.config),
|
|
321
|
+
skipped_junk=self.skipped_junk,
|
|
322
|
+
warnings=self.warnings,
|
|
323
|
+
command=command,
|
|
324
|
+
)
|
|
325
|
+
self.timing["report_s"] = time.perf_counter() - t0
|
|
326
|
+
return info
|
|
327
|
+
|
|
328
|
+
def export_examples(self, folder: PathLike, max_examples: int | None = None) -> list[Path]:
|
|
329
|
+
"""Write image | mask | overlay PNGs of the suspicious examples into ``folder``
|
|
330
|
+
(``max_examples`` per check; default ``config.max_examples``)."""
|
|
331
|
+
n = self.config.max_examples if max_examples is None else max_examples
|
|
332
|
+
return _export_examples(self._pipeline, self.config, Path(folder), n)
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def check(
|
|
336
|
+
path: PathLike | None = None,
|
|
337
|
+
*,
|
|
338
|
+
images: PathLike | None = None,
|
|
339
|
+
masks: PathLike | None = None,
|
|
340
|
+
format: str = "png", # noqa: A002 (mirrors the CLI option --format)
|
|
341
|
+
coco_json: PathLike | None = None,
|
|
342
|
+
layout: str | None = None,
|
|
343
|
+
mask_suffix: str | None = None,
|
|
344
|
+
classes: PathLike | None = None,
|
|
345
|
+
ignore_index: int | None = None,
|
|
346
|
+
binary: bool = False,
|
|
347
|
+
palette: PathLike | None = None,
|
|
348
|
+
background: int | None = None,
|
|
349
|
+
analysis_max_side: int | None = None,
|
|
350
|
+
select: str | Sequence[str] | None = None,
|
|
351
|
+
ignore: str | Sequence[str] | None = None,
|
|
352
|
+
experimental: bool = False,
|
|
353
|
+
include_profile_checks: bool = False,
|
|
354
|
+
config: PathLike | None = None,
|
|
355
|
+
sensitivity: str | None = None,
|
|
356
|
+
budget: int | None = None,
|
|
357
|
+
workers: int = 1,
|
|
358
|
+
fail_on: str = "error",
|
|
359
|
+
) -> Result:
|
|
360
|
+
"""Check a segmentation dataset; the Python form of ``seglint check``.
|
|
361
|
+
|
|
362
|
+
Args:
|
|
363
|
+
path: Dataset root (layouts A/B/C), or a COCO JSON with ``format="coco"``.
|
|
364
|
+
images: Images folder (layout C, with ``masks``).
|
|
365
|
+
masks: Masks folder (layout C, with ``images``).
|
|
366
|
+
format: "png" (mask files) or "coco".
|
|
367
|
+
coco_json: COCO annotation file (``format="coco"``).
|
|
368
|
+
layout: Force layout "A", "B" or "C".
|
|
369
|
+
mask_suffix: Suffix of mask file names, e.g. "_mask".
|
|
370
|
+
classes: classes.json file.
|
|
371
|
+
ignore_index: Class id to ignore.
|
|
372
|
+
binary: Treat 0/255 masks as 0/1.
|
|
373
|
+
palette: palette.json for RGB masks.
|
|
374
|
+
background: Background class id (-1: none).
|
|
375
|
+
analysis_max_side: Downscale masks for component analysis (0: off).
|
|
376
|
+
select: Check ids or prefixes to run ("S", "R001", ...), comma-separated or a list.
|
|
377
|
+
ignore: Check ids or prefixes to skip.
|
|
378
|
+
experimental: Also run experimental checks (G005).
|
|
379
|
+
include_profile_checks: Also report G004/T003 as findings.
|
|
380
|
+
config: seglint.toml path (default: seglint.toml / pyproject.toml next to ``path``).
|
|
381
|
+
sensitivity: "strict" (k 2.5), "balanced" (k 3.5) or "relaxed" (k 5.0). None keeps
|
|
382
|
+
the configured k (3.5 unless seglint.toml sets another). Ignored when ``budget``
|
|
383
|
+
is given, as on the command line.
|
|
384
|
+
budget: Return all absolute findings plus the ``budget`` most suspicious other samples
|
|
385
|
+
in :attr:`Result.budget`.
|
|
386
|
+
workers: Worker processes for pass 1.
|
|
387
|
+
fail_on: "error", "warning" or "info": the severity that sets :attr:`Result.failed`.
|
|
388
|
+
|
|
389
|
+
Returns:
|
|
390
|
+
The :class:`Result`.
|
|
391
|
+
|
|
392
|
+
Raises:
|
|
393
|
+
SeglintError: on a usage or input problem (the CLI exits with code 2).
|
|
394
|
+
"""
|
|
395
|
+
start = time.perf_counter()
|
|
396
|
+
try:
|
|
397
|
+
threshold = Severity.parse(fail_on)
|
|
398
|
+
except ValueError as e:
|
|
399
|
+
raise SeglintError(str(e)) from e
|
|
400
|
+
ignored_sensitivity = None
|
|
401
|
+
if budget is not None and sensitivity is not None:
|
|
402
|
+
ignored_sensitivity, sensitivity = sensitivity, None # the budget wins
|
|
403
|
+
run = _run(_p(path), format, _p(images), _p(masks), layout, mask_suffix, _p(classes),
|
|
404
|
+
ignore_index, binary, _p(palette), select, ignore, experimental, _p(config), True,
|
|
405
|
+
workers, background, analysis_max_side, _p(coco_json), sensitivity,
|
|
406
|
+
include_profile_checks) # fmt: skip
|
|
407
|
+
res = run.result
|
|
408
|
+
stats, skipped = stats_for(res, run.cfg)
|
|
409
|
+
normal = dataset_normal(res, run.cfg, stats, skipped, sensitivity, budget)
|
|
410
|
+
block = None
|
|
411
|
+
if budget:
|
|
412
|
+
block = budget_summary(rank_samples(res, run.cfg, stats), budget, ignored_sensitivity)
|
|
413
|
+
total = time.perf_counter() - start
|
|
414
|
+
res.timing.update(total_s=total, workers=workers, n_samples=len(res.samples))
|
|
415
|
+
return Result(
|
|
416
|
+
findings=res.issues,
|
|
417
|
+
config=run.cfg,
|
|
418
|
+
layout=run.layout,
|
|
419
|
+
dataset=str(_p(path) or _p(images)),
|
|
420
|
+
checks_run=run.check_ids,
|
|
421
|
+
skipped_junk=run.skipped_junk,
|
|
422
|
+
fail_on=threshold,
|
|
423
|
+
dataset_normal=normal,
|
|
424
|
+
warnings=duplicate_notes(run.duplicates)
|
|
425
|
+
+ binary_hint(res, run.cfg)
|
|
426
|
+
+ majority_warnings(res, run.cfg),
|
|
427
|
+
budget=block,
|
|
428
|
+
timing=res.timing,
|
|
429
|
+
_pipeline=res,
|
|
430
|
+
_label=_dataset_label(_p(path), _p(images), False),
|
|
431
|
+
_full_label=_dataset_label(_p(path), _p(images), True),
|
|
432
|
+
)
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
@dataclass
|
|
436
|
+
class Calibration:
|
|
437
|
+
"""The outcome of :func:`calibrate`: statistics of a scanned dataset, ready to be frozen."""
|
|
438
|
+
|
|
439
|
+
config: Config
|
|
440
|
+
n_samples: int
|
|
441
|
+
sensitivity: str
|
|
442
|
+
skipped_junk: int = 0
|
|
443
|
+
_records: list[SampleRecord] = field(default_factory=list, repr=False)
|
|
444
|
+
|
|
445
|
+
def _render(self, head: str | None = None) -> tuple[str, dict]:
|
|
446
|
+
return _render_calibration(self.config, self._records, self.n_samples, self.sensitivity,
|
|
447
|
+
head) # fmt: skip
|
|
448
|
+
|
|
449
|
+
def to_toml(self) -> str:
|
|
450
|
+
"""The seglint.toml text (proposed thresholds + frozen statistics, with comments)."""
|
|
451
|
+
return self._render()[0]
|
|
452
|
+
|
|
453
|
+
def to_dict(self) -> dict[str, Any]:
|
|
454
|
+
"""Samples, usable samples, sensitivity, k, notes and the TOML text."""
|
|
455
|
+
text, info = self._render()
|
|
456
|
+
return {
|
|
457
|
+
"n_samples": self.n_samples,
|
|
458
|
+
"n_valid": info["n_valid"],
|
|
459
|
+
"sensitivity": self.sensitivity,
|
|
460
|
+
"k": self.config.thresholds.relative_k,
|
|
461
|
+
"notes": list(info["notes"]),
|
|
462
|
+
"toml": text,
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
def write_toml(self, path: PathLike, *, force: bool = False) -> dict[str, Any]:
|
|
466
|
+
"""Write seglint.toml, keeping the user part above the generated marker.
|
|
467
|
+
|
|
468
|
+
Raises:
|
|
469
|
+
SeglintError: if ``path`` exists, was not written by calibrate and ``force`` is
|
|
470
|
+
False, or cannot be written.
|
|
471
|
+
"""
|
|
472
|
+
path = Path(path)
|
|
473
|
+
head = split_head(path) if path.exists() else None
|
|
474
|
+
if path.exists() and head is None and not force:
|
|
475
|
+
raise SeglintError(
|
|
476
|
+
f"{path} exists and was not written by `seglint calibrate`; use --force"
|
|
477
|
+
)
|
|
478
|
+
text, info = self._render(head)
|
|
479
|
+
try:
|
|
480
|
+
path.write_text(text, encoding="utf-8")
|
|
481
|
+
except OSError as e:
|
|
482
|
+
raise SeglintError(f"cannot write {path}: {e}") from e
|
|
483
|
+
return info
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def calibrate(
|
|
487
|
+
path: PathLike | None = None,
|
|
488
|
+
*,
|
|
489
|
+
images: PathLike | None = None,
|
|
490
|
+
masks: PathLike | None = None,
|
|
491
|
+
format: str = "png", # noqa: A002 (mirrors the CLI option --format)
|
|
492
|
+
coco_json: PathLike | None = None,
|
|
493
|
+
layout: str | None = None,
|
|
494
|
+
mask_suffix: str | None = None,
|
|
495
|
+
classes: PathLike | None = None,
|
|
496
|
+
ignore_index: int | None = None,
|
|
497
|
+
binary: bool = False,
|
|
498
|
+
palette: PathLike | None = None,
|
|
499
|
+
background: int | None = None,
|
|
500
|
+
analysis_max_side: int | None = None,
|
|
501
|
+
config: PathLike | None = None,
|
|
502
|
+
sensitivity: str | None = None,
|
|
503
|
+
workers: int = 1,
|
|
504
|
+
) -> Calibration:
|
|
505
|
+
"""Scan a dataset for ``seglint calibrate`` (pass 1 only, no checks).
|
|
506
|
+
|
|
507
|
+
Args:
|
|
508
|
+
path, images, masks, format, coco_json, layout, mask_suffix, classes, ignore_index,
|
|
509
|
+
binary, palette, background, analysis_max_side, config, workers: as in
|
|
510
|
+
:func:`check`.
|
|
511
|
+
sensitivity: k written to the file: "strict", "balanced" (default) or "relaxed".
|
|
512
|
+
|
|
513
|
+
Returns:
|
|
514
|
+
A :class:`Calibration`; write it with :meth:`Calibration.write_toml`.
|
|
515
|
+
|
|
516
|
+
Raises:
|
|
517
|
+
SeglintError: on a usage or input problem.
|
|
518
|
+
"""
|
|
519
|
+
sens = sensitivity or "balanced"
|
|
520
|
+
run = _run(_p(path), format, _p(images), _p(masks), layout, mask_suffix, _p(classes),
|
|
521
|
+
ignore_index, binary, _p(palette), None, None, False, _p(config), False, workers,
|
|
522
|
+
background, analysis_max_side, _p(coco_json), sens) # fmt: skip
|
|
523
|
+
return Calibration(run.cfg, len(run.result.samples), sens, run.skipped_junk,
|
|
524
|
+
list(run.result.records)) # fmt: skip
|