#!/usr/bin/env python3 """Summarize MedWeave image coverage and export external-image mappings.""" from __future__ import annotations import argparse import csv import glob import json from collections import Counter, defaultdict from pathlib import Path from typing import Any def read_jsonl(path: Path): with path.open(encoding="utf-8") as handle: for line in handle: if line.strip(): yield json.loads(line) def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--repo-root", type=Path, default=Path(".")) parser.add_argument("--csv", type=Path, default=None) parser.add_argument( "--all", action="store_true", help="Include redistributed assets in the CSV (default: external only)", ) args = parser.parse_args() root = args.repo_root.resolve() manifest_path = root / "image_manifests" / "all.jsonl" assets = {row["sha256"]: row for row in read_jsonl(manifest_path)} question_counts: Counter[str] = Counter() example_ids: dict[str, list[str]] = defaultdict(list) domain_rows: Counter[str] = Counter() data_paths = sorted(Path(path) for path in glob.glob(str(root / "data" / "*" / "test-*.jsonl"))) if not data_paths: raise FileNotFoundError(f"No QA shards found below {root / 'data'}") for path in data_paths: domain = path.parent.name for row in read_jsonl(path): digest = row.get("image_sha256") if not digest: continue question_counts[digest] += 1 domain_rows[domain] += 1 if len(example_ids[digest]) < 3: example_ids[digest].append(str(row["id"])) source_asset_counts: Counter[str] = Counter() source_question_counts: Counter[str] = Counter() available_assets = 0 external_assets = 0 output_rows: list[dict[str, Any]] = [] for digest, row in sorted(assets.items()): available = bool(row.get("available_on_hub")) if available: available_assets += 1 else: external_assets += 1 sources = [str(value) for value in row.get("source_datasets", [])] if not available: for source in sources: source_asset_counts[source] += 1 source_question_counts[source] += question_counts[digest] if args.all or not available: output_rows.append( { "specialty": row.get("specialty", ""), "source_datasets": ";".join(sources), "expected_path": row["expected_path"], "sha256": digest, "source_references": ";".join(row.get("source_references", [])), "available_on_hub": available, "distribution_status": row.get("distribution_status", ""), "affected_questions": question_counts[digest], "example_question_ids": ";".join(example_ids[digest]), } ) summary = { "qa_rows_with_images_by_domain": dict(sorted(domain_rows.items())), "assets_total": len(assets), "assets_available_on_hub": available_assets, "assets_external": external_assets, "external_by_source": { source: { "assets": source_asset_counts[source], "affected_questions": source_question_counts[source], } for source in sorted(source_asset_counts) }, } print(json.dumps(summary, indent=2, sort_keys=True)) if args.csv: args.csv.parent.mkdir(parents=True, exist_ok=True) fieldnames = list(output_rows[0]) if output_rows else [] with args.csv.open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() writer.writerows(output_rows) print(json.dumps({"csv": str(args.csv), "rows": len(output_rows)}, sort_keys=True)) if __name__ == "__main__": main()