from dataclasses import dataclass from typing import Dict, Any, List import re REQ = [ "loss_of_control_risk", "recovery_window_seconds", "recommended_adaptive_action", "intervention_priority", "recovery_confidence", "post_action_stability_expectation", ] PRIORITY = ["low","medium","high","urgent"] @dataclass class ScoreResult: score: float details: Dict[str, Any] def _f(p: str, key: str): m = re.search(rf"{key}\s*[:=]\s*(0\.\d+|1\.0)\b", p) return float(m.group(1)) if m else None def _int(p: str, key: str): m = re.search(rf"{key}\s*[:=]\s*(\d+)", p) return int(m.group(1)) if m else None def score(sample: Dict[str, Any], prediction: str) -> ScoreResult: p = (prediction or "").lower() words_ok = len(p.split()) <= 950 hits = sum(1 for k in REQ if k in p) risk = _f(p,"loss_of_control_risk") win = _int(p,"recovery_window_seconds") conf = _f(p,"recovery_confidence") numeric_ok = int( risk is not None and 0<=risk<=1 and win is not None and 0<=win<=3600 and conf is not None and 0<=conf<=1 ) pr_ok = int("intervention_priority" in p and any(x in p for x in PRIORITY)) action_ok = int("recommended_adaptive_action" in p) expect_ok = int("post_action_stability_expectation" in p) raw = ( 0.18 * int(words_ok) + 0.40 * (hits/len(REQ)) + 0.22 * numeric_ok + 0.08 * pr_ok + 0.06 * action_ok + 0.06 * expect_ok ) return ScoreResult(score=min(1.0,raw), details={"id": sample.get("id"),"hits":hits}) 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)}