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/cli.py ADDED
@@ -0,0 +1,715 @@
1
+ """Command-line interface for seglint."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import errno
6
+ import json
7
+ import os
8
+ import sys
9
+ from pathlib import Path
10
+ from typing import Annotated
11
+
12
+ import typer
13
+ from rich.console import Console
14
+ from rich.table import Table
15
+
16
+ from seglint import __version__, api
17
+ from seglint.api import SeglintError, _build_config, _Run
18
+ from seglint.api import _run as _api_run
19
+ from seglint.calibrate import split_head
20
+ from seglint.config import (
21
+ ConfigError,
22
+ effective_values,
23
+ )
24
+ from seglint.models import Severity
25
+ from seglint.pipeline import PipelineResult
26
+ from seglint.profile import dataset_profile, profile_lines
27
+ from seglint.report.html import dataset_label, write_report
28
+ from seglint.report.json_out import build_report, class_stats, write_json
29
+ from seglint.review import (
30
+ absolute_counts,
31
+ binary_hint,
32
+ dataset_normal,
33
+ majority_warnings,
34
+ stats_for,
35
+ )
36
+
37
+ app = typer.Typer(
38
+ name="seglint",
39
+ help=(
40
+ "A model-free health check for segmentation masks: flags masks that look broken and "
41
+ "duplicate images before training."
42
+ ),
43
+ no_args_is_help=True,
44
+ add_completion=False,
45
+ )
46
+ PIPE_CLOSED_EXIT = 141 # 128 + SIGPIPE (13)
47
+
48
+
49
+ class _Console(Console):
50
+ """rich Console that exits with PIPE_CLOSED_EXIT when its reader has gone away.
51
+
52
+ Recent rich (15.0.0 here) catches BrokenPipeError itself and calls `on_broken_pipe`, which exits
53
+ with 1; on Linux and macOS that hid the closed pipe behind the "finding" exit code. Same
54
+ steps as rich, other exit code. Windows reports a closed pipe as OSError EINVAL instead,
55
+ which `run()` handles.
56
+ """
57
+
58
+ def on_broken_pipe(self) -> None:
59
+ self.quiet = True
60
+ devnull = os.open(os.devnull, os.O_WRONLY)
61
+ os.dup2(devnull, sys.stdout.fileno())
62
+ raise SystemExit(PIPE_CLOSED_EXIT)
63
+
64
+
65
+ console = _Console()
66
+ err_console = _Console(stderr=True)
67
+
68
+
69
+ def _show_version(value: bool) -> None:
70
+ if value:
71
+ typer.echo(f"seglint {__version__}")
72
+ raise typer.Exit(0)
73
+
74
+
75
+ @app.callback()
76
+ def main(
77
+ version_flag: Annotated[
78
+ bool,
79
+ typer.Option(
80
+ "--version",
81
+ callback=_show_version,
82
+ is_eager=True,
83
+ help="Print the installed seglint version and exit.",
84
+ ),
85
+ ] = False,
86
+ ) -> None:
87
+ """A model-free health check for segmentation masks: flags masks that look broken and
88
+ duplicate images before training."""
89
+
90
+
91
+ def _stdout_pipe_closed(exc: OSError) -> bool:
92
+ """True when `exc` comes from writing to a stdout whose reader went away.
93
+
94
+ POSIX raises BrokenPipeError (EPIPE). Windows raises OSError EINVAL instead; that errno is
95
+ also used for unrelated problems, so it only counts when stdout itself still cannot be
96
+ flushed.
97
+ """
98
+ if isinstance(exc, BrokenPipeError) or exc.errno == errno.EPIPE:
99
+ return True
100
+ if exc.errno != errno.EINVAL:
101
+ return False
102
+ try:
103
+ sys.stdout.flush()
104
+ except OSError:
105
+ return True
106
+ return False
107
+
108
+
109
+ def run() -> None:
110
+ """Console entry point: the Typer app, plus a quiet exit when stdout is closed early.
111
+
112
+ Follows the BrokenPipeError pattern of the Python docs (signal module): stdout is pointed
113
+ at os.devnull so that the interpreter's final flush does not fail again. The exit code is
114
+ PIPE_CLOSED_EXIT (141 = 128 + SIGPIPE 13, the usual Unix code for a closed pipe), not 1,
115
+ which already means "a finding reached --fail-on".
116
+ """
117
+ try:
118
+ app()
119
+ except OSError as e:
120
+ if not _stdout_pipe_closed(e):
121
+ raise
122
+ devnull = os.open(os.devnull, os.O_WRONLY)
123
+ os.dup2(devnull, sys.stdout.fileno())
124
+ sys.exit(PIPE_CLOSED_EXIT)
125
+
126
+
127
+ @app.command()
128
+ def version() -> None:
129
+ """Print the installed seglint version."""
130
+ typer.echo(f"seglint {__version__}")
131
+
132
+
133
+ def _fail(msg: str) -> typer.Exit:
134
+ err_console.print(f"[red]error:[/red] {msg}")
135
+ return typer.Exit(2)
136
+
137
+
138
+ def _split_ids(value: str | None) -> list[str]:
139
+ return [p for p in (value or "").split(",") if p.strip()]
140
+
141
+
142
+ def _run(*args, **kwargs) -> _Run:
143
+ """api._run with usage/input errors turned into exit code 2."""
144
+ try:
145
+ return _api_run(*args, **kwargs)
146
+ except SeglintError as e:
147
+ raise _fail(str(e)) from e
148
+
149
+
150
+ SensitivityOpt = Annotated[
151
+ str | None,
152
+ typer.Option(
153
+ "--sensitivity",
154
+ help="strict (k=2.5) | balanced (k=3.5, default) | relaxed (k=5.0): how far from the "
155
+ "dataset's normal a mask must be to count as extreme.",
156
+ ),
157
+ ]
158
+ PathArg = Annotated[Path | None, typer.Argument(help="Dataset root directory.")]
159
+ FormatOpt = Annotated[str, typer.Option("--format", help="png or coco (needs --coco-json).")]
160
+ ImagesOpt = Annotated[
161
+ Path | None,
162
+ typer.Option("--images", help="Images folder; use with --masks instead of a dataset root."),
163
+ ]
164
+ MasksOpt = Annotated[
165
+ Path | None,
166
+ typer.Option("--masks", help="Masks folder; use with --images instead of a dataset root."),
167
+ ]
168
+ LayoutOpt = Annotated[
169
+ str | None,
170
+ typer.Option(
171
+ "--layout",
172
+ help="Force a folder layout instead of detecting it: A = <split>/images + "
173
+ "<split>/masks, B = images/<split> + masks/<split>, C = images + masks.",
174
+ ),
175
+ ]
176
+ SuffixOpt = Annotated[
177
+ str | None,
178
+ typer.Option(
179
+ "--mask-suffix",
180
+ help="End of the mask file name after the image name, e.g. _mask for img1.jpg + "
181
+ "img1_mask.png. _mask, _segmentation and _gt are always tried.",
182
+ ),
183
+ ]
184
+ ClassesOpt = Annotated[
185
+ Path | None,
186
+ typer.Option(
187
+ "--classes",
188
+ help='JSON class list, e.g. {"0": "background", "1": "lesion"}. Values outside it '
189
+ "are reported (S005).",
190
+ ),
191
+ ]
192
+ IgnoreIdxOpt = Annotated[
193
+ int | None,
194
+ typer.Option(
195
+ "--ignore-index", help="Mask value for void / unlabelled pixels, skipped (default 255)."
196
+ ),
197
+ ]
198
+ BinaryOpt = Annotated[
199
+ bool,
200
+ typer.Option(
201
+ "--binary", help="For 0/255 masks: read 255 as the object (class 1), all else as 0."
202
+ ),
203
+ ]
204
+ PaletteOpt = Annotated[
205
+ Path | None,
206
+ typer.Option(
207
+ "--palette",
208
+ help='JSON colour -> class map for RGB masks, e.g. {"1": [255, 0, 0]}.',
209
+ ),
210
+ ]
211
+ ConfigOpt = Annotated[
212
+ Path | None,
213
+ typer.Option(
214
+ "--config",
215
+ help="seglint.toml to use (default: seglint.toml or pyproject.toml [tool.seglint] in "
216
+ "the dataset folder, then in the current folder).",
217
+ ),
218
+ ]
219
+ CocoOpt = Annotated[Path | None, typer.Option("--coco-json", help="COCO annotation file.")]
220
+
221
+
222
+ def _command_text(ctx: typer.Context, full_paths: bool) -> str:
223
+ """The command as typed, rebuilt from the parsed options (defaults left out). Paths keep only
224
+ their last part unless `full_paths`, so the report does not reveal local folders."""
225
+ parts = ["seglint", ctx.info_name or "check"]
226
+ for p in ctx.command.params:
227
+ v = ctx.params.get(p.name)
228
+ if v is None or v == p.default or v is False:
229
+ continue
230
+ text = str(v)
231
+ if isinstance(v, Path) and not full_paths:
232
+ text = v.name or text
233
+ if " " in text:
234
+ text = f'"{text}"'
235
+ if getattr(p, "opts", None) and p.opts[0].startswith("-"):
236
+ parts.append(p.opts[0] if getattr(p, "is_flag", False) else f"{p.opts[0]} {text}")
237
+ else:
238
+ parts.append(text)
239
+ return " ".join(parts)
240
+
241
+
242
+ @app.command()
243
+ def check(
244
+ ctx: typer.Context,
245
+ path: PathArg = None,
246
+ fmt: FormatOpt = "png",
247
+ images: ImagesOpt = None,
248
+ masks: MasksOpt = None,
249
+ layout: LayoutOpt = None,
250
+ mask_suffix: SuffixOpt = None,
251
+ classes: ClassesOpt = None,
252
+ ignore_index: IgnoreIdxOpt = None,
253
+ binary: BinaryOpt = False,
254
+ palette: PaletteOpt = None,
255
+ select: Annotated[
256
+ str | None, typer.Option("--select", help="Comma-separated check ids.")
257
+ ] = None,
258
+ ignore: Annotated[
259
+ str | None, typer.Option("--ignore", help="Comma-separated check ids.")
260
+ ] = None,
261
+ experimental: Annotated[
262
+ bool, typer.Option("--experimental", help="Also run experimental checks (G005).")
263
+ ] = False,
264
+ include_profile_checks: Annotated[
265
+ bool,
266
+ typer.Option(
267
+ "--include-profile-checks",
268
+ help="Also report the dataset-profile checks G004 (border contact) and T003 "
269
+ "(resolution outliers) as findings. Off by default: they describe the dataset, "
270
+ "not mask quality.",
271
+ ),
272
+ ] = False,
273
+ workers: Annotated[
274
+ int, typer.Option("--workers", min=1, help="Worker processes for pass 1 (1 = serial).")
275
+ ] = 1,
276
+ background: Annotated[
277
+ int | None, typer.Option("--background", help="Background class id (-1: none; default 0).")
278
+ ] = None,
279
+ analysis_max_side: Annotated[
280
+ int | None,
281
+ typer.Option("--analysis-max-side", help="Downscale masks for component analysis (0=off)."),
282
+ ] = None,
283
+ fail_on: Annotated[str, typer.Option("--fail-on", help="error|warning|info")] = "error",
284
+ report: Annotated[
285
+ Path | None, typer.Option("--report", help="Write a self-contained HTML report.")
286
+ ] = None,
287
+ export_examples: Annotated[
288
+ Path | None,
289
+ typer.Option(
290
+ "--export-examples", help="Write image|mask|overlay PNGs of the suspicious examples."
291
+ ),
292
+ ] = None,
293
+ review_checks: Annotated[
294
+ str | None,
295
+ typer.Option(
296
+ "--review-checks",
297
+ help="Comma-separated check ids; the report starts with a merged list of samples "
298
+ "to verify by hand (e.g. G002,G003,G005).",
299
+ ),
300
+ ] = None,
301
+ review_limit: Annotated[
302
+ int,
303
+ typer.Option(
304
+ "--review-limit",
305
+ min=1,
306
+ help="Rows of the --review-checks list (top by severity, score).",
307
+ ),
308
+ ] = 30,
309
+ review_all: Annotated[
310
+ bool, typer.Option("--review-all", help="Show every row of the --review-checks list.")
311
+ ] = False,
312
+ report_full_path: Annotated[
313
+ bool, typer.Option("--report-full-path", help="Show the full dataset path in the report.")
314
+ ] = False,
315
+ json_out: Annotated[Path | None, typer.Option("--json", help="Write JSON report.")] = None,
316
+ max_examples: Annotated[
317
+ int | None,
318
+ typer.Option(
319
+ "--max-examples",
320
+ min=0,
321
+ help="Example cards per check in the report (default 50, or max_examples in "
322
+ "seglint.toml).",
323
+ ),
324
+ ] = None,
325
+ config_file: ConfigOpt = None,
326
+ coco_json: CocoOpt = None,
327
+ sensitivity: SensitivityOpt = None,
328
+ budget: Annotated[
329
+ int | None,
330
+ typer.Option(
331
+ "--budget",
332
+ min=1,
333
+ help="Return the N most suspicious samples (below-threshold ones fill the list). "
334
+ "Wins over --sensitivity.",
335
+ ),
336
+ ] = None,
337
+ explain_config: Annotated[
338
+ bool,
339
+ typer.Option(
340
+ "--explain-config",
341
+ help="Print every effective config value with its source and exit 0 (no scan).",
342
+ ),
343
+ ] = False,
344
+ quiet: Annotated[
345
+ bool,
346
+ typer.Option(
347
+ "-q",
348
+ "--quiet",
349
+ help="Print no summary tables and no note about unused same-name files; errors, "
350
+ "warnings and the 0/255 note are still printed.",
351
+ ),
352
+ ] = False,
353
+ ) -> None:
354
+ """Check the masks of a dataset and list suspicious samples. Exit 1 if a finding reaches
355
+ --fail-on, 2 on a usage or input error."""
356
+ try:
357
+ Severity.parse(fail_on) # fail fast on a bad value, before any scan
358
+ except ValueError as e:
359
+ raise _fail(str(e)) from e
360
+ ignored_sensitivity = None
361
+ if budget is not None and sensitivity is not None:
362
+ ignored_sensitivity, sensitivity = sensitivity, None # --budget wins
363
+ if not quiet:
364
+ err_console.print(
365
+ f"note: --budget {budget} given, so --sensitivity {ignored_sensitivity} is "
366
+ "ignored (the list has a fixed size; thresholds stay as configured)"
367
+ )
368
+ if explain_config:
369
+ _explain(path, config_file, mask_suffix, ignore_index, binary, background,
370
+ analysis_max_side, classes, palette, sensitivity, budget) # fmt: skip
371
+ raise typer.Exit(0)
372
+ try:
373
+ result = api.check(
374
+ path, images=images, masks=masks, format=fmt, coco_json=coco_json, layout=layout,
375
+ mask_suffix=mask_suffix, classes=classes, ignore_index=ignore_index, binary=binary,
376
+ palette=palette, background=background, analysis_max_side=analysis_max_side,
377
+ select=select, ignore=ignore, experimental=experimental,
378
+ include_profile_checks=include_profile_checks, config=config_file,
379
+ sensitivity=sensitivity, budget=budget, workers=workers, fail_on=fail_on,
380
+ ) # fmt: skip
381
+ except SeglintError as e:
382
+ raise _fail(str(e)) from e
383
+ res = result._pipeline
384
+ if max_examples is not None: # the flag wins over max_examples in seglint.toml
385
+ result.config.max_examples, result.config.sources["max_examples"] = max_examples, "cli"
386
+ max_examples = result.config.max_examples
387
+ if result.budget and ignored_sensitivity:
388
+ result.budget["overrides_sensitivity"] = ignored_sensitivity
389
+ budget_block = result.budget
390
+ for w in result.warnings:
391
+ if w.get("kind") == "duplicate_files": # information, not a finding; -q hides it
392
+ if not quiet:
393
+ err_console.print(f"[cyan]note:[/cyan] {w['message']}")
394
+ elif w.get("kind") == "binary_hint": # information, not a finding
395
+ err_console.print(f"[cyan]note:[/cyan] {w['message']}")
396
+ else:
397
+ err_console.print(f"[yellow]warning:[/yellow] {w['message']}")
398
+ # Write every file before printing to stdout, so that a reader closing the pipe early
399
+ # (`seglint check ... | head -1`) cannot stop a file from being written.
400
+ written: list[str] = []
401
+ if report is not None:
402
+ try:
403
+ info = result.write_report(
404
+ report,
405
+ max_examples=max_examples,
406
+ review_checks=_split_ids(review_checks),
407
+ review_limit=None if review_all else review_limit,
408
+ full_path=report_full_path,
409
+ command=_command_text(ctx, report_full_path),
410
+ )
411
+ except OSError as e:
412
+ raise _fail(f"cannot write {report}: {e}") from e
413
+ written.append(f"report: {report} ({info['file_bytes'] / 1e6:.1f} MB)")
414
+ if info["file_bytes"] > REPORT_HINT_BYTES and not quiet:
415
+ err_console.print(size_hint(info["file_bytes"]))
416
+ if export_examples is not None:
417
+ try:
418
+ files = result.export_examples(export_examples, max_examples)
419
+ except OSError as e:
420
+ raise _fail(f"cannot write to {export_examples}: {e}") from e
421
+ written.append(f"exported {len(files)} example images to {export_examples}")
422
+ if json_out is not None:
423
+ try:
424
+ result.to_json(json_out)
425
+ except OSError as e:
426
+ raise _fail(f"cannot write {json_out}: {e}") from e
427
+ if not quiet:
428
+ for line in written:
429
+ console.print(line)
430
+ if result.config.reference is not None:
431
+ console.print(
432
+ f"judging against calibrated reference statistics "
433
+ f"({result.config.reference.n_samples} reference samples), not against this "
434
+ "dataset"
435
+ )
436
+ _print_junk(result.skipped_junk)
437
+ _print_summary(res, max_examples=10)
438
+ if budget_block:
439
+ _print_budget(budget_block)
440
+ console.print(timing_line(result.timing))
441
+ if result.failed:
442
+ raise typer.Exit(1)
443
+
444
+
445
+ REPORT_HINT_BYTES = 10_000_000 # a larger report gets a one-line hint
446
+
447
+
448
+ def size_hint(n_bytes: int) -> str:
449
+ return f"hint: report is {n_bytes / 1e6:.1f} MB; use --max-examples N to shrink it"
450
+
451
+
452
+ def timing_line(timing: dict) -> str:
453
+ """One line with the scan time (and the report time, when a report was written)."""
454
+ n, w = timing.get("n_samples", 0), timing.get("workers", 1)
455
+ line = f"Scanned {n} samples in {timing.get('total_s', 0.0):.1f} s ({w} worker{'s' * (w != 1)})"
456
+ if "report_s" in timing:
457
+ line += f"; report written in {timing['report_s']:.1f} s"
458
+ return line
459
+
460
+
461
+ def _print_junk(n: int) -> None:
462
+ if n:
463
+ console.print(
464
+ f"{n} hidden/junk file(s) skipped (._*, .DS_Store, __MACOSX/, Thumbs.db, desktop.ini)"
465
+ )
466
+
467
+
468
+ def _print_summary(res: PipelineResult, max_examples: int) -> None:
469
+ console.print(f"{len(res.samples)} samples scanned, {len(res.issues)} suspicious findings")
470
+ if not res.issues:
471
+ return
472
+ table = Table("check", "severity", "count")
473
+ seen: dict[tuple[str, Severity], int] = {}
474
+ for i in res.issues:
475
+ seen[(i.check_id, i.severity)] = seen.get((i.check_id, i.severity), 0) + 1
476
+ for (cid, sev), n in sorted(seen.items()):
477
+ table.add_row(cid, sev.name, str(n))
478
+ console.print(table)
479
+ top = Table("score", "check", "sample", "message", title="Most suspicious")
480
+ for i in sorted(res.issues, key=lambda i: -i.score)[:max_examples]:
481
+ top.add_row(f"{i.score:.2f}", i.check_id, i.sample_id, i.message)
482
+ console.print(top)
483
+ kinds = absolute_counts(res.issues)
484
+ if kinds:
485
+ console.print(
486
+ "absolute findings by kind (samples): "
487
+ + ", ".join(f"{a['samples']} {a['label']} ({a['check']})" for a in kinds)
488
+ )
489
+ if any(i.check_id in RELATIVE_NOTE_IDS or i.data.get("tier") == "relative" for i in res.issues):
490
+ console.print(
491
+ "note: relative findings (R001-R004, relative tiers of G002/G003, G005) mean "
492
+ "'extreme relative to this dataset', not 'error'."
493
+ )
494
+
495
+
496
+ RELATIVE_NOTE_IDS = {"R001", "R002", "R003", "R004", "G005"}
497
+
498
+
499
+ def _print_budget(block: dict) -> None:
500
+ budget, rows, absolute = block["budget"], block["rows"], block["absolute_rows"]
501
+ console.print(f"Review list: {block['summary']} (budget {budget} limits only the second part)")
502
+ if absolute:
503
+ console.print(
504
+ "absolute findings by kind: "
505
+ + ", ".join(
506
+ f"{a['samples']} {a['label']} ({a['check']})" for a in block["absolute_by_check"]
507
+ )
508
+ )
509
+ title = f"Absolute findings (all {len(absolute)}, never cut by --budget)"
510
+ at = Table("#", "sample", "checks", "severity", "message", title=title)
511
+ for r in absolute:
512
+ at.add_row(str(r["rank"]), r["sample_id"], ",".join(r["checks"]),
513
+ r["max_severity"] or "", r["message"] or "") # fmt: skip
514
+ console.print(at)
515
+ n_below = sum(1 for r in rows if r["below_threshold"])
516
+ table = Table(
517
+ "#", "sample", "status", "suspicion", "z/k", "why",
518
+ title=f"Uncertain review list (budget {budget})",
519
+ ) # fmt: skip
520
+ for r in rows:
521
+ why = r["why"]
522
+ text = r["message"] or (
523
+ f"class {why['class']} {why['label']} {why['value']:.4g} "
524
+ f"(median {why['median']:.4g}, normal {why['normal_range'][0]:.4g}-"
525
+ f"{why['normal_range'][1]:.4g})"
526
+ if why
527
+ else ""
528
+ )
529
+ status = "below threshold" if r["below_threshold"] else ",".join(r["checks"])
530
+ table.add_row(
531
+ str(r["rank"]), r["sample_id"], status, f"{r['suspicion']:.3f}", f"{r['ratio']:.2f}",
532
+ text,
533
+ ) # fmt: skip
534
+ console.print(table)
535
+ if n_below:
536
+ console.print(
537
+ f"{len(rows) - n_below} of {len(rows)} rows crossed a threshold; {n_below} are "
538
+ "below threshold (filled up to the budget by suspicion score)."
539
+ )
540
+
541
+
542
+ def _explain(path, config_file, mask_suffix, ignore_index, binary, background,
543
+ analysis_max_side, classes, palette, sensitivity, budget) -> None: # fmt: skip
544
+ try:
545
+ cfg = _build_config(path, config_file, mask_suffix, ignore_index, binary, background,
546
+ analysis_max_side, classes, palette, sensitivity) # fmt: skip
547
+ except (ConfigError, OSError, ValueError) as e:
548
+ raise _fail(str(e)) from e
549
+ table = Table("key", "value", "source", title="Effective configuration")
550
+ for key, value, source in effective_values(cfg):
551
+ table.add_row(key, str(value), source)
552
+ console.print(table)
553
+ ref = cfg.reference
554
+ console.print(
555
+ f"relative statistics: calibrated reference ({ref.n_samples} samples)"
556
+ if ref
557
+ else "relative statistics: computed from the scanned dataset"
558
+ )
559
+ if budget:
560
+ console.print(f"budget: {budget} (list of the {budget} most suspicious samples)")
561
+
562
+
563
+ @app.command()
564
+ def demo(
565
+ out: Annotated[
566
+ Path | None,
567
+ typer.Option(
568
+ "--out",
569
+ help="Folder for the demo data, report and answer key (default: a "
570
+ "new temporary folder).",
571
+ ),
572
+ ] = None,
573
+ seed: Annotated[int, typer.Option("--seed", help="Random seed of the synthetic data.")] = 0,
574
+ ) -> None:
575
+ """Build a small synthetic dataset with planted defects, check it and write an HTML report.
576
+
577
+ No download and no network are needed. The planted defects are listed in
578
+ demo_answer_key.json (and below), not in the report, so the report can be checked against
579
+ them.
580
+ """
581
+ import tempfile
582
+ import time
583
+
584
+ from seglint.demo import build_dataset, caught, write_answer_key
585
+
586
+ t0 = time.time()
587
+ root = out if out is not None else Path(tempfile.mkdtemp(prefix="seglint-demo-"))
588
+ data = root / "data"
589
+ planted = build_dataset(data, seed)
590
+ key = root / "demo_answer_key.json"
591
+ write_answer_key(key, planted, seed)
592
+ run = _run(data, "png", None, None, None, None, None, None, False, None, None, None, False,
593
+ None, True) # fmt: skip
594
+ res = run.result
595
+ stats, skipped = stats_for(res, run.cfg)
596
+ normal = dataset_normal(res, run.cfg, stats, skipped, None, None)
597
+ notices = binary_hint(res, run.cfg) + majority_warnings(res, run.cfg)
598
+ report = root / "report.html"
599
+ write_report(res, run.cfg, dataset_label(data, None, False), report,
600
+ checks_run=run.check_ids, dataset_normal=normal,
601
+ provenance=effective_values(run.cfg), skipped_junk=run.skipped_junk,
602
+ warnings=notices,
603
+ command="seglint demo (then: seglint check data --report r.html)") # fmt: skip
604
+ data_json = build_report(res, run.cfg, str(data), run.layout, Severity.ERROR)
605
+ data_json["dataset_normal"] = normal
606
+ data_json["warnings"] = notices
607
+ write_json(data_json, root / "results.json")
608
+ hits = caught(planted, res.issues)
609
+ console.print(f"seglint demo: {len(res.samples)} synthetic samples (seed {seed}), "
610
+ f"{len(res.issues)} findings, {time.time() - t0:.1f} s") # fmt: skip
611
+ table = Table("planted defect", "sample", "expected check", "reported", title="Planted defects")
612
+ for p in planted:
613
+ table.add_row(p.defect, p.sample_id, p.expected_check, "yes" if hits[p.sample_id] else "NO")
614
+ console.print(table)
615
+ console.print(f"report: {report}")
616
+ console.print(f"answer key: {key}")
617
+ console.print(f"data: {data}")
618
+
619
+
620
+ @app.command()
621
+ def calibrate(
622
+ path: PathArg = None,
623
+ fmt: FormatOpt = "png",
624
+ images: ImagesOpt = None,
625
+ masks: MasksOpt = None,
626
+ layout: LayoutOpt = None,
627
+ mask_suffix: SuffixOpt = None,
628
+ classes: ClassesOpt = None,
629
+ ignore_index: IgnoreIdxOpt = None,
630
+ binary: BinaryOpt = False,
631
+ palette: PaletteOpt = None,
632
+ config_file: ConfigOpt = None,
633
+ coco_json: CocoOpt = None,
634
+ workers: Annotated[
635
+ int, typer.Option("--workers", min=1, help="Worker processes (1 = serial).")
636
+ ] = 1,
637
+ background: Annotated[
638
+ int | None, typer.Option("--background", help="Background class id (-1: none; default 0).")
639
+ ] = None,
640
+ analysis_max_side: Annotated[
641
+ int | None,
642
+ typer.Option("--analysis-max-side", help="Downscale masks for component analysis (0=off)."),
643
+ ] = None,
644
+ sensitivity: SensitivityOpt = None,
645
+ output: Annotated[Path, typer.Option("-o", "--output", help="TOML file to write.")] = Path(
646
+ "seglint.toml"
647
+ ),
648
+ force: Annotated[
649
+ bool, typer.Option("--force", help="Overwrite an existing file not written by calibrate.")
650
+ ] = False,
651
+ ) -> None:
652
+ """Scan a dataset and write seglint.toml: proposed thresholds + frozen reference statistics."""
653
+ if output.exists() and split_head(output) is None and not force:
654
+ raise _fail(f"{output} exists and was not written by `seglint calibrate`; use --force")
655
+ try:
656
+ cal = api.calibrate(
657
+ path, images=images, masks=masks, format=fmt, coco_json=coco_json, layout=layout,
658
+ mask_suffix=mask_suffix, classes=classes, ignore_index=ignore_index, binary=binary,
659
+ palette=palette, background=background, analysis_max_side=analysis_max_side,
660
+ config=config_file, sensitivity=sensitivity, workers=workers,
661
+ ) # fmt: skip
662
+ info = cal.write_toml(output, force=force)
663
+ except SeglintError as e:
664
+ raise _fail(str(e)) from e
665
+ console.print(
666
+ f"wrote {output}: {cal.n_samples} samples scanned, {info['n_valid']} usable, "
667
+ f"k = {cal.config.thresholds.relative_k:g} ({cal.sensitivity})"
668
+ )
669
+ _print_junk(cal.skipped_junk)
670
+ for note in info["notes"]:
671
+ err_console.print(f"[yellow]warning:[/yellow] {note}")
672
+
673
+
674
+ @app.command()
675
+ def stats(
676
+ path: PathArg = None,
677
+ fmt: FormatOpt = "png",
678
+ images: ImagesOpt = None,
679
+ masks: MasksOpt = None,
680
+ layout: LayoutOpt = None,
681
+ mask_suffix: SuffixOpt = None,
682
+ classes: ClassesOpt = None,
683
+ ignore_index: IgnoreIdxOpt = None,
684
+ binary: BinaryOpt = False,
685
+ palette: PaletteOpt = None,
686
+ config_file: ConfigOpt = None,
687
+ coco_json: CocoOpt = None,
688
+ json_out: Annotated[Path | None, typer.Option("--json", help="Write stats as JSON.")] = None,
689
+ ) -> None:
690
+ """Summary only: sample count, split distribution, class histogram."""
691
+ run = _run(path, fmt, images, masks, layout, mask_suffix, classes, ignore_index, binary,
692
+ palette, None, None, False, config_file, False, coco_json=coco_json) # fmt: skip
693
+ res = run.result
694
+ splits: dict[str, int] = {}
695
+ for s in res.samples:
696
+ splits[s.split or "-"] = splits.get(s.split or "-", 0) + 1
697
+ cs = class_stats(res)
698
+ prof = dataset_profile(res.records, run.cfg)
699
+ if json_out is not None:
700
+ data = {"n_samples": len(res.samples), "layout": run.layout, "splits": splits,
701
+ "skipped_junk": run.skipped_junk, "profile": prof, **cs} # fmt: skip
702
+ json_out.write_text(json.dumps(data, indent=2), encoding="utf-8")
703
+ console.print(
704
+ f"samples: {len(res.samples)} (layout {run.layout}, {len(res.records)} readable pairs)"
705
+ )
706
+ _print_junk(run.skipped_junk)
707
+ console.print("splits: " + ", ".join(f"{k}={v}" for k, v in sorted(splits.items())))
708
+ total = sum(cs["pixels"].values()) or 1
709
+ table = Table("class", "name", "pixels", "fraction")
710
+ for k, v in cs["pixels"].items():
711
+ table.add_row(k, run.cfg.classes.get(int(k), ""), str(v), f"{v / total:.4f}")
712
+ console.print(table)
713
+ console.print("dataset profile (information, not findings):")
714
+ for line in profile_lines(prof):
715
+ console.print(f" {line}")