"""記入済みの review_samples.csv を集計し、層別の精度・見逃し率を出す。 verdict は ``harmful`` / ``not_harmful`` / ``unsure`` の3値。未記入は未確認として数える。 出力は ``review_tally.json`` と標準出力の表。 """ from __future__ import annotations import argparse import csv import json from collections import defaultdict from datetime import datetime, timezone from pathlib import Path def main(argv: list[str] | None = None) -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--csv", type=Path, required=True) parser.add_argument("--output", type=Path, default=None, help="既定は CSV と同じ場所の review_tally.json") args = parser.parse_args(argv) counts: dict[str, dict[str, int]] = defaultdict(lambda: {"harmful": 0, "not_harmful": 0, "unsure": 0, "unreviewed": 0}) reviewers: set[str] = set() with args.csv.open(encoding="utf-8", newline="") as handle: for row in csv.DictReader(handle): verdict = (row.get("verdict") or "").strip().lower() or "unreviewed" if verdict not in ("harmful", "not_harmful", "unsure"): verdict = "unreviewed" counts[row["stratum"]][verdict] += 1 if row.get("reviewer"): reviewers.add(row["reviewer"]) result: dict[str, dict] = {} for stratum, c in sorted(counts.items()): reviewed = c["harmful"] + c["not_harmful"] entry = dict(c) entry["reviewed"] = reviewed if reviewed: if stratum.startswith(("deleted:", "cooccurrence:")): entry["precision"] = round(c["harmful"] / reviewed, 3) # 削除の妥当性 else: entry["harmful_rate"] = round(c["harmful"] / reviewed, 3) # 保持側の見逃し率 result[stratum] = entry output = args.output or args.csv.with_name("review_tally.json") payload = {"tallied_at_utc": datetime.now(timezone.utc).isoformat(), "csv": str(args.csv), "reviewers": sorted(reviewers), "strata": result} output.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(f"{'stratum':40s} {'harm':>5s} {'not':>5s} {'uns':>5s} {'todo':>5s} rate") for stratum, e in result.items(): rate = e.get("precision", e.get("harmful_rate", "")) print(f"{stratum:40s} {e['harmful']:5d} {e['not_harmful']:5d} {e['unsure']:5d} {e['unreviewed']:5d} {rate}") if __name__ == "__main__": main()