import csv import json import re from dataclasses import dataclass from typing import Dict, List, Tuple, Optional, Any @dataclass class ScoredItem: sample_id: str gold: str pred: str is_correct: int parsed_ok: int # Find A or B as a standalone token CHOICE_RE = re.compile(r"\b([AB])\b", re.IGNORECASE) # Non-greedy JSON object extractor JSON_OBJ_RE = re.compile(r"\{.*?\}", re.DOTALL) def _extract_json_obj(text: str) -> Optional[Dict[str, Any]]: """ Finds the first JSON object substring and tries to parse it. Returns a dict if successful, else None. """ m = JSON_OBJ_RE.search(text) if not m: return None candidate = m.group(0).strip() try: obj = json.loads(candidate) return obj if isinstance(obj, dict) else None except Exception: return None def parse_choice(model_output: Optional[str]) -> Tuple[Optional[str], int]: """ Returns (choice, parsed_ok) where choice is "A" or "B". Accepts: - "A" - "Answer: B" - "I choose A because ..." - JSON anywhere: {"choice":"A"} {"answer":"B"} {"selected":"A"} {"option":"B"} """ if model_output is None: return None, 0 text = str(model_output).strip() if not text: return None, 0 # 1) JSON object anywhere obj = _extract_json_obj(text) if obj is not None: for k in ("choice", "answer", "selected", "option"): v = obj.get(k) if isinstance(v, str): c = v.strip().upper() if c in ("A", "B"): return c, 1 # 2) A/B token anywhere m = CHOICE_RE.search(text) if m: return m.group(1).upper(), 1 # 3) Fallback first char c0 = text[0].upper() if c0 in ("A", "B"): return c0, 1 return None, 0 def validate_row(row: Dict[str, str]) -> Tuple[str, str]: """ Requires columns: - sample_id - correct_option (A or B) """ if "sample_id" not in row: raise KeyError("CSV missing required column: sample_id") if "correct_option" not in row: raise KeyError("CSV missing required column: correct_option") sample_id = (row.get("sample_id") or "").strip() if not sample_id: raise ValueError("Empty sample_id encountered") gold = (row.get("correct_option") or "").strip().upper() if gold not in ("A", "B"): raise ValueError(f"Invalid correct_option for {sample_id}: {gold!r} (must be 'A' or 'B')") return sample_id, gold def score_row(row: Dict[str, str], model_output: Optional[str]) -> ScoredItem: sample_id, gold = validate_row(row) choice, ok = parse_choice(model_output) pred = choice or "" is_correct = 1 if choice == gold else 0 return ScoredItem(sample_id, gold, pred, is_correct, ok) def score_file(gold_csv_path: str, predictions: Dict[str, str]) -> Dict[str, float]: """ predictions: {sample_id: model_output_string} Returns: - accuracy - parse_rate - n - missing_predictions """ scored: List[ScoredItem] = [] missing_predictions = 0 with open(gold_csv_path, "r", newline="", encoding="utf-8") as f: reader = csv.DictReader(f) if not reader.fieldnames: return {"accuracy": 0.0, "parse_rate": 0.0, "n": 0, "missing_predictions": 0} for row in reader: sid, _ = validate_row(row) if sid not in predictions: missing_predictions += 1 scored.append(score_row(row, predictions.get(sid, ""))) n = len(scored) if n == 0: return {"accuracy": 0.0, "parse_rate": 0.0, "n": 0, "missing_predictions": 0} return { "accuracy": sum(s.is_correct for s in scored) / n, "parse_rate": sum(s.parsed_ok for s in scored) / n, "n": n, "missing_predictions": missing_predictions, } def load_predictions_csv(pred_csv_path: str) -> Dict[str, str]: """ Optional helper. Predictions CSV must have columns: - sample_id - output """ preds: Dict[str, str] = {} with open(pred_csv_path, "r", newline="", encoding="utf-8") as f: reader = csv.DictReader(f) if not reader.fieldnames: return preds if "sample_id" not in reader.fieldnames or "output" not in reader.fieldnames: raise KeyError("Predictions CSV must include columns: sample_id, output") for row in reader: sid = (row.get("sample_id") or "").strip() out = row.get("output") or "" if sid: preds[sid] = out return preds def write_detailed_results(gold_csv_path: str, predictions: Dict[str, str], out_csv_path: str) -> None: """ Optional helper for auditing. Writes per-item rows: sample_id,gold,pred,is_correct,parsed_ok """ with open(gold_csv_path, "r", newline="", encoding="utf-8") as f_in: reader = csv.DictReader(f_in) fieldnames = ["sample_id", "gold", "pred", "is_correct", "parsed_ok"] with open(out_csv_path, "w", newline="", encoding="utf-8") as f_out: writer = csv.DictWriter(f_out, fieldnames=fieldnames) writer.writeheader() for row in reader: sid, _ = validate_row(row) item = score_row(row, predictions.get(sid, "")) writer.writerow( { "sample_id": item.sample_id, "gold": item.gold, "pred": item.pred, "is_correct": item.is_correct, "parsed_ok": item.parsed_ok, } ) if __name__ == "__main__": # Minimal smoke test. Replace IDs with ones from your dataset. preds = { "CDGC-0001": "A", "CDGC-0002": "Answer: A", "CDGC-0003": '{"choice":"B"}', } print(score_file("data/train.csv", preds))