File size: 2,640 Bytes
53c72a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""The original evaluated Study E verifier and gene reader, with standalone entry points."""
import argparse
import hashlib
import json
from pathlib import Path
import re

def verified_source_passage(expected, retrieved):
    """Return text only for the exact passage admitted by the caller.

    The caller owns the source, edition, subject and answer-bearing passage
    admission. The search score does not supply any of those authorities.
    """
    if retrieved is None:
        return None
    for key in ("family", "source_record_id", "edition", "passage_id"):
        if not isinstance(expected[key], str) or not expected[key] or retrieved.get(key) != expected[key]:
            return None
    text = retrieved.get("text")
    if not isinstance(text, str) or not text.strip():
        return None
    return text if hashlib.sha256(text.encode("utf-8")).hexdigest() == expected["sha256"] else None

def source_gene_readback(answer):
    """Read one explicit gene proposal or evidence-unknown decision."""
    if not isinstance(answer, str):
        return None
    answer = answer.strip().removesuffix('.')
    if answer == 'UNKNOWN':
        return ('unknown', None)
    match = re.fullmatch(r'GENE:[ \t]*([A-Z][A-Z0-9]*(?:-[A-Z0-9]+)*)', answer)
    return ('gene', match[1]) if match and match[1] != 'UNKNOWN' else None

def lookup(verified_text, read_gene):
    if verified_text is None:
        return ("unknown", None)
    symbols = re.findall(r"^Symbol: ([A-Z][A-Z0-9]*(?:-[A-Z0-9]+)*)$", verified_text, re.M)
    return read_gene("GENE: "+symbols[0]) if len(symbols) == 1 else None


def deliver(expected, retrieved, pipeline_answer):
    """Apply the source gate to the final answer extracted from model output."""
    text = verified_source_passage(expected, retrieved)
    return ("unknown", None) if text is None else source_gene_readback(pipeline_answer)


def deterministic_delivery(expected, retrieved):
    """Return the symbol from the verified source or an unknown decision."""
    return lookup(verified_source_passage(expected, retrieved), source_gene_readback)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("input", type=Path, help="Local JSON with expected, retrieved and pipeline_answer fields")
    args = parser.parse_args()
    sample = json.loads(args.input.read_text(encoding="utf-8"))
    print(json.dumps({
        "guarded": deliver(sample["expected"], sample["retrieved"], sample["pipeline_answer"]),
        "deterministic": deterministic_delivery(sample["expected"], sample["retrieved"]),
    }, indent=2))


if __name__ == "__main__":
    main()