omnidiag / scripts /v3_validation /ui_capture.py
yahyoha's picture
Space snapshot of af9d80f (binaries stripped)
ef838e0
Raw History Blame Contribute Delete
4.84 kB
#!/usr/bin/env python3
"""
V3-S1 validation, part D (browser half): Clinical EMR mode, headless Chromium.
For each module and each demo patient the EMR patient picker offers (A-C:
P-001..P-003, N-001..N-003), screenshot the Evidence-backed actions card and
the Estimate drivers card, save the card's screen text, and export the PDF
through the real "Export PDF" button.
Needs the backend on :8000 and `vite preview` on :4173 (built with
VITE_API_BASE=http://127.0.0.1:8000). One browser instance, headless.
Run with a Python that has Playwright, e.g. ~/venv/bin/python.
python scripts/v3_validation/ui_capture.py --out docs/v3/validation
"""
from __future__ import annotations
import argparse
import json
import sys
import urllib.request
from pathlib import Path
from playwright.sync_api import sync_playwright
UI = "http://127.0.0.1:4173/"
API = "http://127.0.0.1:8000"
CHROMIUM = Path.home() / ".cache/ms-playwright/chromium_headless_shell-1243/chrome-headless-shell-linux64/chrome-headless-shell"
PATIENTS = {
"heart_disease": [("A", "P-001"), ("B", "P-002"), ("C", "P-003")],
"diabetes_nhanes": [("A", "N-001"), ("B", "N-002"), ("C", "N-003")],
}
def display_names() -> dict:
with urllib.request.urlopen(f"{API}/api/v4/diseases") as r:
data = json.load(r)
return {d["name"]: d["info"]["display_name"] for d in data["diseases"]}
def wait_for_cards(page) -> None:
card = page.locator('[data-testid="evidence-actions-card"]')
card.wait_for(state="visible", timeout=120_000)
# Loaded when the spinner text is gone and a section, or the error line, is shown.
page.wait_for_function(
"""() => {
const c = document.querySelector('[data-testid="evidence-actions-card"]');
return c && !c.innerText.includes('Loading evidence') &&
(c.querySelector('[data-section]') || c.innerText.includes('could not be loaded'));
}""",
timeout=120_000,
)
page.locator('[data-testid="estimate-drivers"]').wait_for(state="visible", timeout=120_000)
page.wait_for_timeout(800) # chart animation
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--out", default="docs/v3/validation")
args = ap.parse_args()
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
names = display_names()
captured = {}
with sync_playwright() as pw:
browser = pw.chromium.launch(headless=True, executable_path=str(CHROMIUM))
context = browser.new_context(viewport={"width": 1400, "height": 1000}, accept_downloads=True)
page = context.new_page()
console_errors = []
page.on("console", lambda m: console_errors.append(m.text) if m.type == "error" else None)
page.goto(UI, wait_until="networkidle")
page.get_by_role("button", name="Clinical EMR Mode").first.click()
for disease, patients in PATIENTS.items():
# Switch module through the disease selector.
page.get_by_role("button", name=names["heart_disease"]).or_(
page.get_by_role("button", name=names["diabetes_nhanes"])
).first.click()
page.get_by_role("option", name=names[disease]).first.click()
for label, pid in patients:
if label != "A":
page.locator("button[data-print-keep]").first.click()
page.locator("button", has_text=pid).last.click()
page.locator("p", has_text=pid).first.wait_for(timeout=60_000)
wait_for_cards(page)
stem = f"{disease}_{label}"
card = page.locator('[data-testid="evidence-actions-card"]')
# Open the collapsed sections so the screenshot and text show everything.
for d in card.locator("details").all():
d.evaluate("el => el.open = true")
page.wait_for_timeout(300)
card.screenshot(path=str(out / f"{stem}_evidence.png"))
page.locator('[data-testid="estimate-drivers"]').screenshot(path=str(out / f"{stem}_drivers.png"))
text = card.inner_text()
(out / f"{stem}_evidence_screen.txt").write_text(text, encoding="utf-8")
with page.expect_download(timeout=120_000) as dl:
page.get_by_role("button", name="Export PDF").click()
dl.value.save_as(str(out / f"{stem}_report.pdf"))
captured[stem] = {"patient": pid, "screen_chars": len(text)}
print(f"captured {stem} ({pid})", flush=True)
(out / "ui_console_errors.json").write_text(json.dumps(console_errors, indent=2))
browser.close()
(out / "ui_capture.json").write_text(json.dumps(captured, indent=2))
return 0
if __name__ == "__main__":
sys.exit(main())