| from dataclasses import dataclass |
| from typing import Dict, Any, List |
| import json |
|
|
| @dataclass |
| class ScoreResult: |
| score: float |
| details: Dict[str, Any] |
|
|
| BANDS = {"low", "medium", "high"} |
|
|
| def score(sample: Dict[str, Any], prediction: str) -> ScoreResult: |
| try: |
| pred = json.loads(prediction) |
| cs = float(pred.get("coherence_score", -1)) |
| band = str(pred.get("risk_band", "")).strip().lower() |
| except Exception: |
| return ScoreResult(0.0, {"error":"parse_fail","id":sample.get("id")}) |
|
|
| true_cs_raw = sample.get("coherence_score", "") |
| true_band_raw = sample.get("stochastic_risk_band", "") |
|
|
| try: |
| true_cs = float(true_cs_raw) if true_cs_raw not in ("", None) else None |
| except Exception: |
| true_cs = None |
|
|
| true_band = str(true_band_raw).strip().lower() if true_band_raw not in ("", None) else "" |
|
|
| |
| if true_cs is None or true_band == "": |
| ok = (0.0 <= cs <= 1.0) and (band in BANDS) |
| return ScoreResult(1.0 if ok else 0.0, {"mode":"format_only","id":sample.get("id")}) |
|
|
| cs_err = abs(true_cs - cs) |
| cs_score = max(0.0, 1.0 - cs_err) |
| band_score = 1.0 if band == true_band else 0.0 |
|
|
| total = 0.65 * cs_score + 0.35 * band_score |
| return ScoreResult(total, {"id":sample.get("id"),"cs":cs,"true_cs":true_cs,"band":band,"true_band":true_band}) |
|
|
| def aggregate(results: List[ScoreResult]) -> Dict[str, Any]: |
| if not results: |
| return {"mean":0.0,"n":0} |
| return {"mean": sum(r.score for r in results)/len(results), "n": len(results)} |
|
|