from dataclasses import dataclass from typing import Dict, Any, List import re REQ = [ "decoherence_onset_timestamp", "coherence_drop_delta", "affected_modalities", "narrative_conflict_flag", "onset_confidence", "early_warning_score", ] @dataclass class ScoreResult: score: float details: Dict[str, Any] def _time_ok(p: str): # accepts t=6.2s or 6.2s m = re.search(r"decoherence_onset_timestamp\s*[:=]\s*(t\s*=\s*)?([0-9]+(\.[0-9]+)?)\s*s", p) if not m: return None return float(m.group(2)) 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 _i(p: str, key: str): m = re.search(rf"{key}\s*[:=]\s*(\d+)\b", 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()) <= 900 hits = sum(1 for k in REQ if k in p) t = _time_ok(p) delta = _f(p, "coherence_drop_delta") conf = _f(p, "onset_confidence") warn = _f(p, "early_warning_score") flag = _i(p, "narrative_conflict_flag") numeric_ok = int( t is not None and 0.0 <= t <= 120.0 and delta is not None and 0.0 <= delta <= 1.0 and conf is not None and 0.0 <= conf <= 1.0 and warn is not None and 0.0 <= warn <= 1.0 and flag is not None and flag in [0, 1] ) mods_ok = int("affected_modalities" in p and len(p) > 70) # optional sanity: if delta is high, warning should tend high sanity = 0 if delta is not None and warn is not None: sanity = int(warn + 0.15 >= delta) raw = ( 0.15 * int(words_ok) + 0.45 * (hits / len(REQ)) + 0.20 * numeric_ok + 0.10 * mods_ok + 0.10 * sanity ) return ScoreResult(score=min(1.0, raw), details={"id": sample.get("id"), "hits": hits, "sanity": sanity}) 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)}