"""WS6 image inference, Grad-CAM overlays and validated Week 2 evidence export.""" from __future__ import annotations import argparse import sys from collections.abc import Sequence from pathlib import Path from jsonschema import ValidationError from capstone.data.label_space import DOMAIN_ORDER from capstone.inference.engine import Finding, InferenceEngine from capstone.inference.evidence import build_evidence_bundle from capstone.inference.explainability import GradCamExplainer from capstone.inference.image_io import prepare_image from capstone.inference.regions import check_fraction from capstone.models import CheckpointVersionError def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description="Run WS6 inference on one image") parser.add_argument("image", type=Path, help="PNG or JPEG image path") parser.add_argument( "--checkpoint", required=True, type=Path, help="WS2 checkpoint bundle", ) parser.add_argument( "--overlay-dir", type=Path, default=Path("outputs/ws6"), help="directory for Grad-CAM side-by-side overlays", ) parser.add_argument( "--threshold", type=float, default=0.5, help=("provisional Week 1 placeholder superseded by WS6 Week 3 per-label thresholds"), ) parser.add_argument( "--top-k", type=int, default=5, help="how many findings to print from the winning domain", ) parser.add_argument( "--no-overlay", action="store_true", help="skip saving overlays (Grad-CAM still runs when --evidence-output is requested)", ) parser.add_argument( "--evidence-output", type=Path, help="write a validated EvidenceBundle JSON" ) parser.add_argument( "--region-threshold", type=float, default=0.15, help="minimum share of total activation mass per grid cell", ) return parser def main(argv: Sequence[str] | None = None) -> int: args = build_parser().parse_args(argv) try: return _run(args) except (ValueError, OSError, RuntimeError, ValidationError, CheckpointVersionError) as exc: print(f"error: {exc}", file=sys.stderr) return 1 def _run(args: argparse.Namespace) -> int: check_fraction(args.threshold, "threshold") check_fraction(args.region_threshold, "region_threshold") engine = InferenceEngine.from_checkpoint(args.checkpoint) card = getattr(engine.model, "model_card", None) if isinstance(card, dict) and card.get("training_strategy") == "stub": print( "WARNING: checkpoint training_strategy is 'stub'; " "the head is untrained and this output has no clinical meaning." ) # Decode once so prediction and explanation use the same pixel snapshot. source = prepare_image(args.image, engine.preprocessing).rgb result = engine.predict(source) domain = result.inferred_domain print(f"domain: {domain.domain}") print(f"domain confidence: {domain.confidence:.4f} (uncalibrated max class probability)") for name in DOMAIN_ORDER: print(f" {name}: {domain.block_scores[name]:.4f}") _print_findings_table(result.findings[: max(args.top_k, 0)]) if args.no_overlay and args.evidence_output is None: return 0 positives = result.positive_findings(args.threshold) if not positives: print("no label cleared the threshold; no overlay was generated") explanations = () if positives: explainer = GradCamExplainer(engine.model, preprocessing=engine.preprocessing) explanations = explainer.explain_positives(source, result, threshold=args.threshold) if args.evidence_output is not None: bundle = build_evidence_bundle( result, explanations, image_reference=str(args.image.resolve()), image_size=source.size, model_card=card, threshold=args.threshold, min_activation_fraction=args.region_threshold, ) bundle.save(args.evidence_output) print(f"evidence: {args.evidence_output.resolve()}") if args.no_overlay or not explanations: return 0 args.overlay_dir.mkdir(parents=True, exist_ok=True) slug_by_index = { int(position["index"]): str(position["slug"]) for position in engine.label_positions } stem = args.image.stem for explanation in explanations: slug = slug_by_index[explanation.target_label] path = (args.overlay_dir / f"{stem}_{slug}.png").resolve() explanation.side_by_side.save(path) label = explanation.label_name or str(explanation.target_label) print(f"overlay: {label} -> {path}") return 0 def _print_findings_table(findings: Sequence[Finding]) -> None: print("findings:") if not findings: print(" (none)") return header = ("index", "qualified_name", "probability") rows = [ (str(finding.index), finding.qualified_name, f"{finding.probability:.4f}") for finding in findings ] widths = [ max(len(header[column]), max(len(row[column]) for row in rows)) for column in range(3) ] print(f" {header[0]:>{widths[0]}} {header[1]:<{widths[1]}} {header[2]:>{widths[2]}}") for row in rows: print(f" {row[0]:>{widths[0]}} {row[1]:<{widths[1]}} {row[2]:>{widths[2]}}") if __name__ == "__main__": raise SystemExit(main())