File size: 10,190 Bytes
0084562
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7eda9ec
 
 
 
 
0084562
 
 
 
 
 
 
 
 
7eda9ec
f664bab
 
 
0084562
 
 
 
f664bab
7eda9ec
 
 
 
 
 
 
 
 
 
0084562
 
 
 
 
f664bab
6e8ca17
0084562
 
 
 
 
 
 
f664bab
0084562
7eda9ec
 
 
0084562
 
 
 
f664bab
7eda9ec
 
 
0084562
f664bab
0084562
f664bab
7eda9ec
 
 
 
 
 
 
 
0084562
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7eda9ec
0084562
7eda9ec
0084562
7eda9ec
 
0084562
 
 
 
 
0370135
0084562
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b6ba86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0084562
 
7eda9ec
 
f664bab
 
0084562
f664bab
 
 
 
0084562
f664bab
 
 
 
 
0084562
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
# from __future__ import annotations

# import re


# FLUFF_LINES = {
#     "i hope this helps",
#     "hope this helps",
#     "let me know if you need anything else",
#     "thanks",
# }


# def extract_final_answer(text: str) -> str:
#     if text is None:
#         return ""

#     text = str(text).strip()
#     if not text:
#         return ""

#     text = re.sub(r"^```[a-zA-Z0-9_-]*\s*", "", text)
#     text = re.sub(r"\s*```$", "", text)

#     # Strong preference: explicit final-answer style markers
#     explicit_patterns = [
#         r"(?is)\bfinal answer\s*:\s*(.+)$",
#         r"(?is)\banswer\s*:\s*(.+)$",
#         r"(?is)\bthe answer is\s*:\s*(.+)$",
#         r"(?is)\bthe answer is\s+(.+)$",
#     ]
#     for pattern in explicit_patterns:
#         match = re.search(pattern, text)
#         if match:
#             candidate = match.group(1).strip()
#             candidate_lines = [line.strip() for line in candidate.splitlines() if line.strip()]
#             if candidate_lines:
#                 return candidate_lines[0]

#     lines = [line.strip() for line in text.splitlines() if line.strip()]
#     if not lines:
#         return ""

#     # Prefer short non-fluff lines near the end
#     for line in reversed(lines):
#         normalized = normalize_basic_answer(line).lower()
#         if normalized and normalized not in FLUFF_LINES and len(normalized) <= 200:
#             return line

#     return lines[-1]


# def normalize_basic_answer(text: str) -> str:
#     if text is None:
#         return ""

#     text = str(text).strip()
#     if not text:
#         return ""

#     text = re.sub(r"\s+", " ", text).strip()
#     text = re.sub(r"(?i)^(final answer|answer)\s*:\s*", "", text).strip()

#     if len(text) >= 2 and text[0] == text[-1] and text[0] in {'"', "'"}:
#         text = text[1:-1].strip()

#     if text.endswith(".") and not re.fullmatch(r"\d+\.\d+", text):
#         text = text[:-1].strip()

#     return text


# def normalize_final_answer(question: str, text: str) -> str:
#     text = normalize_basic_answer(text)
#     if not text:
#         return ""

#     q = question.lower()

#     # first name only
#     if "give only the first name" in q or "first name only" in q:
#         text = re.split(r"\s+", text.strip())[0]

#     # last name only
#     if "last names only" in q or "use their last names only" in q:
#         parts = [part.strip() for part in text.split(",")]
#         cleaned_parts = []
#         for part in parts:
#             tokens = part.split()
#             cleaned_parts.append(tokens[-1] if tokens else part)
#         text = ", ".join(cleaned_parts)

#     # city only
#     if "just give me the city name" in q or "city name without abbreviations" in q:
#         text = re.split(r"[,;()\-]", text)[0].strip()

#     # comma-delimited / comma separated list
#     if "comma separated list" in q or "comma-delimited list" in q or "comma delimited list" in q:
#         parts = [p.strip() for p in re.split(r",|\n", text) if p.strip()]
#         text = ",".join(parts)

#     # ascending order / alphabetical
#     if "ascending order" in q:
#         try:
#             nums = [int(x.strip()) for x in text.split(",") if x.strip()]
#             text = ",".join(str(n) for n in sorted(nums))
#         except Exception:
#             pass

#     if "alphabetical order" in q or "alphabetize" in q or "alphabetized" in q:
#         parts = [p.strip() for p in text.split(",") if p.strip()]
#         if parts:
#             text = ",".join(sorted(parts, key=lambda x: x.lower()))

#     # two decimal places
#     if "two decimal places" in q:
#         number_match = re.search(r"-?\d+(?:\.\d+)?", text.replace(",", ""))
#         if number_match:
#             try:
#                 value = float(number_match.group(0))
#                 text = f"{value:.2f}"
#             except Exception:
#                 pass

#     # IOC code / abbreviations / codes often expected uppercase single token
#     if "ioc country code" in q:
#         text = text.strip().upper()

#     # algebraic notation answer should be just one move token-like string
#     if "algebraic notation" in q:
#         text = text.strip().split()[0]

#     return text


# def is_placeholder_answer(text: str) -> bool:
#     normalized = normalize_basic_answer(text).lower()
#     return normalized in {"", "placeholder", "n/a", "unknown"}


from __future__ import annotations

import re


_FLUFF_LINES = {
    "i hope this helps",
    "hope this helps",
    "let me know if you need anything else",
    "thanks",
    "thank you",
}


def extract_final_answer(text: str) -> str:
    """
    Extract the most likely final answer from raw model output.

    Strategy:
    - prefer explicit markers like 'Final answer:'
    - strip code fences
    - if multiline, prefer a short meaningful line near the end
    """
    if text is None:
        return ""

    text = str(text).strip()
    if not text:
        return ""

    text = re.sub(r"^```[a-zA-Z0-9_-]*\s*", "", text)
    text = re.sub(r"\s*```$", "", text)

    explicit_patterns = [
        r"(?is)\bfinal answer\s*:\s*(.+)$",
        r"(?is)\banswer\s*:\s*(.+)$",
        r"(?is)\bthe answer is\s*:\s*(.+)$",
        r"(?is)\bthe answer is\s+(.+)$",
    ]

    for pattern in explicit_patterns:
        match = re.search(pattern, text)
        if match:
            candidate = match.group(1).strip()
            candidate_lines = [line.strip() for line in candidate.splitlines() if line.strip()]
            if candidate_lines:
                return candidate_lines[0]

    lines = [line.strip() for line in text.splitlines() if line.strip()]
    if not lines:
        return ""

    for line in reversed(lines):
        normalized = normalize_basic_answer(line).lower()
        if normalized and normalized not in _FLUFF_LINES and len(normalized) <= 200:
            return line

    return lines[-1]


def normalize_basic_answer(text: str) -> str:
    """
    Basic cleanup independent of question format.
    """
    if text is None:
        return ""

    text = str(text).strip()
    if not text:
        return ""

    text = re.sub(r"\s+", " ", text).strip()
    text = re.sub(r"(?i)^(final answer|answer)\s*:\s*", "", text).strip()

    if len(text) >= 2 and text[0] == text[-1] and text[0] in {'"', "'"}:
        text = text[1:-1].strip()

    if text.endswith(".") and not re.fullmatch(r"-?\d+\.\d+", text):
        text = text[:-1].strip()

    return text


def normalize_final_answer(*args: str) -> str:
    """
    Backward-compatible normalizer.

    Supports:
    - normalize_final_answer(text)
    - normalize_final_answer(question, text)
    """
    if len(args) == 1:
        question = ""
        text = args[0]
    elif len(args) == 2:
        question, text = args
    else:
        return ""

    text = normalize_basic_answer(text)
    if not text:
        return ""

    q = (question or "").lower()

    # Remove outer labels once more, conservatively
    text = re.sub(r"(?i)^(final answer|answer)\s*:\s*", "", text).strip()

    # first name only
    if "give only the first name" in q or "first name only" in q:
        tokens = text.split()
        if tokens:
            text = tokens[0]

    # last name only
    if "last names only" in q or "use their last names only" in q:
        parts = [part.strip() for part in text.split(",") if part.strip()]
        if parts:
            cleaned_parts: list[str] = []
            for part in parts:
                tokens = part.split()
                cleaned_parts.append(tokens[-1] if tokens else part)
            text = ", ".join(cleaned_parts)

    # surname only
    if "what is the surname" in q or "surname of" in q:
        tokens = text.split()
        if tokens:
            text = tokens[-1]

    # city only
    if "city name without abbreviations" in q or "just give me the city name" in q:
        text = re.split(r"[,;()\-]", text)[0].strip()

    # IOC code
    if "ioc country code" in q:
        text = text.strip().upper()

    # algebraic notation
    if "algebraic notation" in q:
        text = text.strip().split()[0]

    # comma-separated list formatting
    if (
        "comma separated list" in q
        or "comma-separated list" in q
        or "comma delimited list" in q
        or "comma-delimited list" in q
        or "comma separated" in q
    ):
        parts = [p.strip() for p in re.split(r",|\n", text) if p.strip()]
        text = ",".join(parts)

    # ascending order
    if "ascending order" in q:
        try:
            nums = [int(x.strip()) for x in text.split(",") if x.strip()]
            text = ",".join(str(n) for n in sorted(nums))
        except Exception:
            pass

    # alphabetical order
    if "alphabetical order" in q or "alphabetize" in q or "alphabetized" in q:
        parts = [p.strip() for p in text.split(",") if p.strip()]
        if parts:
            text = ",".join(sorted(parts, key=lambda x: x.lower()))

    # two decimal places
    if "two decimal places" in q:
        compact = text.replace(",", "")
        match = re.search(r"-?\d+(?:\.\d+)?", compact)
        if match:
            try:
                value = float(match.group(0))
                text = f"{value:.2f}"
            except Exception:
                pass
    if "nasa award number" in q:
        text = text.replace("NASA award number", "").strip()

    if "city name without abbreviations" in q:
        text = text.replace("St. Petersburg", "Saint Petersburg").strip()

    if "use their last names only" in q:
        parts = [p.strip() for p in text.split(",") if p.strip()]
        last_names = []
        for part in parts:
            tokens = part.split()
            if tokens:
                last_names.append(tokens[-1])
        if last_names:
            text = ",".join(last_names)

    return text.strip()


def is_placeholder_answer(text: str) -> bool:
    """
    Detect placeholder/fallback outputs.
    """
    if text is None:
        return True

    normalized = normalize_basic_answer(text).lower()
    return normalized in {
        "",
        "placeholder",
        "n/a",
        "unknown",
    }