File size: 2,700 Bytes
66cf27f df6fa5a 66cf27f 76eacb1 66cf27f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | """Answer parsing shared by the task verifiers. Verifiers never trust the agent's format."""
import math
import re
from dataclasses import dataclass, field
from typing import Callable
@dataclass
class TaskInstance:
instruction: str
files: dict[str, str]
grade: Callable[[str], float]
oracle: str
# Plausible but wrong answers, used only by tests.
wrong: list[str] = field(default_factory=list)
# Extra data for tests and workspace graders (never shown to the agent).
meta: dict = field(default_factory=dict)
def norm(text: str) -> str:
return " ".join(str(text).strip().strip("`'\"").lower().split())
def to_number(text: str):
cleaned = re.sub(r"[\s,$€£%]", "", str(text)).strip("`'\"")
cleaned = re.sub(r"(usd|eur|mm|mmol/l|g|s|sec|seconds)$", "", cleaned, flags=re.I)
try:
value = float(cleaned)
except ValueError:
return None
return value if math.isfinite(value) else None
def number_close(text: str, target: float, abs_tol: float = 0.0, rel_tol: float = 0.0) -> bool:
value = to_number(text)
if value is None:
return False
return abs(value - target) <= max(abs_tol, rel_tol * abs(target)) + 1e-9
def split_parts(text: str, count: int, sep: str = ","):
parts = [p.strip() for p in str(text).strip().strip("`'\"").split(sep)]
return parts if len(parts) == count else None
def token_set(text: str):
body = norm(text).strip("[](){}")
if body == "":
return None # an empty submission never matches, even when the answer is "none"
if body in ("none", "no", "nothing"):
return frozenset()
return frozenset(t.strip().strip("'\"") for t in re.split(r"[,\s;]+", body) if t.strip())
def parts_score(text: str, checks: list[Callable[[str], bool]], sep: str = ",") -> float:
"""Mean of per-part checks; 0 when the part count is wrong."""
parts = split_parts(text, len(checks), sep)
if parts is None and sep == ",": # tolerate thousands separators such as 12,345.67
parts = split_parts(re.sub(r"(?<=\d),(?=\d{3}(?!\d))", "", str(text)), len(checks), sep)
if parts is None:
return 0.0
return sum(1.0 for part, check in zip(parts, checks) if check(part)) / len(checks)
def exact(target: str) -> Callable[[str], bool]:
return lambda part: norm(part) == norm(target)
def close(target: float, abs_tol: float = 0.0, rel_tol: float = 0.0) -> Callable[[str], bool]:
return lambda part: number_close(part, target, abs_tol, rel_tol)
def csv_text(header: list[str], rows: list[list]) -> str:
lines = [",".join(header)]
lines += [",".join(str(v) for v in row) for row in rows]
return "\n".join(lines) + "\n"
|