ClarusC64's picture
Create scorer.py
f0c1a17 verified
Raw
History Blame
1.8 kB
from dataclasses import dataclass
from typing import Dict, Any, List
VALID_AXES = {"thermal","cooling","mount","metrology","contamination","none"}
@dataclass
class ScoreResult:
score: float
details: Dict[str, Any]
def parse(prediction: str):
# expected: drift_score,drift_flag,dominant_axis
try:
parts = [p.strip() for p in prediction.split(",")]
drift_score = float(parts[0])
drift_flag = int(parts[1])
axis = parts[2].lower()
return drift_score, drift_flag, axis
except Exception:
return None, None, None
def score(sample: Dict[str, Any], prediction: str) -> ScoreResult:
ds, df, ax = parse(prediction or "")
if ds is None:
return ScoreResult(0.0, {"error":"parse failure"})
true_ds = sample.get("overlay_drift_score","")
true_df = sample.get("drift_flag","")
true_ax = str(sample.get("dominant_cause_axis","")).lower()
try:
true_ds = float(true_ds)
true_df = int(true_df)
except:
true_ds = None
if true_ds is None:
valid = (0 <= ds <= 1) and (df in (0,1)) and (ax in VALID_AXES)
return ScoreResult(1.0 if valid else 0.0, {"mode":"format_only"})
err = abs(true_ds - ds)
s = max(0.0, 1.0 - err)
if df == true_df:
s += 0.20
if ax == true_ax:
s += 0.20
return ScoreResult(min(1.0, s), {
"id": sample.get("id"),
"pred_drift_score": ds,
"true_drift_score": true_ds,
"pred_flag": df,
"true_flag": true_df,
"pred_axis": ax,
"true_axis": true_ax
})
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)}