"""Label-agnostic redaction benchmark for any HF token-classification model. Runs the stock `pipeline("token-classification", aggregation_strategy="simple")` and measures character-level redaction precision/recall (did the model mask the PII characters?), which is comparable across models with different label sets. Also reports latency. Usage: python bench_redaction.py [...] [--limit N] [--out results.json] """ import argparse, json, os, sys, time from collections import Counter import torch from transformers import pipeline sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from common import read_jsonl def main(): ap = argparse.ArgumentParser() ap.add_argument("model"); ap.add_argument("tests", nargs="+") ap.add_argument("--limit", type=int, default=1000); ap.add_argument("--out") ap.add_argument("--min-score", type=float, default=0.0) a = ap.parse_args() torch.set_num_threads(os.cpu_count()) nlp = pipeline("token-classification", model=a.model, aggregation_strategy="simple", device=-1) results = {"model": a.model} for path in a.tests: ex = read_jsonl(path, a.limit) by_lang = {} t0 = time.time() outs = nlp([e["text"] for e in ex], batch_size=16) dt = time.time() - t0 for e, out in zip(ex, outs): text = e["text"] g = {i for s, en, _ in e["spans"] for i in range(s, en) if not text[i].isspace()} p = {i for o in out if o["score"] >= a.min_score for i in range(o["start"], o["end"]) if not text[i].isspace()} c = by_lang.setdefault(e.get("lang", "?"), Counter()) c["tp"] += len(g & p); c["fp"] += len(p - g); c["fn"] += len(g - p) r = {} tot = Counter() for lang, c in sorted(by_lang.items()): tot.update(c) r[lang] = {"redact_precision": round(c["tp"] / max(1, c["tp"] + c["fp"]), 4), "redact_recall": round(c["tp"] / max(1, c["tp"] + c["fn"]), 4)} r["all"] = {"redact_precision": round(tot["tp"] / max(1, tot["tp"] + tot["fp"]), 4), "redact_recall": round(tot["tp"] / max(1, tot["tp"] + tot["fn"]), 4), "ms_per_example": round(1000 * dt / len(ex), 1)} results[os.path.basename(path)] = r print(a.model, os.path.basename(path), json.dumps(r), flush=True) if a.out: json.dump(results, open(a.out, "w"), indent=1) if __name__ == "__main__": main()