from __future__ import annotations import csv import json import sys from pathlib import Path from typing import Dict, List, Tuple PREDICTION_COLUMN_CANDIDATES = [ "prediction", "pred", "predicted_label", "label", ] def _to_int(value: str) -> int: value = str(value).strip() return 1 if value in {"1", "1.0", "true", "True"} else 0 def _load_csv(path: Path) -> List[Dict[str, str]]: with path.open("r", encoding="utf-8", newline="") as f: return list(csv.DictReader(f)) def _find_label_column(rows: List[Dict[str, str]]) -> str: if not rows: raise ValueError("Ground truth file is empty.") label_cols = [c for c in rows[0].keys() if c.startswith("label_")] if len(label_cols) == 1: return label_cols[0] raise ValueError(f"Expected one label column, found: {label_cols}") def _find_prediction_column(rows: List[Dict[str, str]]) -> str: if not rows: raise ValueError("Prediction file is empty.") available = set(rows[0].keys()) for col in PREDICTION_COLUMN_CANDIDATES: if col in available: return col label_like_cols = [c for c in rows[0].keys() if c.startswith("label_")] if len(label_like_cols) == 1: return label_like_cols[0] raise ValueError( "No prediction column found. Expected one of " f"{PREDICTION_COLUMN_CANDIDATES} or a single label_* column." ) def _confusion(y_true: List[int], y_pred: List[int]) -> Tuple[int, int, int, int]: tp = fp = tn = fn = 0 for yt, yp in zip(y_true, y_pred): if yt == 1 and yp == 1: tp += 1 elif yt == 0 and yp == 1: fp += 1 elif yt == 0 and yp == 0: tn += 1 elif yt == 1 and yp == 0: fn += 1 return tp, fp, tn, fn def _safe_div(n: float, d: float) -> float: return n / d if d else 0.0 def score(ground_truth_path: str, prediction_path: str) -> Dict[str, object]: gt_rows = _load_csv(Path(ground_truth_path)) pred_rows = _load_csv(Path(prediction_path)) if len(gt_rows) != len(pred_rows): raise ValueError( f"Row count mismatch: ground truth has {len(gt_rows)} rows, " f"predictions have {len(pred_rows)} rows." ) label_column = _find_label_column(gt_rows) pred_col = _find_prediction_column(pred_rows) y_true = [_to_int(row[label_column]) for row in gt_rows] y_pred = [_to_int(row[pred_col]) for row in pred_rows] tp, fp, tn, fn = _confusion(y_true, y_pred) accuracy = _safe_div(tp + tn, tp + tn + fp + fn) precision = _safe_div(tp, tp + fp) recall_boundary_detection = _safe_div(tp, tp + fn) false_safe_rate = _safe_div(fn, fn + tp) f1 = _safe_div( 2 * precision * recall_boundary_detection, precision + recall_boundary_detection, ) return { "label_column": label_column, "prediction_column": pred_col, "accuracy": round(accuracy, 6), "precision": round(precision, 6), "recall_boundary_detection": round(recall_boundary_detection, 6), "false_safe_rate": round(false_safe_rate, 6), "f1": round(f1, 6), "confusion_matrix": { "tp": tp, "fp": fp, "tn": tn, "fn": fn, }, "primary_metric": "recall_boundary_detection", "secondary_metric": "false_safe_rate", } if __name__ == "__main__": if len(sys.argv) != 3: raise SystemExit("Usage: python scorer.py ") results = score(sys.argv[1], sys.argv[2]) print(json.dumps(results, indent=2))