|
| 1 | +""" |
| 2 | +Quoted Spans Alignment Metric |
| 3 | +================================ |
| 4 | +
|
| 5 | +This module provides a simple metric to measure citation alignment for quoted spans |
| 6 | +in model-generated answers. The idea is to compute the fraction of quoted spans |
| 7 | +appearing verbatim in any of the provided source passages. If an answer quotes |
| 8 | +facts that cannot be found in the sources, the metric will reflect that drift. |
| 9 | +
|
| 10 | +The metric function is designed to be plug‑and‑play in existing evaluation |
| 11 | +pipelines. It returns a score in the range [0, 1] along with the raw counts for |
| 12 | +matched and total quoted spans. It performs light normalization by collapsing |
| 13 | +whitespace and lower‑casing strings. You can adjust the minimum length of a |
| 14 | +quoted span and choose to disable case folding if desired. |
| 15 | +""" |
| 16 | + |
| 17 | +from __future__ import annotations |
| 18 | + |
| 19 | +import re |
| 20 | +from typing import Dict, Sequence |
| 21 | + |
| 22 | +# Regular expression to extract both straight and curly quoted spans. Matches |
| 23 | +# pairs of quotes and captures the inner text. |
| 24 | +_QUOTE_RE = re.compile(r"[\"" "''`´](.*?)[\"" "''`´]") |
| 25 | + |
| 26 | + |
| 27 | +def _normalize(text: str) -> str: |
| 28 | + """Normalize text by collapsing whitespace and lower‑casing it.""" |
| 29 | + return re.sub(r"\s+", " ", text).strip().lower() |
| 30 | + |
| 31 | + |
| 32 | +def _extract_quoted_spans(answer: str, *, min_len: int = 3) -> Sequence[str]: |
| 33 | + """ |
| 34 | + Extract quoted spans from an answer. |
| 35 | +
|
| 36 | + Parameters |
| 37 | + ---------- |
| 38 | + answer: str |
| 39 | + The model answer to search for quoted spans. |
| 40 | + min_len: int, optional |
| 41 | + Minimum number of words required for a span to be considered. Shorter |
| 42 | + spans are ignored to avoid spurious matches. |
| 43 | +
|
| 44 | + Returns |
| 45 | + ------- |
| 46 | + Sequence[str] |
| 47 | + A list of quoted spans (strings) that meet the minimum length |
| 48 | + requirement. |
| 49 | + """ |
| 50 | + spans: list[str] = [] |
| 51 | + for match in _QUOTE_RE.finditer(answer): |
| 52 | + span = (match.group(1) or "").strip() |
| 53 | + # filter out spans shorter than min_len words |
| 54 | + if len(span.split()) >= min_len: |
| 55 | + spans.append(span) |
| 56 | + return spans |
| 57 | + |
| 58 | + |
| 59 | +def quoted_spans_alignment( |
| 60 | + answers: Sequence[str], |
| 61 | + sources: Sequence[Sequence[str]], |
| 62 | + *, |
| 63 | + casefold: bool = True, |
| 64 | + min_len: int = 3, |
| 65 | +) -> Dict[str, float]: |
| 66 | + """ |
| 67 | + Compute the citation alignment score for quoted spans in model answers. |
| 68 | +
|
| 69 | + Parameters |
| 70 | + ---------- |
| 71 | + answers: Sequence[str] |
| 72 | + List of model answers (length N). |
| 73 | + sources: Sequence[Sequence[str]] |
| 74 | + List of lists (length N) containing passages for each answer. |
| 75 | + casefold: bool, optional |
| 76 | + Whether to normalize text by lower‑casing before matching. Defaults |
| 77 | + to True. |
| 78 | + min_len: int, optional |
| 79 | + Minimum number of words in a quoted span. Defaults to 3. |
| 80 | +
|
| 81 | + Returns |
| 82 | + ------- |
| 83 | + Dict[str, float] |
| 84 | + A dictionary containing: |
| 85 | + - "citation_alignment_quoted_spans": the fraction of quoted |
| 86 | + spans found verbatim in the provided sources. |
| 87 | + - "matched": number of spans that were matched |
| 88 | + - "total": total number of spans considered |
| 89 | +
|
| 90 | + Notes |
| 91 | + ----- |
| 92 | + If no quoted spans are found across the dataset, the score is defined as |
| 93 | + 0.0, with matched=0 and total=0. Matching is substring matching on |
| 94 | + normalized text. |
| 95 | + """ |
| 96 | + if len(answers) != len(sources): |
| 97 | + raise ValueError("answers and sources must have the same length") |
| 98 | + matched = 0 |
| 99 | + total = 0 |
| 100 | + |
| 101 | + for answer, src_list in zip(answers, sources): |
| 102 | + spans = _extract_quoted_spans(answer, min_len=min_len) |
| 103 | + if not spans: |
| 104 | + continue |
| 105 | + # join all sources for this answer into one string |
| 106 | + joined_sources = " ".join(src_list) |
| 107 | + if casefold: |
| 108 | + normalized_sources = _normalize(joined_sources) |
| 109 | + else: |
| 110 | + normalized_sources = joined_sources |
| 111 | + |
| 112 | + for span in spans: |
| 113 | + total += 1 |
| 114 | + span_norm = _normalize(span) if casefold else span |
| 115 | + # check if the normalized span appears in the normalized sources |
| 116 | + if span_norm and span_norm in normalized_sources: |
| 117 | + matched += 1 |
| 118 | + |
| 119 | + score = (matched / total) if total else 0.0 |
| 120 | + return { |
| 121 | + "citation_alignment_quoted_spans": float(score), |
| 122 | + "matched": float(matched), |
| 123 | + "total": float(total), |
| 124 | + } |
0 commit comments