Download packlib/normalize.py from gmreincglm/graded-task-environment-pack-sample: direct link, hf CLI and curl.
- Browser
- Download file 2.35 kB
-
https://huggingface.co/datasets/gmreincglm/graded-task-environment-pack-sample/resolve/main/packlib/normalize.py
- Command line
-
hf download hf://datasets/gmreincglm/graded-task-environment-pack-sample/packlib/normalize.py
-
curl -L -o normalize.py https://huggingface.co/datasets/gmreincglm/graded-task-environment-pack-sample/resolve/main/packlib/normalize.py
2.35 kB
| """Answer normalisation and comparison rules shared by the pack and grader. | |
| integer exact match after stripping whitespace and separators | |
| decimal1 numeric match within +/- 0.05 | |
| string case-insensitive, whitespace-collapsed | |
| id exact after stripping surrounding whitespace | |
| date YYYY-MM-DD, or any ISO timestamp whose date part matches | |
| """ | |
| from __future__ import annotations | |
| import re | |
| ANSWER_TYPES = ("integer", "string", "decimal1", "id", "date") | |
| _WS = re.compile(r"\s+") | |
| _DATE = re.compile(r"^(\d{4})-(\d{2})-(\d{2})") | |
| class BadAnswer(ValueError): | |
| pass | |
| def _text(value) -> str: | |
| if value is None: | |
| return "" | |
| return str(value).strip() | |
| def norm_integer(value): | |
| raw = _text(value).replace(",", "").replace("_", "") | |
| if raw.startswith("+"): | |
| raw = raw[1:] | |
| if re.fullmatch(r"-?\d+", raw): | |
| return int(raw) | |
| # tolerate an integral float such as "12.0" | |
| try: | |
| as_float = float(raw) | |
| except (TypeError, ValueError): | |
| raise BadAnswer(f"not an integer: {value!r}") | |
| if abs(as_float - round(as_float)) > 1e-9: | |
| raise BadAnswer(f"not an integer: {value!r}") | |
| return int(round(as_float)) | |
| def norm_decimal1(value): | |
| raw = _text(value).replace(",", "") | |
| try: | |
| return float(raw) | |
| except (TypeError, ValueError): | |
| raise BadAnswer(f"not a number: {value!r}") | |
| def norm_string(value): | |
| return _WS.sub(" ", _text(value)).casefold() | |
| def norm_id(value): | |
| return _text(value) | |
| def norm_date(value): | |
| raw = _text(value) | |
| match = _DATE.match(raw) | |
| if not match: | |
| raise BadAnswer(f"not a date: {value!r}") | |
| return f"{match.group(1)}-{match.group(2)}-{match.group(3)}" | |
| NORMALISERS = { | |
| "integer": norm_integer, | |
| "decimal1": norm_decimal1, | |
| "string": norm_string, | |
| "id": norm_id, | |
| "date": norm_date, | |
| } | |
| def equal(answer_type: str, expected, given) -> bool: | |
| """True when a submitted answer counts as correct for this answer type.""" | |
| if answer_type not in NORMALISERS: | |
| raise BadAnswer(f"unknown answer_type: {answer_type!r}") | |
| try: | |
| want = NORMALISERS[answer_type](expected) | |
| got = NORMALISERS[answer_type](given) | |
| except BadAnswer: | |
| return False | |
| if answer_type == "decimal1": | |
| return abs(want - got) <= 0.05 | |
| return want == got | |