"""Pure parsing helpers for benchmark model outputs.""" from __future__ import annotations import json import re from typing import Any, Iterable, Mapping FENCED_JSON_RE = re.compile(r"^\s*```(?:json|JSON)?\s*(.*?)\s*```\s*$", re.DOTALL) def strip_markdown_json_fence(text: str) -> str: cleaned = str(text or "").strip() match = FENCED_JSON_RE.match(cleaned) return match.group(1).strip() if match else cleaned def extract_json_text(text: str) -> str | None: cleaned = strip_markdown_json_fence(text) if not cleaned: return None start = cleaned.find("{") if start < 0: return None depth = 0 in_string = False escape = False for idx, char in enumerate(cleaned[start:], start=start): if in_string: if escape: escape = False elif char == "\\": escape = True elif char == '"': in_string = False continue if char == '"': in_string = True elif char == "{": depth += 1 elif char == "}": depth -= 1 if depth == 0: return cleaned[start : idx + 1] return None def extract_json_payload(text: str) -> dict[str, Any] | None: payload_text = extract_json_text(text) if not payload_text: return None try: payload = json.loads(payload_text) except Exception: return None return payload if isinstance(payload, dict) else None def normalize_step_id(value: Any) -> str | None: if value is None: return None text = str(value).strip() if not text or text.lower() == "null": return None match = re.fullmatch(r"(?:step|s)[_\-\s]*(\d+)", text, flags=re.IGNORECASE) if match: return match.group(1) digits = re.sub(r"\D+", "", text) return digits or None def parse_bool_field(value: Any) -> bool | None: if isinstance(value, bool): return value if value is None: return None text = str(value).strip().lower() if text in {"true", "yes", "y", "1", "correct"}: return True if text in {"false", "no", "n", "0", "incorrect"}: return False return None def parse_step_field(value: Any) -> str | None: return normalize_step_id(value) def _normalize_option(value: Any) -> str: return re.sub(r"[\s\-]+", "_", str(value or "").strip().upper()) def strip_answer_tag(text: str) -> str: cleaned = str(text or "").strip() match = re.fullmatch(r"\s*(.*?)\s*", cleaned, flags=re.IGNORECASE | re.DOTALL) return match.group(1).strip() if match else cleaned def parse_choice_option( text: str, options: Iterable[str], *, json_keys: Iterable[str] = ("option", "answer", "prediction", "pred_option", "choice", "label", "mistake_type"), number_map: Mapping[str, str] | None = None, ) -> str | None: option_list = [_normalize_option(option) for option in options] option_set = set(option_list) normalized_number_map = { str(key): _normalize_option(value) for key, value in (number_map or {}).items() } payload = extract_json_payload(text) if payload is not None: for key in json_keys: if key not in payload: continue parsed = parse_choice_option( str(payload[key]), option_list, json_keys=(), number_map=normalized_number_map, ) if parsed is not None: return parsed cleaned = strip_answer_tag(strip_markdown_json_fence(text)) upper = _normalize_option(cleaned) if upper in option_set: return upper if upper in normalized_number_map: return normalized_number_map[upper] first_line = cleaned.splitlines()[0].strip() if cleaned else "" first_token = re.split(r"[\s:.)\-\]]+", first_line, maxsplit=1)[0].strip().upper() if first_token in normalized_number_map: return normalized_number_map[first_token] if first_token in option_set: return first_token pattern = r"\b(" + "|".join(re.escape(option) for option in sorted(option_set, key=len, reverse=True)) + r")\b" matches = re.findall(pattern, _normalize_option(cleaned)) unique = sorted(set(matches)) return unique[0] if len(unique) == 1 else None def parse_monitoring_response(text: str) -> tuple[bool | None, str | None]: cleaned = strip_markdown_json_fence(text) payload = extract_json_payload(cleaned) if payload is not None: candidate = parse_bool_field(payload.get("candidate_matches_visible_step")) step_id = payload.get("observed_step_id") step_value = None if step_id in (None, "", "null") else str(step_id) return candidate, step_value upper = cleaned.upper() if re.search(r"\b(TRUE|YES)\b", upper): return True, None if re.search(r"\b(FALSE|NO)\b", upper): return False, None return None, None def parse_next_step_delta_response(text: str) -> dict[str, Any]: payload = extract_json_payload(text) if payload is None: return { "pred_current_step_id": None, "pred_has_error": None, "pred_has_step_skipped": None, "pred_error_type": None, "pred_error_step_id": None, "pred_parse_ok": False, } current = payload.get("current_step") if current in (None, "", "null"): current = None errors = payload.get("errors") if not isinstance(errors, list): errors = [] parsed_errors = [item for item in errors if isinstance(item, dict)] error_types = [ str(item.get("error_type") or "").strip() for item in parsed_errors if str(item.get("error_type") or "").strip() ] non_none_error_types = [kind for kind in error_types if kind.lower() != "none"] skipped = any(kind.lower() == "step_skipped" for kind in error_types) step_ref = None for item in parsed_errors: if str(item.get("error_type") or "").strip().lower() == "step_skipped": step_ref = item.get("step_ref") break if step_ref in (None, "", "null"): step_ref = None return { "pred_current_step_id": None if current is None else str(current), "pred_has_error": bool(non_none_error_types), "pred_has_step_skipped": skipped, "pred_error_type": non_none_error_types[0] if non_none_error_types else None, "pred_error_step_id": None if step_ref is None else str(step_ref), "pred_parse_ok": True, }