File size: 7,095 Bytes
1b86964
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Shared text-parsing utilities for pipeline modules."""

from __future__ import annotations

import random
import re
from typing import List, Optional


def extract_measurement(text: str) -> Optional[str]:
    """Extract content from <measurement>…</measurement> tags.

    Robust to models that emit extra opening tags or forget the closing tag.
    Returns None only if no opening tag is found.
    """
    # Prefer the LAST opening tag before the first closing tag (handles
    # doubled <measurement><measurement>...</measurement> where the content
    # starts only after the second opening tag).
    close = re.search(r"</measurement>", text)
    if close:
        prefix = text[: close.start()]
        last_open = prefix.rfind("<measurement>")
        if last_open >= 0:
            return prefix[last_open + len("<measurement>") :].strip()

    # No closing tag: take content after the LAST opening tag.
    last_open = text.rfind("<measurement>")
    if last_open >= 0:
        content = text[last_open + len("<measurement>") :].strip()
        content = re.sub(r"<\s*/?\s*[a-zA-Z]*\s*>?\s*$", "", content).rstrip()
        return content or None
    return None


def extract_complete_measurement(text: str) -> Optional[str]:
    """Extract a measurement only when both opening and closing tags exist."""
    close = re.search(r"</measurement>", text)
    if not close:
        return None
    prefix = text[: close.start()]
    last_open = prefix.rfind("<measurement>")
    if last_open < 0:
        return None
    content = prefix[last_open + len("<measurement>") :].strip()
    return content or None


def normalize_prediction_label(text: str) -> str:
    """Normalize a prediction label to a bare option number.

    Accepts current number-only labels (``"2"``) and legacy labels
    (``"Option 2"``). Returns the first integer as a string.
    """
    m = re.search(r"(?:option\s*)?(\d+)", text.strip(), re.IGNORECASE)
    if not m:
        raise ValueError(f"Could not parse prediction label: {text!r}")
    return m.group(1)


def split_numbered_answers(text: str, n: int) -> list[str] | None:
    """Return explicit Q answer blocks in order, or None for unnumbered text.

    Answers without Q labels retain their original line order. If Q labels are
    present, every question must occur exactly once; a duplicated label cannot
    stand in for a missing answer.
    """
    matches = list(re.finditer(r"^\s*Q\s*(\d+)\s*[:.)-]\s*", text, flags=re.IGNORECASE | re.MULTILINE))
    if not matches:
        return None
    numbers = [int(m.group(1)) for m in matches]
    if len(numbers) != n or set(numbers) != set(range(1, n + 1)):
        raise ValueError("Answer Q numbers must cover each question exactly once")
    blocks = {}
    for i, match in enumerate(matches):
        end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
        blocks[numbers[i]] = text[match.end():end].strip()
    if any(not block for block in blocks.values()):
        raise ValueError("Each numbered question requires an answer")
    return [blocks[i] for i in range(1, n + 1)]


def parse_batch_predictions(text: str, n: int) -> List[str]:
    """Parse number-only prediction lines, with legacy 'Option N' support.

    Raises ValueError if the number of parsed predictions != n.
    """
    preds = []
    for line in text.splitlines():
        line = line.strip()
        m = re.match(
            r"(?:Q\s*\d+\s*[:.)-]\s*)?(?:Option\s*)?(\d+)\b",
            line,
            re.IGNORECASE,
        )
        if m:
            preds.append(m.group(1))
    if len(preds) != n:
        raise ValueError(f"Expected {n} predictions, got {len(preds)}: {text!r}")
    return preds


def parse_numeric_predictions(text: str, n: int) -> List[str]:
    """Parse one numeric prediction per line.

    Used by regression-style domains whose targets are continuous scores rather
    than option ids. We accept plain integers/floats and tolerate labels such as
    ``Q1: 73.5`` by taking the last number on each non-empty line.
    """
    preds = []
    for line in text.splitlines():
        line = line.strip()
        if not line:
            continue
        nums = re.findall(r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)", line)
        if nums:
            preds.append(format_numeric_label(nums[-1]))
    if len(preds) != n:
        raise ValueError(f"Expected {n} numeric predictions, got {len(preds)}: {text!r}")
    return preds


def parse_generation_predictions(text: str, n: int, *, tag: str = "comment") -> List[str]:
    """Parse generated free-text predictions from XML-ish tags.

    Generation tasks may contain arbitrary punctuation and newlines, so the
    classification/regression line parsers are not appropriate. We require one
    tagged block per prediction for batched outputs. For single-question calls,
    bare text is accepted as a fallback to make interactive eval less brittle.
    """
    pattern = rf"<\s*{re.escape(tag)}\s*>(.*?)<\s*/\s*{re.escape(tag)}\s*>"
    matches = [m.strip() for m in re.findall(pattern, text, flags=re.IGNORECASE | re.DOTALL)]
    if len(matches) == n:
        return matches
    if n == 1 and not matches:
        stripped = text.strip()
        if stripped:
            return [stripped]
    raise ValueError(f"Expected {n} <{tag}> predictions, got {len(matches)}: {text!r}")


def format_numeric_label(value: str | float | int) -> str:
    """Format a numeric label compactly while preserving decimal values."""
    v = float(value)
    if v.is_integer():
        return str(int(v))
    return f"{v:.6f}".rstrip("0").rstrip(".")


def format_generation_label(value: str, *, tag: str = "comment") -> str:
    """Wrap a free-text supervised target in the generation prediction tag."""
    return f"<{tag}>\n{value.strip()}\n</{tag}>"


def rouge_l_f1(prediction: str, reference: str) -> float:
    """Compute deterministic ROUGE-L F1 over lowercase word tokens."""
    pred_tokens = re.findall(r"\w+", prediction.lower())
    ref_tokens = re.findall(r"\w+", reference.lower())
    if not pred_tokens or not ref_tokens:
        return 0.0

    prev = [0] * (len(ref_tokens) + 1)
    for pred_tok in pred_tokens:
        curr = [0]
        for j, ref_tok in enumerate(ref_tokens, start=1):
            if pred_tok == ref_tok:
                curr.append(prev[j - 1] + 1)
            else:
                curr.append(max(prev[j], curr[-1]))
        prev = curr
    lcs = prev[-1]
    if lcs == 0:
        return 0.0
    precision = lcs / len(pred_tokens)
    recall = lcs / len(ref_tokens)
    return 2 * precision * recall / (precision + recall)


def shuffled_observations(
    observations: List[str],
    seed: int,
    sample_index: int,
    candidate_k: int,
) -> List[str]:
    """Return a deterministically shuffled copy of *observations*.

    Each (sample_index, candidate_k) pair produces a distinct ordering,
    giving diversity across parallel candidate generations.
    """
    rng = random.Random(seed ^ (sample_index * 31337) ^ (candidate_k * 7919))
    obs = list(observations)
    rng.shuffle(obs)
    return obs