Download source/five_desks/grading.py from rca-umb/five-desks: direct link, hf CLI and curl.
- Browser
- Download file 4.21 kB
-
https://huggingface.co/datasets/rca-umb/five-desks/resolve/main/source/five_desks/grading.py
- Command line
-
hf download hf://datasets/rca-umb/five-desks/source/five_desks/grading.py
-
curl -L -o grading.py https://huggingface.co/datasets/rca-umb/five-desks/resolve/main/source/five_desks/grading.py
4.21 kB
| """Answer parts and their scoring. Reward is the mean score over parts.""" | |
| import math | |
| import re | |
| from dataclasses import dataclass | |
| from typing import Any | |
| _NUMBER_RE = re.compile(r"[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?") | |
| def parse_number(value: Any) -> float | None: | |
| if isinstance(value, bool): | |
| return None | |
| if isinstance(value, (int, float)): | |
| return float(value) if math.isfinite(value) else None | |
| if isinstance(value, str): | |
| match = _NUMBER_RE.search(value.replace(",", "").replace("−", "-")) | |
| if match: | |
| return float(match.group()) | |
| return None | |
| def parse_int(value: Any) -> int | None: | |
| """Whole numbers only: 1234, "1,234", "1234.0"; anything else is not an integer answer.""" | |
| if isinstance(value, bool): | |
| return None | |
| if isinstance(value, int): | |
| return value | |
| if isinstance(value, float): | |
| return int(value) if value.is_integer() else None | |
| if isinstance(value, str): | |
| text = value.strip().replace(",", "").replace(" ", "") | |
| if re.fullmatch(r"[-+]?\d+(\.0*)?", text): | |
| return int(float(text)) if abs(float(text)) < 2**53 else int(text.split(".")[0]) | |
| return None | |
| def parse_items(value: Any) -> list[str] | None: | |
| if isinstance(value, list): | |
| items = [str(v) for v in value] | |
| elif isinstance(value, str): | |
| if value.strip().lower() in {"", "none", "[]"}: | |
| return [] | |
| items = re.split(r"[,;\s]+", value.strip().strip("[]")) | |
| elif isinstance(value, (int, float)) and not isinstance(value, bool): | |
| items = [str(value)] | |
| else: | |
| return None | |
| return [normalize_text(i) for i in items if normalize_text(i)] | |
| def normalize_text(value: Any) -> str: | |
| text = str(value).strip().strip("\"'").strip() | |
| return re.sub(r"\s+", " ", text).lower() | |
| class Part: | |
| key: str | |
| kind: str # number | int | text | items | rule | timecode | |
| expected: Any | |
| hint: str | |
| abs_tol: float = 0.0 | |
| rel_tol: float = 0.0 | |
| def score(self, given: Any) -> float: | |
| if given is None: | |
| return 0.0 | |
| if self.kind == "number": | |
| value = parse_number(given) | |
| if value is None: | |
| return 0.0 | |
| tol = max(self.abs_tol, self.rel_tol * abs(self.expected)) | |
| return 1.0 if abs(value - self.expected) <= tol + 1e-12 else 0.0 | |
| if self.kind == "int": | |
| value = parse_int(given) | |
| return 1.0 if value is not None and value == self.expected else 0.0 | |
| if self.kind == "text": | |
| return 1.0 if normalize_text(given) == normalize_text(self.expected) else 0.0 | |
| if self.kind == "rule": | |
| if self.expected == "default": | |
| text = normalize_text(given).rstrip(".") | |
| return 1.0 if text in {"default", "default deny", "no match", "none", "no rule"} else 0.0 | |
| text = re.sub(r"^rule\s*", "", normalize_text(given)).rstrip(".") | |
| return 1.0 if parse_int(text) == int(self.expected) else 0.0 | |
| if self.kind == "timecode": | |
| text = normalize_text(given).replace(";", ":").replace(".", ":") | |
| return 1.0 if text == normalize_text(self.expected) else 0.0 | |
| if self.kind == "items": | |
| items = parse_items(given) | |
| if items is None: | |
| return 0.0 | |
| got = set(items) | |
| want = {normalize_text(i) for i in self.expected} | |
| if got == want: | |
| return 1.0 | |
| union = got | want | |
| # Near misses earn a little, so groups of rollouts still differ. | |
| return 0.5 * len(got & want) / len(union) if union else 0.0 | |
| raise ValueError(f"unknown part kind {self.kind}") | |
| def grade(parts: list[Part], answer: dict[str, Any]) -> tuple[float, list[float]]: | |
| lowered = {normalize_text(k): v for k, v in answer.items()} if isinstance(answer, dict) else {} | |
| scores = [p.score(lowered.get(normalize_text(p.key))) for p in parts] | |
| return (sum(scores) / len(scores) if scores else 0.0), scores | |
| def answer_template(parts: list[Part]) -> str: | |
| return "{" + ", ".join(f'"{p.key}": {p.hint}' for p in parts) + "}" | |