chiron-data / code /utils /text_utils.py
henry-yeh's picture htr234234's picture
Chiron data release
1b86964
Raw History Blame Contribute Delete
7.1 kB
"""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