| from dataclasses import dataclass |
| from typing import Dict, Any, List |
| import re |
|
|
| REQ = [ |
| "failure_surface_type", |
| "subgroup_affected", |
| "intervention_route", |
| "recalibration_needed", |
| "protocol_reset_plan", |
| "escalation_priority", |
| "confidence_score", |
| ] |
|
|
| @dataclass |
| class ScoreResult: |
| score: float |
| details: Dict[str, Any] |
|
|
| def _yesno(text: str, key: str) -> bool: |
| return bool(re.search(rf"{key}\s*[:=]\s*(yes|no)\b", text)) |
|
|
| def _float01(text: str, key: str) -> bool: |
| return bool(re.search(rf"{key}\s*[:=]\s*(0\.\d+|1\.0)\b", text)) |
|
|
| def score(sample: Dict[str, Any], prediction: str) -> ScoreResult: |
| p = (prediction or "").lower() |
| words_ok = len(p.split()) <= 1200 |
|
|
| hits = sum(1 for k in REQ if k in p) |
|
|
| recal_ok = int(_yesno(p, "recalibration_needed")) |
| conf_ok = int(_float01(p, "confidence_score")) |
|
|
| priority_ok = int("escalation_priority" in p and any(x in p for x in [ |
| "low", "medium", "high", "critical" |
| ])) |
|
|
| raw = ( |
| 0.20 * int(words_ok) + |
| 0.55 * (hits / len(REQ)) + |
| 0.10 * recal_ok + |
| 0.10 * conf_ok + |
| 0.05 * priority_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)} |
|
|