Spaces:
Running
Running
Download foresightbench_env/parse.py from ruhzi/foresightbench-rl: direct link, hf CLI and curl.
- Browser
- Download file 8.44 kB
-
https://huggingface.co/spaces/ruhzi/foresightbench-rl/resolve/main/foresightbench_env/parse.py
- Command line
-
hf download hf://spaces/ruhzi/foresightbench-rl/foresightbench_env/parse.py
-
curl -L -o parse.py https://huggingface.co/spaces/ruhzi/foresightbench-rl/resolve/main/foresightbench_env/parse.py
8.44 kB
| """Pull predicted numbers out of a completion, without ever failing the run. | |
| Parsing is separated from generation on purpose. Models do not reliably emit | |
| clean JSON -- so when this gets it wrong, the fix is to improve this file and | |
| re-run `python run_pilot.py --parse-only`, which re-reads the stored raw text | |
| and costs nothing. A parse bug must never mean paying for the completions | |
| twice. | |
| Nothing here decides whether a prediction is GOOD. That is scoring, it does | |
| not exist yet, and it belongs in its own module when it does. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import re | |
| _FENCE_RE = re.compile(r"```(?:json|JSON)?\s*\n(.*?)```", re.DOTALL) | |
| _NUM_RE = re.compile(r"[-+]?(?:\d[\d,]*\.?\d*|\.\d+)(?:[eE][-+]?\d+)?") | |
| # Keys a model might use for the label and the number, in preference order. | |
| _SLOT_KEYS = ("slot", "metric", "label", "name", "benchmark_metric", "key") | |
| _VALUE_KEYS = ("value", "prediction", "predicted_value", "pred", "estimate") | |
| def _balanced_objects(text: str): | |
| """Yield every balanced {...} region, outermost first, longest first. | |
| A brace counter rather than a regex because predictions nest, and it | |
| tracks string state so a `{` inside a quoted label does not derail it. | |
| """ | |
| starts = [i for i, ch in enumerate(text) if ch == "{"] | |
| for start in starts: | |
| depth, in_str, esc = 0, False, False | |
| for i in range(start, len(text)): | |
| ch = text[i] | |
| if in_str: | |
| if esc: | |
| esc = False | |
| elif ch == "\\": | |
| esc = True | |
| elif ch == '"': | |
| in_str = False | |
| continue | |
| if ch == '"': | |
| in_str = True | |
| elif ch == "{": | |
| depth += 1 | |
| elif ch == "}": | |
| depth -= 1 | |
| if depth == 0: | |
| yield text[start:i + 1] | |
| break | |
| def _to_number(v) -> float | None: | |
| """A number, from a number or from the kind of string models write.""" | |
| if isinstance(v, bool): | |
| return None | |
| if isinstance(v, (int, float)): | |
| return float(v) | |
| if not isinstance(v, str): | |
| return None | |
| m = _NUM_RE.search(v.replace("−", "-")) # unicode minus | |
| if not m: | |
| return None | |
| try: | |
| return float(m.group(0).replace(",", "")) | |
| except ValueError: | |
| return None | |
| def _entries(obj) -> list[tuple[str, float | None]]: | |
| """Normalise whatever shape came back into [(slot_label, value)].""" | |
| preds = obj | |
| if isinstance(obj, dict): | |
| for key in ("predictions", "prediction", "results", "values", "answers"): | |
| if isinstance(obj.get(key), (list, dict)): | |
| preds = obj[key] | |
| break | |
| out: list[tuple[str, float | None]] = [] | |
| if isinstance(preds, dict): | |
| # {"AppWorld-Normal PR (in %)": 66.3, ...} | |
| for k, v in preds.items(): | |
| out.append((str(k), _to_number(v))) | |
| return out | |
| if isinstance(preds, list): | |
| for item in preds: | |
| if isinstance(item, dict): | |
| slot = next((str(item[k]) for k in _SLOT_KEYS if k in item), "") | |
| val = next((item[k] for k in _VALUE_KEYS if k in item), None) | |
| if val is None and len(item) == 1: | |
| # {"AppWorld-Normal PR": 66.3} | |
| (slot, val), = item.items() | |
| slot = str(slot) | |
| out.append((slot, _to_number(val))) | |
| else: | |
| out.append(("", _to_number(item))) | |
| return out | |
| def _candidates(text: str): | |
| """Every plausible JSON payload, best strategy first.""" | |
| fenced = _FENCE_RE.findall(text or "") | |
| for block in reversed(fenced): # the LAST block is the answer | |
| yield "fenced", block | |
| for blob in reversed(list(_balanced_objects(text or ""))): | |
| if '"predictions"' in blob or "'predictions'" in blob: | |
| yield "balanced_predictions", blob | |
| for blob in reversed(list(_balanced_objects(text or ""))): | |
| yield "balanced", blob | |
| def _norm(label: str) -> str: | |
| return re.sub(r"[^a-z0-9]+", "", (label or "").lower()) | |
| # --------------------------------------------------------- markdown fallbacks | |
| # | |
| # deepseek-v4-flash sometimes answers in markdown instead of JSON (a table on | |
| # 2608.09052-s010, a bulleted list on 2608.08911-s000). These run only after | |
| # every JSON strategy has failed, so a completion with any JSON payload is | |
| # never affected. | |
| _MD_ROW_RE = re.compile(r"^\s*\|(.+)\|\s*$") | |
| _MD_BULLET_RE = re.compile(r"^\s*[-*•]\s*([^:|]{1,80}?)\s*:\s*(.+)$") | |
| _EMPH_RE = re.compile(r"[*_`]+") | |
| def _table_entries(text: str) -> list[tuple[str, float | None]]: | |
| """[(label, value)] from markdown table rows. | |
| The value is the RIGHTMOST numeric cell: answers in this shape carry the | |
| baseline in a middle column and the prediction last, and taking anything | |
| but the rightmost cell would silently grade the model's copy of our own | |
| baseline. Rows whose last cell has no number (headers, separators) are | |
| skipped. | |
| """ | |
| out = [] | |
| for line in (text or "").splitlines(): | |
| m = _MD_ROW_RE.match(line) | |
| if not m: | |
| continue | |
| cells = [_EMPH_RE.sub("", c).strip() for c in m.group(1).split("|")] | |
| if len(cells) < 2 or all(set(c) <= set("-: ") for c in cells): | |
| continue # |---|---:| separator | |
| val = next((_to_number(c) for c in reversed(cells) | |
| if _to_number(c) is not None), None) | |
| if val is None: | |
| continue # header row | |
| out.append((cells[0], val)) | |
| return out | |
| def _bullet_entries(text: str) -> list[tuple[str, float | None]]: | |
| """[(label, value)] from '- label: **1.6 m**' style bullets, in order.""" | |
| out = [] | |
| for line in (text or "").splitlines(): | |
| m = _MD_BULLET_RE.match(line) | |
| if not m: | |
| continue | |
| val = _to_number(_EMPH_RE.sub("", m.group(2))) | |
| if val is not None: | |
| out.append((_EMPH_RE.sub("", m.group(1)).strip(), val)) | |
| return out | |
| def extract(text: str, asked: list[str]) -> dict: | |
| """Best-effort predictions for `asked`, aligned by position. | |
| Position, not label, is the key: the harness wrote the question, so it | |
| knows the order it asked in. The label is kept as a cross-check -- | |
| `label_matches` below is how you find out the model reordered or dropped | |
| a slot without having to eyeball the raw text. | |
| """ | |
| result = { | |
| "ok": False, | |
| "strategy": None, | |
| "error": None, | |
| "n_asked": len(asked), | |
| "n_returned": 0, | |
| "label_matches": 0, | |
| "values": [None] * len(asked), | |
| "returned": [], | |
| } | |
| if not (text or "").strip(): | |
| result["error"] = "empty completion" | |
| return result | |
| def fill(strategy: str, entries: list[tuple[str, float | None]]) -> dict: | |
| result["strategy"] = strategy | |
| result["returned"] = [{"slot": s, "value": v} for s, v in entries] | |
| result["n_returned"] = len(entries) | |
| values: list[float | None] = [None] * len(asked) | |
| for i, (_, val) in enumerate(entries[:len(asked)]): | |
| values[i] = val | |
| result["values"] = values | |
| result["label_matches"] = sum( | |
| 1 for (s, _), a in zip(entries, asked) if _norm(s) == _norm(a)) | |
| missing = sum(1 for v in values if v is None) | |
| if len(entries) != len(asked): | |
| result["error"] = (f"returned {len(entries)} predictions for " | |
| f"{len(asked)} asked slots") | |
| elif missing: | |
| result["error"] = f"{missing} slot(s) had no usable number" | |
| else: | |
| result["ok"] = True | |
| return result | |
| for strategy, blob in _candidates(text): | |
| try: | |
| obj = json.loads(blob) | |
| except (ValueError, TypeError): | |
| continue | |
| entries = _entries(obj) | |
| if entries: | |
| return fill(strategy, entries) | |
| # No JSON anywhere -- markdown answers are still answers. | |
| for strategy, entries in (("markdown_table", _table_entries(text)), | |
| ("markdown_bullets", _bullet_entries(text))): | |
| if entries: | |
| return fill(strategy, entries) | |
| result["error"] = "no JSON payload found in the completion" | |
| return result | |