Download oracle.py from debudash/slm-training: direct link, hf CLI and curl.
- Browser
- Download file 5.67 kB
-
https://huggingface.co/debudash/slm-training/resolve/main/oracle.py
- Command line
-
hf download hf://debudash/slm-training/oracle.py
-
curl -L -o oracle.py https://huggingface.co/debudash/slm-training/resolve/main/oracle.py
5.67 kB
| """The source of truth: the exact reply behaviour.spec requires for a structured request. | |
| The caller supplies each component exactly as written in the message (None if missing), plus the two | |
| judgement labels the spec can't compute: whether the message is a conversion request at all, and which | |
| components the message leaves unclear (e.g. two zones with no from/to). | |
| """ | |
| import json | |
| import re | |
| from dataclasses import dataclass, field | |
| from datetime import date as Date, datetime, time as Time, timedelta, timezone | |
| from pathlib import Path | |
| from zoneinfo import ZoneInfo | |
| ROOT = Path(__file__).resolve().parent | |
| ABBREVIATIONS = json.loads((ROOT / "abbreviations.json").read_text(encoding="utf-8")) | |
| ZONES = json.loads((ROOT / "zones.json").read_text(encoding="utf-8"))["zones"] | |
| FIRST_YEAR, LAST_YEAR = 2020, 2030 | |
| ORDER = ("date", "time", "source_timezone", "target_timezone") | |
| class Request: | |
| date: str | None | |
| time: str | None | |
| source: str | None | |
| target: str | None | |
| is_request: bool = True | |
| unclear: frozenset = field(default_factory=frozenset) | |
| class Invalid(Exception): | |
| pass | |
| class Ambiguous(Exception): | |
| pass | |
| def _parse_date(text): | |
| if text is None: | |
| raise Invalid | |
| if m := re.fullmatch(r"(\d{4})-(\d{2})-(\d{2})", text): | |
| readings = {(int(m[1]), int(m[2]), int(m[3]))} | |
| elif m := re.fullmatch(r"(\d{2})/(\d{2})/(\d{4})", text): | |
| a, b, year = int(m[1]), int(m[2]), int(m[3]) | |
| readings = {(year, a, b), (year, b, a)} # month/day and day/month | |
| else: | |
| raise Invalid | |
| valid = set() | |
| for y, mo, d in readings: | |
| try: | |
| valid.add(Date(y, mo, d)) | |
| except ValueError: | |
| pass | |
| if not valid or not FIRST_YEAR <= next(iter(valid)).year <= LAST_YEAR: | |
| raise Invalid | |
| if len(valid) > 1: | |
| raise Ambiguous | |
| return valid.pop() | |
| def _parse_time(text): | |
| m = re.fullmatch(r"(\d{2}):(\d{2})(?::(\d{2}))?", text or "") | |
| if not m: | |
| raise Invalid | |
| try: | |
| return Time(int(m[1]), int(m[2]), int(m[3] or 0)) | |
| except ValueError: | |
| raise Invalid | |
| def _offset(sign, hours, minutes): | |
| return (-1 if sign == "-" else 1) * timedelta(hours=int(hours), minutes=int(minutes)) | |
| def _parse_zone(text): | |
| """('iana', ZoneInfo, None), ('offset', timezone, None) or ('abbr', ZoneInfo, offset).""" | |
| if text is None: | |
| raise Invalid | |
| if "/" in text: | |
| if text in ZONES or re.fullmatch(r"Etc/GMT[+-]\d{1,2}", text): | |
| try: | |
| return "iana", ZoneInfo(text), None | |
| except Exception: # Etc/GMT+13 and the like don't exist in tzdata | |
| raise Invalid | |
| raise Invalid | |
| if m := re.fullmatch(r"(?:UTC)?([+-])(\d{2}):(\d{2})", text): | |
| off = _offset(*m.groups()) | |
| if int(m[3]) > 59 or not timedelta(hours=-12) <= off <= timedelta(hours=14): | |
| raise Invalid | |
| return "offset", timezone(off), None | |
| if re.fullmatch(r"[A-Z]{2,5}", text): | |
| if text in ABBREVIATIONS["ambiguous"]: | |
| raise Ambiguous | |
| if entry := ABBREVIATIONS["unambiguous"].get(text): | |
| return "abbr", ZoneInfo(entry["zone"]), _offset(entry["offset"][0], *entry["offset"][1:].split(":")) | |
| raise Invalid | |
| def _to_utc(local, source): | |
| kind, zone, offset = source | |
| if kind != "abbr": | |
| # fold=0: the earlier instance of a repeated time; a skipped time shifts forward by the gap | |
| return local.replace(tzinfo=zone).astimezone(timezone.utc) | |
| # An abbreviation is in season only if the zone really shows that offset at this wall time. | |
| # A skipped time fails the round trip for both folds, so it is never in season. | |
| for fold in (0, 1): | |
| aware = local.replace(tzinfo=zone, fold=fold) | |
| real = aware.astimezone(timezone.utc).astimezone(zone).replace(tzinfo=None) == local | |
| if real and aware.utcoffset() == offset: | |
| return (local - offset).replace(tzinfo=timezone.utc) | |
| raise Ambiguous | |
| def _from_utc(instant, target): | |
| kind, zone, offset = target | |
| out = instant.astimezone(zone) | |
| if kind == "abbr" and out.utcoffset() != offset: | |
| raise Ambiguous | |
| return out | |
| def evaluate(req: Request) -> str: | |
| if not req.is_request: | |
| return "INVALID: input" | |
| parsers = {"date": (_parse_date, req.date), "time": (_parse_time, req.time), | |
| "source_timezone": (_parse_zone, req.source), "target_timezone": (_parse_zone, req.target)} | |
| values, invalid, ambiguous = {}, [], [] | |
| for name in ORDER: | |
| parse, text = parsers[name] | |
| try: | |
| values[name] = parse(text) | |
| except Invalid: | |
| invalid.append(name) | |
| except Ambiguous: | |
| ambiguous.append(name) | |
| if name in req.unclear: | |
| ambiguous.append(name) | |
| # Priority: any INVALID outranks any AMBIGUOUS; within a kind, the first component in ORDER. | |
| if invalid: | |
| return f"INVALID: {invalid[0]}" | |
| if ambiguous: | |
| return f"AMBIGUOUS: {min(ambiguous, key=ORDER.index)}" | |
| # Season checks need a resolved date and time, so they run after the form checks. | |
| local = datetime.combine(values["date"], values["time"]) | |
| try: | |
| instant = _to_utc(local, values["source_timezone"]) | |
| except Ambiguous: | |
| return "AMBIGUOUS: source_timezone" | |
| try: | |
| out = _from_utc(instant, values["target_timezone"]) | |
| except Ambiguous: | |
| return "AMBIGUOUS: target_timezone" | |
| return out.isoformat(timespec="seconds") | |