File size: 6,515 Bytes
aa02235
9b3dd78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa02235
9b3dd78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa02235
9b3dd78
 
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
"""Reference scoring implementation for asmachta.json.

Verifies that a model's claimed quotes actually appear in the source
document -- the same method used to produce this dataset's own
`verified` / `verification_method` fields (see README, "Support
sentences: how grounding works"). No dependencies beyond the standard
library.

Expected model output format, one claim per line:

    1. <claim text> [<verbatim quote from source_text>]
    2. <claim text> [<verbatim quote from source_text>]

Usage as a library:

    from score import parse_claims, score_answer

    claims = parse_claims(model_output_text)
    result = score_answer(claims, record["source_text"])
    print(result["precision"], result["claims"])

Usage as a script (demo against the dataset's own reference answers,
which should score at or near 100% grounded since they are the source
of the verified attribution spans):

    python3 score.py asmachta.json
"""
from __future__ import annotations

import difflib
import json
import re
import sys

CLAIM_RE = re.compile(r"^\s*\d+\.\s*(.+?)\s*\[(.+?)\]\s*$", re.MULTILINE)

# Fallback for output where the model prefixed the numbered claim with
# leftover text on the same line (e.g. reasoning-model self-talk, or a
# stray closing </think> tag never on its own line) -- CLAIM_RE's line
# anchor then finds nothing even though a real, checkable quote is
# right there. This pattern doesn't require the claim to start at the
# beginning of a line, only that "N." is immediately followed by claim
# text and a bracketed quote. Only used as a fallback: if CLAIM_RE finds
# anything at all, its output is used unchanged, so this never changes
# scoring for output that was already parsing correctly.
CLAIM_RE_FALLBACK = re.compile(r"(?:^|\.)?\s*\d+\.\s*(.+?)\s*\[([^\[\]]{3,})\]", re.MULTILINE)

# Same 0.94 similarity threshold this dataset's own offset-validation
# pipeline used for near-exact (whitespace/punctuation-level) matches.
FUZZY_THRESHOLD = 0.94


def parse_claims(text: str) -> list[dict]:
    """Extract (claim, quote) pairs from `N. claim [quote]`-formatted text.

    Tries the strict, line-anchored pattern first; only falls back to a
    more permissive pattern if that finds nothing at all. This recovers
    real quotes hidden behind formatting noise without changing the
    result for output that already parses cleanly -- see CLAIM_RE_FALLBACK.
    """
    matches = CLAIM_RE.findall(text)
    if not matches:
        matches = CLAIM_RE_FALLBACK.findall(text)
    return [{"text": m[0].strip(), "quote": m[1].strip()} for m in matches]


def _normalize(s: str) -> str:
    return re.sub(r"\s+", " ", s).strip()


def verify_quote(quote: str, source_text: str) -> dict:
    """Check whether `quote` appears in `source_text`, exact/normalized/fuzzy."""
    if quote in source_text:
        return {"verified": True, "method": "exact", "score": 1.0}

    if _normalize(quote) in _normalize(source_text):
        return {"verified": True, "method": "normalized_space", "score": 1.0}

    sm = difflib.SequenceMatcher(None, source_text, quote, autojunk=False)
    match = sm.find_longest_match(0, len(source_text), 0, len(quote))
    if match.size == 0:
        return {"verified": False, "method": "fuzzy", "score": 0.0}
    pad = len(quote) - match.size
    window = source_text[max(0, match.a - pad): min(len(source_text), match.a + match.size + pad)]
    ratio = difflib.SequenceMatcher(None, _normalize(window), _normalize(quote)).ratio()
    return {"verified": ratio >= FUZZY_THRESHOLD, "method": "fuzzy", "score": ratio}


def score_answer(claims: list[dict], source_text: str) -> dict:
    """Score a list of {"text", "quote"} claims against a source document.

    Returns per-claim verification results plus overall attribution
    precision (grounded claims / total claims).
    """
    scored = []
    grounded = 0
    for c in claims:
        v = verify_quote(c["quote"], source_text)
        scored.append({**c, **v})
        if v["verified"]:
            grounded += 1
    n = len(claims)
    return {
        "n_claims": n,
        "n_grounded": grounded,
        "precision": grounded / n if n else None,
        "claims": scored,
    }


def score_model_output(text: str, source_text: str) -> dict:
    """End-to-end: parse a raw model response and score it against a document."""
    return score_answer(parse_claims(text), source_text)


def _demo(dataset_path: str) -> None:
    with open(dataset_path, encoding="utf-8") as f:
        records = json.load(f)

    # `reference_answer` is plain prose -- the dataset's own claim/quote
    # structure lives in `claims[].attribution[]`, not embedded as
    # "N. claim [quote]" text. Re-verify verify_quote() against that
    # structure directly, for the first 5 answerable records: this
    # should reproduce every `verified: true` the dataset already ships.
    print("Re-verifying this file's own claims[].attribution[] spans with")
    print("verify_quote() (sanity check -- should match every 'verified' field):\n")

    shown = 0
    for r in records:
        if r["difficulty"] == 0:
            continue
        n = sum(len(c["attribution"]) for c in r["claims"])
        agree = 0
        for c in r["claims"]:
            for a in c["attribution"]:
                v = verify_quote(a["source_excerpt"], r["source_text"])
                if v["verified"] == a["verified"]:
                    agree += 1
        print(f"  {r['id']}: {agree}/{n} spans match the dataset's own 'verified' label")
        shown += 1
        if shown >= 5:
            break

    print("\nScoring a MODEL's raw output (the 'N. claim [quote]' format from")
    print("the README) against a source document -- a fabricated example, one")
    print("real claim and one hallucinated claim:")
    r = next(r for r in records if r["difficulty"] != 0)
    real_excerpt = r["claims"][0]["attribution"][0]["source_excerpt"]
    fake_output = (
        f"1. טענה אמיתית שנתמכת במסמך. [{real_excerpt}]\n"
        f"2. משהו שלא נכתב במסמך כלל ולעולם לא יימצא שם. [ציטוט מומצא שלא קיים]"
    )
    result = score_model_output(fake_output, r["source_text"])
    print(f"  {result['n_grounded']}/{result['n_claims']} claims grounded "
          f"(precision={result['precision']:.2f})")


if __name__ == "__main__":
    if len(sys.argv) != 2:
        print(f"Usage: python3 {sys.argv[0]} asmachta.json", file=sys.stderr)
        sys.exit(1)
    _demo(sys.argv[1])