huggingbahl21 commited on
Commit
f4a4529
·
verified ·
1 Parent(s): c4dd020

Upload benchmark_eval.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. benchmark_eval.py +112 -0
benchmark_eval.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import argparse
3
+ import string
4
+ import warnings
5
+ warnings.filterwarnings("ignore")
6
+
7
+ def normalize_text(s):
8
+ return s.lower().translate(str.maketrans("", "", string.punctuation))
9
+
10
+ def calculate_elr(gold_records, predictions):
11
+ """
12
+ ELR: How many original entities leaked into the anonymized text.
13
+ Lower is better (0% is ideal).
14
+ """
15
+ total_entities = 0
16
+ leaked_entities = 0
17
+
18
+ for gold, pred in zip(gold_records, predictions):
19
+ pred_text = normalize_text(pred.get("anonymized_text", ""))
20
+ entities = gold.get("entities", [])
21
+
22
+ for ent in entities:
23
+ ent_text = normalize_text(ent["text"])
24
+ if not ent_text: continue
25
+ total_entities += 1
26
+ # Simple substring leak detection
27
+ if ent_text in pred_text:
28
+ leaked_entities += 1
29
+
30
+ elr = (leaked_entities / max(total_entities, 1)) * 100
31
+ return elr, leaked_entities, total_entities
32
+
33
+ def get_ngrams(text, n=3):
34
+ words = normalize_text(text).split()
35
+ ngrams = zip(*[words[i:] for i in range(n)])
36
+ return set([" ".join(ngram) for ngram in ngrams])
37
+
38
+ def calculate_crr(gold_records, predictions, n=3):
39
+ """
40
+ CRR: Contextual Re-identification Risk.
41
+ Percentage of n-grams that appear in both original and anonymized text.
42
+ Lower is better, but it has a trade-off with utility.
43
+ """
44
+ total_overlap = 0
45
+ total_ngrams = 0
46
+
47
+ for gold, pred in zip(gold_records, predictions):
48
+ orig_text = gold.get("original_text", "")
49
+ pred_text = pred.get("anonymized_text", "")
50
+
51
+ orig_ngrams = get_ngrams(orig_text, n)
52
+ pred_ngrams = get_ngrams(pred_text, n)
53
+
54
+ overlap = set(orig_ngrams).intersection(set(pred_ngrams))
55
+ total_overlap += len(overlap)
56
+ total_ngrams += len(orig_ngrams)
57
+
58
+ crr = (total_overlap / max(total_ngrams, 1)) * 100
59
+ return crr
60
+
61
+ def calculate_bertscore(gold_records, predictions):
62
+ """
63
+ BERTScore F1 computes the semantic similarity of the texts.
64
+ Higher is better (100 is ideal).
65
+ """
66
+ try:
67
+ from bert_score import score
68
+ except ImportError:
69
+ print("`bert_score` not installed. Skipping. Install with: pip install bert_score")
70
+ return None
71
+
72
+ refs = [g.get("original_text", "") for g in gold_records]
73
+ cands = [p.get("anonymized_text", "") for p in predictions]
74
+
75
+ # Using small model for fast default evaluation
76
+ P, R, F1 = score(cands, refs, lang="en", verbose=False, model_type="distilbert-base-uncased")
77
+ return F1.mean().item() * 100
78
+
79
+ def main():
80
+ parser = argparse.ArgumentParser(description="SAHA-AL Benchmark Evaluator")
81
+ parser.add_argument("--gold", type=str, default="data/test.jsonl", help="Path to gold dataset (e.g. test.jsonl)")
82
+ parser.add_argument("--pred", type=str, required=True, help="Path to predictions JSONL")
83
+ args = parser.parse_args()
84
+
85
+ with open(args.gold, "r", encoding="utf-8") as f:
86
+ gold_records = [json.loads(line) for line in f]
87
+
88
+ with open(args.pred, "r", encoding="utf-8") as f:
89
+ predictions = [json.loads(line) for line in f]
90
+
91
+ if len(gold_records) != len(predictions):
92
+ raise ValueError(f"Mismatch in number of records! Gold: {len(gold_records)}, Pred: {len(predictions)}")
93
+
94
+ print(f"Evaluating {len(predictions)} records...")
95
+
96
+ elr, leaked, total_ents = calculate_elr(gold_records, predictions)
97
+ crr3 = calculate_crr(gold_records, predictions, n=3)
98
+ bert_f1 = calculate_bertscore(gold_records, predictions)
99
+
100
+ print("\n" + "="*40)
101
+ print(" SAHA-AL Benchmark Results")
102
+ print("="*40)
103
+ print(f" Entity Leakage Rate (ELR ↓): {elr:5.2f}% ({leaked}/{total_ents} leaked)")
104
+ print(f" Contextual Re-ID (CRR-3 ↓): {crr3:5.2f}%")
105
+ if bert_f1 is not None:
106
+ print(f" BERTScore (F1 ↑): {bert_f1:5.2f}")
107
+ else:
108
+ print(f" BERTScore (F1 ↑): N/A")
109
+ print("="*40)
110
+
111
+ if __name__ == "__main__":
112
+ main()