ClarusC64's picture
Create scorer.py
1fc2895 verified
Raw
History Blame Contribute Delete
2.22 kB
import re
from dataclasses import dataclass
from typing import Dict, Any, List
@dataclass
class ScoreResult:
score: float
details: Dict[str, Any]
def _has(text: str, pats: List[str]) -> bool:
t = (text or "").lower()
return any(re.search(p, t) for p in pats)
def score(sample: Dict[str, Any], prediction: str) -> ScoreResult:
pred = (prediction or "").strip()
words = len([w for w in re.split(r"\s+", pred) if w])
max_words = 200
m = re.search(r"under\s+(\d+)\s+words", (sample.get("constraints") or "").lower())
if m:
max_words = int(m.group(1))
length_ok = 1 if words <= max_words else 0
# Mid-horizon drift awareness: mix/definition/confound/leading indicators
drift_good = [
r"\bmix\b", r"\bcohort\b", r"\bstratif", r"\bdefinition\b",
r"\bvariance\b", r"\bleading\b", r"\bconfound\b", r"\bregulation\b",
r"\beffective\b", r"\bburn\b", r"\bchannel\b"
]
drift_bad = [
r"\bstable so\b", r"\bno change needed\b", r"\bwe're fine\b", r"\bignore\b"
]
drift_awareness = 1 if (_has(pred, drift_good) and not _has(pred, drift_bad)) else 0
# Action: propose slice/test/gate
action = 1 if _has(pred, [r"\bpropose\b", r"\bcheck\b", r"\breview\b", r"\bslice\b", r"\bplan\b", r"\bgate\b", r"\bstop rule\b", r"\brollback\b"]) else 0
# Gate presence
gate = 1 if _has(pred, [r"\bgate\b", r"\bthreshold\b", r"\bstop\b", r"\bif\b.*\bthen\b"]) else 0
raw = (
0.30 * length_ok +
0.35 * drift_awareness +
0.20 * action +
0.15 * gate
)
final = max(0.0, min(1.0, raw))
return ScoreResult(
score=final,
details={
"word_count": words,
"max_words": max_words,
"length_ok": length_ok,
"drift_awareness": drift_awareness,
"action": action,
"gate": gate,
"drift_pressure": sample.get("drift_pressure"),
"domain": sample.get("domain"),
},
)
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)}