medgemma-source-verification / source_verification.py
synsetai's picture
Publish executable Study E source verification and synthetic example
53c72a7 verified
Raw History Blame Contribute Delete
2.64 kB
"""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()