from dataclasses import dataclass from typing import Dict, Any, List import re REQ = ["niche_definition","safe_dose_band","relapse_risk_index","paradox_zone_flags","systemic_resilience_gain","subgroup_sensitivity"] BANDS = ["avoid","narrow","moderate","broad"] @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 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) rel = _f(p, "relapse_risk_index") gain = _f(p, "systemic_resilience_gain") num_ok = int(rel is not None and 0 <= rel <= 1 and gain is not None and 0 <= gain <= 1) band_ok = int("safe_dose_band" in p and any(b in p for b in BANDS)) niche_ok = int("niche_definition" in p) paradox_ok = int("paradox_zone_flags" in p) sens_ok = int("subgroup_sensitivity" in p) raw = ( 0.18 * int(words_ok) + 0.44 * (hits / len(REQ)) + 0.22 * num_ok + 0.06 * band_ok + 0.04 * niche_ok + 0.03 * paradox_ok + 0.03 * sens_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)}