ClarusC64 commited on
Commit
9116592
·
verified ·
1 Parent(s): 77cd2e5

Update scorer.py

Browse files
Files changed (1) hide show
  1. scorer.py +156 -24
scorer.py CHANGED
@@ -2,7 +2,7 @@ import csv
2
  import json
3
  import re
4
  from dataclasses import dataclass
5
- from typing import Dict, List, Tuple, Optional
6
 
7
 
8
  @dataclass
@@ -14,60 +14,192 @@ class ScoredItem:
14
  parsed_ok: int
15
 
16
 
 
17
  CHOICE_RE = re.compile(r"\b([AB])\b", re.IGNORECASE)
18
 
19
- def parse_choice(model_output: str) -> Tuple[Optional[str], int]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  if model_output is None:
21
  return None, 0
22
 
23
- text = model_output.strip()
24
-
25
- if text.startswith("{") and text.endswith("}"):
26
- try:
27
- obj = json.loads(text)
28
- for k in ["choice", "answer", "selected", "option"]:
29
- if k in obj and isinstance(obj[k], str):
30
- c = obj[k].strip().upper()
31
- if c in ["A", "B"]:
32
- return c, 1
33
- except Exception:
34
- pass
35
 
 
 
 
 
 
 
 
 
 
 
 
36
  m = CHOICE_RE.search(text)
37
  if m:
38
  return m.group(1).upper(), 1
39
 
40
- if text and text[0].upper() in ["A", "B"]:
41
- return text[0].upper(), 1
 
 
42
 
43
  return None, 0
44
 
45
 
46
- def score_row(row: Dict[str, str], model_output: str) -> ScoredItem:
47
- gold = row["correct_option"].strip().upper()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  choice, ok = parse_choice(model_output)
49
- pred = choice if choice else ""
50
  is_correct = 1 if choice == gold else 0
51
- return ScoredItem(row["sample_id"], gold, pred, is_correct, ok)
52
 
53
 
54
  def score_file(gold_csv_path: str, predictions: Dict[str, str]) -> Dict[str, float]:
 
 
 
 
 
 
 
 
 
55
  scored: List[ScoredItem] = []
 
 
56
  with open(gold_csv_path, "r", newline="", encoding="utf-8") as f:
57
- for row in csv.DictReader(f):
58
- scored.append(score_row(row, predictions.get(row["sample_id"], "")))
 
 
 
 
 
 
 
59
 
60
  n = len(scored)
61
  if n == 0:
62
- return {"accuracy": 0.0, "parse_rate": 0.0, "n": 0}
63
 
64
  return {
65
  "accuracy": sum(s.is_correct for s in scored) / n,
66
  "parse_rate": sum(s.parsed_ok for s in scored) / n,
67
  "n": n,
 
68
  }
69
 
70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  if __name__ == "__main__":
72
- preds = {"CVSC-0001": "A", "CVSC-0002": "Answer: A"}
 
 
 
 
 
73
  print(score_file("data/train.csv", preds))
 
2
  import json
3
  import re
4
  from dataclasses import dataclass
5
+ from typing import Dict, List, Tuple, Optional, Any
6
 
7
 
8
  @dataclass
 
14
  parsed_ok: int
15
 
16
 
17
+ # Find A or B as a standalone token
18
  CHOICE_RE = re.compile(r"\b([AB])\b", re.IGNORECASE)
19
 
20
+ # Non-greedy JSON object extractor
21
+ JSON_OBJ_RE = re.compile(r"\{.*?\}", re.DOTALL)
22
+
23
+
24
+ def _extract_json_obj(text: str) -> Optional[Dict[str, Any]]:
25
+ """
26
+ Finds the first JSON object substring and tries to parse it.
27
+ Returns a dict if successful, else None.
28
+ """
29
+ m = JSON_OBJ_RE.search(text)
30
+ if not m:
31
+ return None
32
+ candidate = m.group(0).strip()
33
+ try:
34
+ obj = json.loads(candidate)
35
+ return obj if isinstance(obj, dict) else None
36
+ except Exception:
37
+ return None
38
+
39
+
40
+ def parse_choice(model_output: Optional[str]) -> Tuple[Optional[str], int]:
41
+ """
42
+ Returns (choice, parsed_ok) where choice is "A" or "B".
43
+
44
+ Accepts:
45
+ - "A"
46
+ - "Answer: B"
47
+ - "I choose A because ..."
48
+ - JSON anywhere: {"choice":"A"} {"answer":"B"} {"selected":"A"} {"option":"B"}
49
+ """
50
  if model_output is None:
51
  return None, 0
52
 
53
+ text = str(model_output).strip()
54
+ if not text:
55
+ return None, 0
 
 
 
 
 
 
 
 
 
56
 
57
+ # 1) JSON object anywhere
58
+ obj = _extract_json_obj(text)
59
+ if obj is not None:
60
+ for k in ("choice", "answer", "selected", "option"):
61
+ v = obj.get(k)
62
+ if isinstance(v, str):
63
+ c = v.strip().upper()
64
+ if c in ("A", "B"):
65
+ return c, 1
66
+
67
+ # 2) A/B token anywhere
68
  m = CHOICE_RE.search(text)
69
  if m:
70
  return m.group(1).upper(), 1
71
 
72
+ # 3) Fallback first char
73
+ c0 = text[0].upper()
74
+ if c0 in ("A", "B"):
75
+ return c0, 1
76
 
77
  return None, 0
78
 
79
 
80
+ def validate_row(row: Dict[str, str]) -> Tuple[str, str]:
81
+ """
82
+ Requires columns:
83
+ - sample_id
84
+ - correct_option (A or B)
85
+ """
86
+ if "sample_id" not in row:
87
+ raise KeyError("CSV missing required column: sample_id")
88
+ if "correct_option" not in row:
89
+ raise KeyError("CSV missing required column: correct_option")
90
+
91
+ sample_id = (row.get("sample_id") or "").strip()
92
+ if not sample_id:
93
+ raise ValueError("Empty sample_id encountered")
94
+
95
+ gold = (row.get("correct_option") or "").strip().upper()
96
+ if gold not in ("A", "B"):
97
+ raise ValueError(f"Invalid correct_option for {sample_id}: {gold!r} (must be 'A' or 'B')")
98
+
99
+ return sample_id, gold
100
+
101
+
102
+ def score_row(row: Dict[str, str], model_output: Optional[str]) -> ScoredItem:
103
+ sample_id, gold = validate_row(row)
104
  choice, ok = parse_choice(model_output)
105
+ pred = choice or ""
106
  is_correct = 1 if choice == gold else 0
107
+ return ScoredItem(sample_id, gold, pred, is_correct, ok)
108
 
109
 
110
  def score_file(gold_csv_path: str, predictions: Dict[str, str]) -> Dict[str, float]:
111
+ """
112
+ predictions: {sample_id: model_output_string}
113
+
114
+ Returns:
115
+ - accuracy
116
+ - parse_rate
117
+ - n
118
+ - missing_predictions
119
+ """
120
  scored: List[ScoredItem] = []
121
+ missing_predictions = 0
122
+
123
  with open(gold_csv_path, "r", newline="", encoding="utf-8") as f:
124
+ reader = csv.DictReader(f)
125
+ if not reader.fieldnames:
126
+ return {"accuracy": 0.0, "parse_rate": 0.0, "n": 0, "missing_predictions": 0}
127
+
128
+ for row in reader:
129
+ sid, _ = validate_row(row)
130
+ if sid not in predictions:
131
+ missing_predictions += 1
132
+ scored.append(score_row(row, predictions.get(sid, "")))
133
 
134
  n = len(scored)
135
  if n == 0:
136
+ return {"accuracy": 0.0, "parse_rate": 0.0, "n": 0, "missing_predictions": 0}
137
 
138
  return {
139
  "accuracy": sum(s.is_correct for s in scored) / n,
140
  "parse_rate": sum(s.parsed_ok for s in scored) / n,
141
  "n": n,
142
+ "missing_predictions": missing_predictions,
143
  }
144
 
145
 
146
+ def load_predictions_csv(pred_csv_path: str) -> Dict[str, str]:
147
+ """
148
+ Optional helper.
149
+ Predictions CSV must have columns:
150
+ - sample_id
151
+ - output
152
+ """
153
+ preds: Dict[str, str] = {}
154
+ with open(pred_csv_path, "r", newline="", encoding="utf-8") as f:
155
+ reader = csv.DictReader(f)
156
+ if not reader.fieldnames:
157
+ return preds
158
+ if "sample_id" not in reader.fieldnames or "output" not in reader.fieldnames:
159
+ raise KeyError("Predictions CSV must include columns: sample_id, output")
160
+
161
+ for row in reader:
162
+ sid = (row.get("sample_id") or "").strip()
163
+ out = row.get("output") or ""
164
+ if sid:
165
+ preds[sid] = out
166
+
167
+ return preds
168
+
169
+
170
+ def write_detailed_results(gold_csv_path: str, predictions: Dict[str, str], out_csv_path: str) -> None:
171
+ """
172
+ Optional helper for auditing.
173
+ Writes per-item rows:
174
+ sample_id,gold,pred,is_correct,parsed_ok
175
+ """
176
+ with open(gold_csv_path, "r", newline="", encoding="utf-8") as f_in:
177
+ reader = csv.DictReader(f_in)
178
+ fieldnames = ["sample_id", "gold", "pred", "is_correct", "parsed_ok"]
179
+
180
+ with open(out_csv_path, "w", newline="", encoding="utf-8") as f_out:
181
+ writer = csv.DictWriter(f_out, fieldnames=fieldnames)
182
+ writer.writeheader()
183
+
184
+ for row in reader:
185
+ sid, _ = validate_row(row)
186
+ item = score_row(row, predictions.get(sid, ""))
187
+ writer.writerow(
188
+ {
189
+ "sample_id": item.sample_id,
190
+ "gold": item.gold,
191
+ "pred": item.pred,
192
+ "is_correct": item.is_correct,
193
+ "parsed_ok": item.parsed_ok,
194
+ }
195
+ )
196
+
197
+
198
  if __name__ == "__main__":
199
+ # Minimal smoke test. Replace IDs with ones from your dataset.
200
+ preds = {
201
+ "CDGC-0001": "A",
202
+ "CDGC-0002": "Answer: A",
203
+ "CDGC-0003": '{"choice":"B"}',
204
+ }
205
  print(score_file("data/train.csv", preds))