File size: 6,662 Bytes
f91d9a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
"""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"<answer>\s*(.*?)\s*</answer>", 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,
    }