import re from dataclasses import dataclass from typing import Dict, Any, List BASINS = { "basin_a_inflammatory_autonomic", "basin_b_mito_metabolic_fatigue", "basin_c_neuroimmune_cognitive", "basin_d_mast_cell_histamine_like", "basin_e_autoimmune_multisystem", } @dataclass class ScoreResult: score: float details: Dict[str, Any] def _has(t: str, pats: List[str]) -> bool: t = (t or "").lower() return any(re.search(p, t) for p in pats) def _extract_ints(text: str) -> List[int]: return [int(x) for x in re.findall(r"\b\d{1,3}\b", text) if 0 <= int(x) <= 100] def score(sample: Dict[str, Any], prediction: str) -> ScoreResult: p = (prediction or "").lower().strip() words_ok = len(p.split()) <= 360 basin_ok = any(b in p for b in BASINS) nums = _extract_ints(p) has_score = any(0 <= n <= 100 for n in nums) features_ref = _has(p, [r"top5", r"features", r"pem", r"pots", r"il6", r"ana", r"tryptase", r"esr"]) evidence_ref = _has(p, [r"because", r"domin", r"pattern", r"defines", r"stable"]) raw = ( 0.30 * int(basin_ok) + 0.20 * int(has_score) + 0.20 * int(features_ref) + 0.20 * int(evidence_ref) + 0.10 * int(words_ok) ) return ScoreResult(score=min(1.0, raw), details={"basin_ok": basin_ok, "id": sample.get("id")}) 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)}