ClarusC64 commited on
Commit
7466ce1
·
verified ·
1 Parent(s): 5a1a22e

Create scorer.py

Browse files
Files changed (1) hide show
  1. scorer.py +194 -0
scorer.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import csv
2
+ import json
3
+ import re
4
+ from typing import Dict, Any, List, Tuple
5
+
6
+ ALLOWED_ACCEPT = {"ready", "borderline", "not_supportable"}
7
+
8
+ CERTAINTY_TERMS = {
9
+ "proves", "proof", "definitive", "definitively", "certain", "guarantee",
10
+ "clearly effective", "clearly efficacy", "we hit the endpoint", "winner"
11
+ }
12
+
13
+ SAFETY_MINIMIZE_TERMS = {
14
+ "clean safety", "no safety issues", "basically safe", "minimal safety",
15
+ "no concerning safety", "solved", "not dangerous"
16
+ }
17
+
18
+ def norm(s: str) -> str:
19
+ return re.sub(r"\s+", " ", (s or "").strip().lower())
20
+
21
+ def tokset(s: str) -> set:
22
+ s = re.sub(r"[^a-z0-9\s]", " ", norm(s))
23
+ return {t for t in s.split() if t}
24
+
25
+ def jaccard(a: str, b: str) -> float:
26
+ ta, tb = tokset(a), tokset(b)
27
+ if not ta and not tb:
28
+ return 1.0
29
+ if not ta or not tb:
30
+ return 0.0
31
+ return len(ta & tb) / len(ta | tb)
32
+
33
+ def extract_json(text: str) -> Dict[str, Any]:
34
+ if text is None:
35
+ return {}
36
+ text = text.strip()
37
+ try:
38
+ return json.loads(text)
39
+ except Exception:
40
+ m = re.search(r"\{.*\}", text, flags=re.DOTALL)
41
+ if not m:
42
+ return {}
43
+ try:
44
+ return json.loads(m.group(0))
45
+ except Exception:
46
+ return {}
47
+
48
+ def split_claims(pipe_text: str) -> List[str]:
49
+ parts = [p.strip() for p in (pipe_text or "").split("|")]
50
+ return [p for p in parts if p]
51
+
52
+ def load_refs(path: str) -> Dict[str, Dict[str, str]]:
53
+ refs = {}
54
+ with open(path, newline="", encoding="utf-8") as f:
55
+ r = csv.DictReader(f)
56
+ for row in r:
57
+ refs[row["case_id"]] = {
58
+ "claims": row["drift_claims_expected"],
59
+ "corrected": row["corrected_narrative_expected"],
60
+ "accept": row["regulatory_acceptability_expected"].strip(),
61
+ "stats": row["stats_summary"],
62
+ "safety": row["safety_results"],
63
+ }
64
+ return refs
65
+
66
+ def score_one(pred: Dict[str, Any], gold: Dict[str, str]) -> Tuple[float, Dict[str, float]]:
67
+ parsed = extract_json(pred.get("prediction", ""))
68
+
69
+ pred_claims = parsed.get("drift_claims", [])
70
+ if isinstance(pred_claims, str):
71
+ pred_claims = [c.strip() for c in pred_claims.split("\n") if c.strip()]
72
+ if not isinstance(pred_claims, list):
73
+ pred_claims = []
74
+
75
+ pred_corrected = (parsed.get("corrected_summary") or parsed.get("corrected_narrative") or "").strip()
76
+ pred_accept = (parsed.get("regulatory_acceptability") or "").strip()
77
+
78
+ gold_claims = split_claims(gold["claims"])
79
+ gold_corrected = gold["corrected"]
80
+ gold_accept = gold["accept"]
81
+
82
+ # Drift detection (35)
83
+ # score by soft matching claims via token overlap
84
+ hit = 0
85
+ for gc in gold_claims:
86
+ best = 0.0
87
+ for pc in pred_claims:
88
+ best = max(best, jaccard(pc, gc))
89
+ if best >= 0.35:
90
+ hit += 1
91
+ drift = 35.0 * (hit / max(1, len(gold_claims)))
92
+
93
+ # Rewrite alignment (25)
94
+ rewrite = 25.0 * jaccard(pred_corrected, gold_corrected)
95
+
96
+ # Cross-doc consistency (20)
97
+ # reward if they mention cross-doc drift when expected includes it
98
+ # heuristic: if any expected claim contains "framed" or "overstated" and pred mentions "headline" or "press" or "investor" or "across"
99
+ expects_multi = any(("framed" in norm(c) or "overstated" in norm(c) or "softened" in norm(c)) for c in gold_claims)
100
+ mentions_multi = any(k in norm(" ".join(pred_claims)) for k in ["press", "headline", "investor", "across documents", "deck", "call"])
101
+ cross = 20.0 * (1.0 if (expects_multi and mentions_multi) else 0.3 if expects_multi else 0.6)
102
+
103
+ # Safety integrity (20)
104
+ safety = 20.0
105
+ txt = norm(pred_corrected + " " + " ".join(pred_claims))
106
+ # penalize certainty when stats show primary not significant
107
+ primary_miss = ("not significant" in norm(gold["stats"])) or ("p=0.18" in norm(gold["stats"])) or ("p=0.29" in norm(gold["stats"])) or ("p=0.11" in norm(gold["stats"])) or ("p=0.09" in norm(gold["stats"]))
108
+ if primary_miss:
109
+ for t in CERTAINTY_TERMS:
110
+ if t in txt:
111
+ safety -= 6.0
112
+ break
113
+ # penalize safety minimization when safety text indicates imbalance
114
+ safety_issue = any(k in norm(gold["safety"]) for k in ["higher", "increased", "imbalance", "g3", "sae", "aria", "anaphylaxis", "crs", "mortality", "qt"])
115
+ if safety_issue:
116
+ for t in SAFETY_MINIMIZE_TERMS:
117
+ if t in txt:
118
+ safety -= 8.0
119
+ break
120
+ safety = max(0.0, min(20.0, safety))
121
+
122
+ # Regulatory accept match as a small gate on total
123
+ gate = 1.0
124
+ if pred_accept in ALLOWED_ACCEPT:
125
+ if pred_accept != gold_accept:
126
+ gate = 0.9
127
+ else:
128
+ gate = 0.85
129
+
130
+ total = gate * (drift + rewrite + safety + cross)
131
+
132
+ return total, {
133
+ "drift_points": drift,
134
+ "rewrite_points": rewrite,
135
+ "safety_points": safety,
136
+ "cross_doc_points": cross,
137
+ "gate": gate,
138
+ }
139
+
140
+ def score_predictions(predictions_path: str, test_csv_path: str) -> Dict[str, float]:
141
+ refs = load_refs(test_csv_path)
142
+
143
+ n = 0
144
+ total = 0.0
145
+ drift = 0.0
146
+ rewrite = 0.0
147
+ safety = 0.0
148
+ cross = 0.0
149
+ gate_avg = 0.0
150
+ fmt = 0
151
+
152
+ with open(predictions_path, encoding="utf-8") as f:
153
+ for line in f:
154
+ if not line.strip():
155
+ continue
156
+ item = json.loads(line)
157
+ cid = item.get("case_id")
158
+ if cid not in refs:
159
+ continue
160
+
161
+ n += 1
162
+ parsed = extract_json(item.get("prediction", ""))
163
+ ok = isinstance(parsed.get("drift_claims", []), (list, str)) and (parsed.get("corrected_summary") or parsed.get("corrected_narrative")) and parsed.get("regulatory_acceptability")
164
+ fmt += 1 if ok else 0
165
+
166
+ sc, parts = score_one(item, refs[cid])
167
+ total += sc
168
+ drift += parts["drift_points"]
169
+ rewrite += parts["rewrite_points"]
170
+ safety += parts["safety_points"]
171
+ cross += parts["cross_doc_points"]
172
+ gate_avg += parts["gate"]
173
+
174
+ if n == 0:
175
+ return {"final_score": 0.0, "n_scored": 0.0}
176
+
177
+ return {
178
+ "final_score": float(total / n),
179
+ "drift_points_avg": float(drift / n),
180
+ "rewrite_points_avg": float(rewrite / n),
181
+ "safety_points_avg": float(safety / n),
182
+ "cross_doc_points_avg": float(cross / n),
183
+ "gate_avg": float(gate_avg / n),
184
+ "format_pass_rate": float(fmt / n),
185
+ "n_scored": float(n),
186
+ }
187
+
188
+ if __name__ == "__main__":
189
+ import argparse
190
+ p = argparse.ArgumentParser()
191
+ p.add_argument("--predictions", required=True, help="Path to predictions.jsonl")
192
+ p.add_argument("--test_csv", required=True, help="Path to data/test.csv")
193
+ a = p.parse_args()
194
+ print(json.dumps(score_predictions(a.predictions, a.test_csv), indent=2))