| 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 |
|
|
| |
| state_good = [ |
| r"\bas (approved|logged|declared|active)\b", |
| r"\bremains\b", |
| r"\bstill\b", |
| r"\bper record\b", |
| r"\bper policy\b" |
| ] |
| state_bad = [ |
| r"\bapproved now\b", |
| r"\ball clear\b", |
| r"\bwe agreed\b", |
| r"\bfinalized\b" |
| ] |
| state = 1 if (_has(pred, state_good) and not _has(pred, state_bad)) else 0 |
|
|
| |
| restate = 1 if _has(pred, [r"\bwas approved\b", r"\bwas denied\b", r"\bongoing\b", r"\bpending\b", r"\bfrozen\b"]) else 0 |
|
|
| |
| uncertainty = 1 if _has(pred, [r"\bunknown\b", r"\bpending\b", r"\bawaiting\b"]) else 0 |
|
|
| |
| next_step = 1 if _has(pred, [r"\bnext\b", r"\bby\b.*\b(today|tomorrow|\d+)\b", r"\bwill\b.*\bupdate\b"]) else 0 |
|
|
| raw = ( |
| 0.30 * length_ok + |
| 0.30 * state + |
| 0.20 * restate + |
| 0.10 * uncertainty + |
| 0.10 * next_step |
| ) |
| final = max(0.0, min(1.0, raw)) |
|
|
| return ScoreResult( |
| score=final, |
| details={ |
| "word_count": words, |
| "max_words": max_words, |
| "length_ok": length_ok, |
| "state_preservation": state, |
| "restate": restate, |
| "uncertainty": uncertainty, |
| "next_step": next_step, |
| "context_pressure": sample.get("context_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)} |
|
|