Download code/scorer.py from Vijayarv07/grounding-checker: direct link, hf CLI and curl.
- Browser
- Download file 5.08 kB
-
https://huggingface.co/datasets/Vijayarv07/grounding-checker/resolve/main/code/scorer.py
- Command line
-
hf download hf://datasets/Vijayarv07/grounding-checker/code/scorer.py
-
curl -L -o scorer.py https://huggingface.co/datasets/Vijayarv07/grounding-checker/resolve/main/code/scorer.py
5.08 kB
| """Transparent, rule-based grounding scorer. No trained model — every decision is explainable. | |
| Per claim vs source: | |
| RED (not grounded): a hard violation — contradiction, a number not in the source, | |
| or a proper noun (multi-word or mid-sentence) not in the source. | |
| YELLOW (weak) : no hard violation, but little lexical support — review it | |
| (this is where valid-but-inferential claims land; lexical methods can't verify them). | |
| GREEN (grounded) : supported by the source. | |
| """ | |
| from __future__ import annotations | |
| import re | |
| from features import STOP, NEG, sentences, content_tokens, numbers_norm | |
| LOW_SUPPORT = 0.33 | |
| def _bigrams(s): | |
| s = s.lower() | |
| return [s[i:i+2] for i in range(len(s)-1)] | |
| def _dice(a, b): | |
| A, B = _bigrams(a), _bigrams(b) | |
| if not A or not B: | |
| return 0.0 | |
| from collections import Counter | |
| ca, cb = Counter(A), Counter(B) | |
| return 2 * sum((ca & cb).values()) / (len(A) + len(B)) | |
| def proper_nouns(text: str): | |
| """Capitalized words, excluding each sentence's first word (avoids sentence-initial false positives). | |
| Hyphenated words are split, so 'Austin-based' contributes 'austin', not 'austinbased'.""" | |
| out = set() | |
| for sent in sentences(text): | |
| words = sent.split() | |
| for i, w in enumerate(words): | |
| if i == 0: | |
| continue | |
| for part in re.split(r"[-/]", w): | |
| core = re.sub(r"[^A-Za-z]", "", part) | |
| if core and core[0].isupper() and core.lower() not in STOP: | |
| out.add(core.lower()) | |
| # also keep multi-word capitalized spans even if at sentence start | |
| for span in re.findall(r"\b[A-Z][a-zA-Z]+(?:\s+[A-Z][a-zA-Z]+)+\b", text): | |
| for w in span.split(): | |
| if w.lower() not in STOP: | |
| out.add(w.lower()) | |
| return out | |
| def _recall(a: set, b: set): | |
| return len(a & b) / len(a) if a else 0.0 | |
| def score_claim(claim: str, source: str) -> dict: | |
| src_sents = sentences(source) | |
| ct = set(content_tokens(claim)) | |
| best_r = 0.0 | |
| best_sent = "" | |
| for s in src_sents: | |
| r = _recall(ct, set(content_tokens(s))) | |
| if r > best_r: | |
| best_r, best_sent = r, s | |
| # support is content-word recall against the best-matching source sentence, | |
| # nudged up slightly if the claim also overlaps the document as a whole. | |
| doc_recall = _recall(ct, set(content_tokens(source))) | |
| support = max(best_r, 0.6 * doc_recall) | |
| cn, dn = numbers_norm(claim), numbers_norm(source) | |
| bad_nums = sorted(cn - dn) | |
| cpn, dpn = proper_nouns(claim), proper_nouns(source) | |
| bad_ents = sorted(cpn - dpn) | |
| claim_neg = bool(set(re.findall(r"[a-z']+", claim.lower())) & NEG) | |
| best_neg = bool(set(re.findall(r"[a-z']+", best_sent.lower())) & NEG) | |
| contradiction = claim_neg != best_neg and best_r >= 0.2 # only when it clearly refers to a source sentence | |
| reasons = [] | |
| if contradiction: | |
| reasons.append("contradicts the source") | |
| if bad_nums: | |
| reasons.append("number(s) not in source: " + ", ".join(bad_nums)) | |
| if bad_ents: | |
| reasons.append("name(s)/term(s) not in source: " + ", ".join(bad_ents[:5])) | |
| if reasons: | |
| verdict = "not_grounded" | |
| elif support < LOW_SUPPORT: | |
| verdict = "weak" | |
| reasons.append("little lexical support — may be a valid inference the checker can't verify") | |
| else: | |
| verdict = "grounded" | |
| return {"verdict": verdict, "support": round(support, 3), "reasons": reasons, | |
| "bad_nums": bad_nums, "bad_ents": bad_ents, "contradiction": contradiction} | |
| if __name__ == "__main__": | |
| import json, pandas as pd, collections | |
| # Honest evaluation on the held-out test split: does RED correctly catch label==1? | |
| te = pd.read_parquet("data/test.parquet") | |
| tp = fp = fn = tn = 0 | |
| sub = collections.defaultdict(lambda: [0, 0]) | |
| for _, r in te.iterrows(): | |
| v = score_claim(r["claim"], r["source"])["verdict"] | |
| pred_bad = v == "not_grounded" # treat weak/yellow as "not flagged red" | |
| if r["label"] == 1: | |
| sub[r["subtype"]][1] += 1 | |
| sub[r["subtype"]][0] += int(pred_bad) | |
| if pred_bad: tp += 1 | |
| else: fn += 1 | |
| else: | |
| if pred_bad: fp += 1 | |
| else: tn += 1 | |
| prec = tp/(tp+fp) if tp+fp else 0 | |
| rec = tp/(tp+fn) if tp+fn else 0 | |
| f1 = 2*prec*rec/(prec+rec) if prec+rec else 0 | |
| # how many grounded got yellow-flagged (support cost) | |
| yellow_on_grounded = sum(1 for _, r in te.iterrows() | |
| if r["label"] == 0 and score_claim(r["claim"], r["source"])["verdict"] == "weak") | |
| print(json.dumps({ | |
| "red_flag_precision": round(prec, 3), "red_flag_recall": round(rec, 3), "red_flag_f1": round(f1, 3), | |
| "accuracy_red_vs_rest": round((tp+tn)/len(te), 3), | |
| "subtype_red_recall": {k: round(v[0]/v[1], 3) for k, v in sorted(sub.items())}, | |
| "grounded_sent_sent_to_yellow": yellow_on_grounded, | |
| "n_test": len(te), | |
| }, indent=2)) | |