File size: 9,378 Bytes
a805048
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Evaluation metrics for EvidenceGuard AI (all computed from the generated question set).

Retrieval        Precision@K, Recall@K, MRR                       (gold unit = document + page)
Answer quality   Answer correctness (key-fact match / correct abstention),
                 Faithfulness (claims supported by the retrieved context),
                 Evidence-grounded faithfulness (claims that come from the gold evidence pages),
                 Answer relevance (TF-IDF cosine question vs answer - lexical proxy),
                 Context precision (rank-weighted AP@K), Context recall (key facts present in context)
Reliability      Unsupported answer rate, Abstention accuracy/P/R/F1,
                 Contradiction detection P/R/F1, Citation support accuracy, Behaviour accuracy
Efficiency       mean total / retrieval / generation / verification time (seconds)
"""
from __future__ import annotations

import re
import statistics as st

from src.text_utils import fact_values, keyword_present, normalize, split_sentences

_ABSTAIN_PAT = re.compile(r"(could not find sufficient evidence|insufficient_evidence|do(es)? not (contain|mention|"
                          r"provide|specify)|not (mentioned|specified|available) in|no information)", re.I)


def is_abstention(result: dict) -> bool:
    return result["decision"] == "abstained" or bool(_ABSTAIN_PAT.search(result["answer"] or ""))


def _gold_units(q):
    return {(e["doc_id"], e["page"]) for e in q["evidence"]}


def _support(sentence: str, text: str) -> bool:
    """Loose support check used only for evaluation: values present + >=70% token overlap."""
    s_vals, t_vals = fact_values(sentence), fact_values(text)
    if s_vals - t_vals:
        return False
    st_ = set(re.findall(r"[a-z0-9]+", normalize(sentence)))
    tt = set(re.findall(r"[a-z0-9]+", normalize(text)))
    return len(st_ & tt) / max(1, len(st_)) >= 0.7


def score_question(q: dict, r: dict, page_text: dict, relevance_fn=None) -> dict:
    gold = _gold_units(q)
    ctx = r["passages"]
    units = [(p["doc_id"], p["page"]) for p in ctx]
    k = max(1, len(units))
    rel_flags = [u in gold for u in units]
    has_gold = bool(gold)
    abst = is_abstention(r)
    exp_abst = q["expected_behaviour"] == "abstain"
    answer = r["answer"] or ""
    kws = q["answer_keywords"]
    kw_hits = [keyword_present(answer, kw) for kw in kws]
    ctx_text = " ".join(p["text"] for p in ctx)

    # ---------------- correctness
    if exp_abst:
        correct = abst
    else:
        correct = (not abst) and all(kw_hits)
    flagged = r["decision"] == "conflict" or bool(r.get("conflicts"))
    if q["expected_behaviour"] == "flag_conflict":
        behaviour_ok = (not abst) and flagged and all(kw_hits)
    elif exp_abst:
        behaviour_ok = abst
    else:
        behaviour_ok = (not abst) and all(kw_hits)

    # ---------------- faithfulness of answer claims
    claims = [s for s, _ in r.get("claims", [])] if r.get("claims") else split_sentences(answer)
    claims = [c for c in claims if len(c.split()) >= 3]
    if not abst and claims:
        faith = sum(_support(c, ctx_text) for c in claims) / len(claims)
        gold_text = " ".join(page_text[u] for u in gold)
        gfaith = (sum(_support(c, gold_text) for c in claims) / len(claims)) if gold else 0.0
    else:
        faith = gfaith = None

    # ---------------- citations
    cited = r.get("citations", [])
    if not abst and cited:
        cite_acc = sum((c_doc_id(c, ctx), c["page"]) in gold for c in cited) / len(cited)
    else:
        cite_acc = None

    # ---------------- context precision (AP@K) and recall (key facts in context)
    if has_gold:
        hits, ap = 0, 0.0
        for i, f in enumerate(rel_flags, 1):
            if f:
                hits += 1
                ap += hits / i
        ctx_precision = ap / max(1, hits) if hits else 0.0
        ctx_recall = (sum(keyword_present(ctx_text, kw) for kw in kws) / len(kws)) if kws else None
        p_at_k = sum(rel_flags) / k
        r_at_k = len(gold & set(units)) / len(gold)
        rr = next((1 / i for i, f in enumerate(rel_flags, 1) if f), 0.0)
    else:
        ctx_precision = ctx_recall = p_at_k = r_at_k = rr = None

    return {
        "id": q["id"], "category": q["category"], "question": q["question"],
        "expected_behaviour": q["expected_behaviour"], "expected_status": q["expected_evidence_status"],
        "decision": r["decision"], "abstained": abst, "conflict_flagged": flagged,
        "answer": answer, "expected_answer": q["expected_answer"],
        "keywords_hit": sum(kw_hits), "keywords_total": len(kws),
        "correct": correct, "behaviour_ok": behaviour_ok,
        "unsupported": (not abst) and (exp_abst or (kws and not any(kw_hits))),
        "faithfulness": faith, "grounded_faithfulness": gfaith,
        "answer_relevance": (relevance_fn(q["question"], answer) if (relevance_fn and not abst) else None),
        "citation_support": cite_acc,
        "precision_at_k": p_at_k, "recall_at_k": r_at_k, "mrr": rr,
        "context_precision": ctx_precision, "context_recall": ctx_recall,
        "confidence": r.get("confidence"),
        "t_total": r["timings"]["total"], "t_retrieval": r["timings"]["retrieval"] + r["timings"].get("rerank", 0),
        "t_generation": r["timings"]["generation"], "t_verification": r["timings"].get("verification", 0.0),
        "explanation": r.get("explanation", ""),
        "retrieved": "; ".join(f"{d} p.{p}" for d, p in units),
    }


def c_doc_id(c, ctx):
    for p in ctx:
        if p["n"] == c["n"]:
            return p["doc_id"]
    return ""


def _mean(xs):
    xs = [x for x in xs if x is not None]
    return round(st.mean(xs), 4) if xs else None


def _prf(pred, gold):
    tp = sum(p and g for p, g in zip(pred, gold))
    fp = sum(p and not g for p, g in zip(pred, gold))
    fn = sum((not p) and g for p, g in zip(pred, gold))
    prec = tp / (tp + fp) if tp + fp else 0.0
    rec = tp / (tp + fn) if tp + fn else 0.0
    f1 = 2 * prec * rec / (prec + rec) if prec + rec else 0.0
    acc = sum(p == g for p, g in zip(pred, gold)) / max(1, len(gold))
    return round(prec, 4), round(rec, 4), round(f1, 4), round(acc, 4)


def aggregate(rows: list[dict]) -> dict:
    ap, ar, af, aa = _prf([r["abstained"] for r in rows], [r["expected_behaviour"] == "abstain" for r in rows])
    cp, cr, cf, ca = _prf([r["conflict_flagged"] for r in rows], [r["expected_status"] == "conflicting" for r in rows])
    out = {
        "n_questions": len(rows),
        # retrieval
        "precision_at_k": _mean(r["precision_at_k"] for r in rows),
        "recall_at_k": _mean(r["recall_at_k"] for r in rows),
        "mrr": _mean(r["mrr"] for r in rows),
        # answer quality
        "answer_correctness": _mean(float(r["correct"]) for r in rows),
        "faithfulness": _mean(r["faithfulness"] for r in rows),
        "grounded_faithfulness": _mean(r["grounded_faithfulness"] for r in rows),
        "answer_relevance": _mean(r["answer_relevance"] for r in rows),
        "context_precision": _mean(r["context_precision"] for r in rows),
        "context_recall": _mean(r["context_recall"] for r in rows),
        # reliability
        "unsupported_answer_rate": _mean(float(r["unsupported"]) for r in rows),
        "abstention_accuracy": aa, "abstention_precision": ap, "abstention_recall": ar, "abstention_f1": af,
        "abstention_rate": _mean(float(r["abstained"]) for r in rows),
        "contradiction_precision": cp, "contradiction_recall": cr, "contradiction_f1": cf,
        "contradiction_accuracy": ca,
        "citation_support_accuracy": _mean(r["citation_support"] for r in rows),
        "behaviour_accuracy": _mean(float(r["behaviour_ok"]) for r in rows),
        # efficiency
        "avg_response_time_s": _mean(r["t_total"] for r in rows),
        "avg_retrieval_time_s": _mean(r["t_retrieval"] for r in rows),
        "avg_generation_time_s": _mean(r["t_generation"] for r in rows),
        "avg_verification_time_s": _mean(r["t_verification"] for r in rows),
    }
    return out


def by_category(rows: list[dict]) -> dict:
    cats = sorted({r["category"] for r in rows})
    return {c: {"n": sum(r["category"] == c for r in rows),
                "answer_correctness": _mean(float(r["correct"]) for r in rows if r["category"] == c),
                "behaviour_accuracy": _mean(float(r["behaviour_ok"]) for r in rows if r["category"] == c),
                "unsupported_rate": _mean(float(r["unsupported"]) for r in rows if r["category"] == c),
                "abstention_rate": _mean(float(r["abstained"]) for r in rows if r["category"] == c)}
            for c in cats}


def classify_error(r: dict) -> str:
    """Coarse error taxonomy used in the error analysis."""
    if r["behaviour_ok"]:
        return "correct"
    eb = r["expected_behaviour"]
    if eb == "abstain":
        return "answered unanswerable question (hallucination risk)"
    if r["abstained"]:
        return "over-abstention (answer was available)"
    if eb == "flag_conflict" and not r["conflict_flagged"]:
        return "missed conflict"
    if r["recall_at_k"] is not None and r["recall_at_k"] == 0:
        return "retrieval failure (no gold page retrieved)"
    if r["keywords_hit"] == 0:
        return "wrong/irrelevant answer content"
    return "incomplete answer (some key facts missing)"