Download scripts/v3_validation/compare_layers.py from yahyoha/omnidiag: direct link, hf CLI and curl.
- Browser
- Download file 7.81 kB
-
https://huggingface.co/spaces/yahyoha/omnidiag/resolve/main/scripts/v3_validation/compare_layers.py
- Command line
-
hf download hf://spaces/yahyoha/omnidiag/scripts/v3_validation/compare_layers.py
-
curl -L -o compare_layers.py https://huggingface.co/spaces/yahyoha/omnidiag/resolve/main/scripts/v3_validation/compare_layers.py
7.81 kB
| #!/usr/bin/env python3 | |
| """ | |
| V3-S1 validation, part D (comparison half): do the API, the screen, the PDF and | |
| the report's deterministic evidence section say the same thing? | |
| For each module and demo patient A-D: | |
| api POST /api/v4/{disease}/evidence-actions on the running backend | |
| report backend.evidence.text.evidence_markdown(api) — the section the LLM | |
| report appends (deterministic; no LLM call needed for this part) | |
| pdf pdftotext of docs/v3/validation/<module>_<patient>_report.pdf (A-C) | |
| screen the card's innerText saved by ui_capture.py (A-C) | |
| Checked per item, on every surface: the section title for its status (and that | |
| the item sits under it), action, headline, matched_rule, the rule source | |
| citation, every effect's source citation; and that no intervention absent from | |
| the API appears. Comparison ignores whitespace and case (line wrapping, CSS | |
| upper-casing). A string that matches only once "≥"/"≤" are replaced by what the | |
| PDF printed is reported as a glyph loss, not a missing item. | |
| python scripts/v3_validation/compare_layers.py | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import re | |
| import subprocess | |
| import sys | |
| import urllib.request | |
| from pathlib import Path | |
| ROOT = Path(__file__).resolve().parents[2] | |
| sys.path.insert(0, str(ROOT)) | |
| from backend.evidence.registry import load_registry # noqa: E402 | |
| from backend.evidence.text import SECTION_TITLES, compact_source, evidence_markdown # noqa: E402 | |
| API = "http://127.0.0.1:8000" | |
| OUT = ROOT / "docs/v3/validation" | |
| DEMO = json.load(open(ROOT / "backend/demo_patients.json")) | |
| EXTRA_D = { | |
| "heart_disease": {"Age": 58, "Sex": "M", "ChestPainType": "ASY", "RestingBP": 140, | |
| "Cholesterol": 240, "FastingBS": 1, "RestingECG": "Normal", "ExerciseAngina": "N"}, | |
| "diabetes_nhanes": {"RIDAGEYR": 58, "BMXBMI": 33, "ADIPOSITY_BAND": "high", "LBDHDD": 38, | |
| "PAQ650": 0, "PAQ665": 0}, | |
| } | |
| ALL_ACTIONS = {iid: i["action"] for iid, i in load_registry()["interventions"].items()} | |
| def norm(text: str) -> str: | |
| return re.sub(r"\s+", "", text or "").lower() | |
| def api_response(disease: str, patient: dict) -> dict: | |
| req = urllib.request.Request( | |
| f"{API}/api/v4/{disease}/evidence-actions", data=json.dumps(patient).encode(), | |
| headers={"Content-Type": "application/json"}, method="POST", | |
| ) | |
| with urllib.request.urlopen(req) as r: | |
| return json.load(r) | |
| def pdf_section(path: Path) -> str: | |
| text = subprocess.run(["pdftotext", str(path), "-"], capture_output=True, text=True).stdout | |
| start = text.lower().find("evidence-backed actions") | |
| end = text.lower().find("effects are relative", start) | |
| return text[start:end + 200] if start >= 0 else "" | |
| def find(hay: str, needle: str): | |
| """'ok' | 'glyph:<what the PDF printed>' | 'missing'.""" | |
| h, n = norm(hay), norm(needle) | |
| if n in h: | |
| return "ok" | |
| for glyph in ("≥", "≤"): | |
| if glyph in needle: | |
| # What did the surface print in its place? Try any single char. | |
| pattern = re.escape(n).replace(re.escape(glyph), "(.)") | |
| m = re.search(pattern, h) | |
| if m: | |
| return f"glyph:{glyph}->{m.group(1)!r}" | |
| return "missing" | |
| def checks_for(response: dict) -> list[tuple[str, str, str]]: | |
| """(item, what, expected text).""" | |
| out = [] | |
| for item in response["items"]: | |
| iid = item["intervention_id"] | |
| out.append((iid, "action", item["action"])) | |
| out.append((iid, "headline", item["headline"])) | |
| if item.get("matched_rule"): | |
| out.append((iid, "matched_rule", item["matched_rule"])) | |
| if item.get("rule_source"): | |
| # One-line sections print the compact form (short name + DOI/PMID). | |
| compact = item["status"] in ("at_target", "not_evaluable") | |
| out.append((iid, "rule_source", | |
| compact_source(item["rule_source"]) if compact else item["rule_source"]["citation"])) | |
| for reason in item.get("reasons") or []: | |
| out.append((iid, "reason", reason["text"])) | |
| for effect in item.get("effects") or []: | |
| out.append((iid, "effect_source", effect["source"]["citation"])) | |
| return out | |
| def section_order_ok(hay: str, response: dict, title_of) -> list[str]: | |
| """Each item's action lies after its own section title and before the next one.""" | |
| h = norm(hay) | |
| present = [s for s in SECTION_TITLES if any(i["group"] == s for i in response["items"])] | |
| positions = {} | |
| cursor = 0 | |
| for status in present: | |
| pos = h.find(norm(title_of(status)), cursor) | |
| positions[status] = pos | |
| if pos >= 0: | |
| cursor = pos + 1 | |
| problems = [] | |
| for status in present: | |
| if positions[status] < 0: | |
| problems.append(f"section title for {status} not found") | |
| bounds = [positions[s] for s in present] + [len(h)] | |
| for k, status in enumerate(present): | |
| lo, hi = bounds[k], bounds[k + 1] | |
| for item in response["items"]: | |
| if item["group"] != status: | |
| continue | |
| pos = h.find(norm(item["action"]), lo if lo >= 0 else 0) | |
| if not (lo >= 0 and lo <= pos < hi): | |
| problems.append(f"{item['intervention_id']} not under '{title_of(status)}'") | |
| return problems | |
| def main() -> int: | |
| results, mismatches = {}, [] | |
| for disease in ("heart_disease", "diabetes_nhanes"): | |
| patients = [p["data"] for p in DEMO[disease][:3]] + [EXTRA_D[disease]] | |
| for label, patient in zip("ABCD", patients): | |
| stem = f"{disease}_{label}" | |
| api = api_response(disease, patient) | |
| surfaces = {"report": evidence_markdown(api)} | |
| pdf = OUT / f"{stem}_report.pdf" | |
| if pdf.exists(): | |
| surfaces["pdf"] = pdf_section(pdf) | |
| screen = OUT / f"{stem}_evidence_screen.txt" | |
| if screen.exists(): | |
| surfaces["screen"] = screen.read_text(encoding="utf-8") | |
| row = {"statuses": {i["intervention_id"]: i["status"] for i in api["items"]}, | |
| "groups": {i["intervention_id"]: i["group"] for i in api["items"]}, | |
| "matched_rules": {i["intervention_id"]: i.get("matched_rule") for i in api["items"]}, | |
| "surfaces": sorted(surfaces), "problems": {}} | |
| for name, hay in surfaces.items(): | |
| problems = [] | |
| for iid, what, expected in checks_for(api): | |
| found = find(hay, expected) | |
| if found != "ok": | |
| problems.append(f"{iid}.{what}: {found} — {expected!r}") | |
| titles = {s["group"]: s["title"] for s in api["copy"]["sections"]} | |
| problems += section_order_ok(hay, api, lambda s: titles[s]) | |
| absent = set(ALL_ACTIONS) - {i["intervention_id"] for i in api["items"]} | |
| absent -= {n["intervention_id"] for n in api.get("not_in_model") or []} | |
| for iid in absent: | |
| if norm(ALL_ACTIONS[iid]) in norm(hay): | |
| problems.append(f"{iid}: shown on {name} but absent from the API") | |
| row["problems"][name] = problems | |
| for p in problems: | |
| mismatches.append(f"{stem} [{name}] {p}") | |
| results[stem] = row | |
| (OUT / "layer_comparison.json").write_text( | |
| json.dumps({"results": results, "mismatches": mismatches}, indent=2, ensure_ascii=False) + "\n", | |
| encoding="utf-8", | |
| ) | |
| for stem, row in results.items(): | |
| print(stem, row["statuses"], {k: len(v) for k, v in row["problems"].items()}) | |
| print(f"\n{len(mismatches)} mismatches") | |
| for m in mismatches: | |
| print(" -", m) | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |