"""Score a PII detector on PrivacyBench+. Standard library only. python score.py DATA_DIR predictions.jsonl [--companies a,b] (default: the two suggested test companies) predictions.jsonl: one JSON object per line, {"id": ":", "spans": [{"start": 0, "end": 5}, ...]} where is the file under DATA_DIR/human_annotations and starts at 1. Entity type is ignored: the benchmark measures whether sensitive characters are masked. Two scores are printed. PII detection labels in ground_truth_spans. Records with unresolved ("unknown") spans are left out. Characters of indirect identifiers are neutral (masking them is neither rewarded nor punished). Anonymization grade every record; labels and indirect identifiers are both required; unresolved spans are neutral. """ import json, sys from collections import Counter, defaultdict from pathlib import Path TEST_COMPANIES = ['megan_donovan_eli_lilly', 'nora_caterpillar'] def bits(spans): v = 0 for a, b in spans: v |= ((1 << (b - a)) - 1) << a return v def main(): data, pred_path = Path(sys.argv[1]), sys.argv[2] companies = sys.argv[sys.argv.index('--companies') + 1].split(',') if '--companies' in sys.argv else TEST_COMPANIES ind = defaultdict(list) for l in (data / 'extensions/indirect_identifiers.jsonl').open(): t = json.loads(l) if t['file'].startswith('human_annotations/'): ind[f"{Path(t['file']).name}:{t['line']}"].append((t['start'], t['end'])) recs = {} for f in sorted((data / 'human_annotations').glob('*.jsonl')): if f.stem.removesuffix('_documents') not in companies: continue for n, line in enumerate(f.open(), 1): r = json.loads(line) recs[f'{f.name}:{n}'] = ([(s['start'], s['end']) for s in r['ground_truth_spans']], [(u['annotation']['start'], u['annotation']['end']) for u in r.get('_tracer_review', {}).get('unknown_targets', [])]) pred = {} for l in open(pred_path): if l.strip(): p = json.loads(l); pred[p['id']] = [(s['start'], s['end']) for s in p['spans']] c = Counter() for rid, (gold, unknown) in recs.items(): if rid not in pred: c['missing'] += 1 q = bits(pred.get(rid, [])); g = bits(gold); targets = ind.get(rid, []); im = bits(targets) for a, b in targets: m = ((1 << (b - a)) - 1) << a; c['ind'] += 1; c['ind_hidden'] += (m & q) == m req = g | im; neutral = bits(unknown) & ~req c['a_tp'] += (req & q).bit_count(); c['a_pred'] += (q & ~neutral).bit_count(); c['a_gold'] += req.bit_count() need = gold + targets c['req_rows'] += bool(need); c['leak_rows'] += any((((1 << (b - a)) - 1) << a) & ~q for a, b in need) if unknown: continue c['rows'] += 1 c['tp'] += (g & q).bit_count(); c['pred'] += (q & ~(im & ~g)).bit_count(); c['gold'] += g.bit_count() for a, b in gold: m = ((1 << (b - a)) - 1) << a; c['spans'] += 1; c['hidden'] += (m & q) == m f = lambda a, b: 100 * a / b if b else float('nan') out = {'companies': companies, 'records': len(recs), 'records_without_prediction': c['missing'], 'pii_detection': {'records_scored': c['rows'], 'precision': f(c['tp'], c['pred']), 'recall': f(c['tp'], c['gold']), 'f1': f(2 * c['tp'], c['pred'] + c['gold']), 'spans_not_fully_hidden_pct': 100 - f(c['hidden'], c['spans'])}, 'anonymization_grade': {'records_scored': len(recs), 'precision': f(c['a_tp'], c['a_pred']), 'recall': f(c['a_tp'], c['a_gold']), 'f1': f(2 * c['a_tp'], c['a_pred'] + c['a_gold']), 'indirect_identifiers': c['ind'], 'indirect_identifiers_hidden_pct': f(c['ind_hidden'], c['ind']), 'records_with_a_leak_pct': f(c['leak_rows'], c['req_rows']), 'records_with_something_to_hide': c['req_rows']}} print(json.dumps(out, indent=1)) if __name__ == '__main__': main()