# PathQA — an AI second-reader QA safety-net for pathology labs **Positioning:** quality assurance / workflow, **not** diagnosis. PathQA never issues a diagnosis and never changes a pathologist's sign-out. It runs quietly behind the sign-out and does exactly one thing: when it *confidently disagrees* with the pathologist, it raises a hand — "case N, worth a second look, here's why." A human decides. The pathologist stays in control. This repo is the **v1 build**, in two stages exactly as scoped: 1. **Patch-classifier demo** on public data (PatchCamelyon) — proves the model + the QA logic end-to-end. 2. **Train-on-your-data** version — the model comes to the lab's own labeled slides, which is what fixes domain shift, and nothing leaves the machine. --- ## Why this design (the three product requirements) **1. Trains on the lab's own labeled slides → solves domain shift + keeps data private.** Off-the-shelf histopathology models degrade badly across stains, scanners and tissue mixes. `train_on_your_data.py` fine-tunes on a folder of the lab's own patches, so the model learns *that* lab's distribution. All I/O is local — the model comes to the data. **2. Flags only disagreements → a human re-checks.** The QA engine (`pathqa/qa.py`) compares the model's read to the pathologist's label and flags a case only when the model **disagrees** *and* is **confident** (`confidence ≥ tau`). Everything else passes untouched. Output is a prioritized re-check worklist, sorted by confidence — the queue a pathologist actually opens. **3. Assist, not replace.** No case is ever auto-relabeled. The only output is a "recommend re-review" flag with a plain-language reason. Every artifact carries that reminder. Two extra design choices that matter for a *QA* tool specifically: - **Calibration.** A QA threshold is only meaningful if "0.9 confidence" behaves like 0.9. Raw softmax is over-confident, so I apply **temperature scaling** (Guo et al., 2017) on the validation split. In the smoke test this dropped validation loss from 0.265 → 0.231. - **Workload budget.** Instead of a fixed `tau`, a lab can say "flag the top 5% most-confident disagreements" (`--budget 0.05`) so the QA queue fits the time the lab actually has. The engine backs out the effective `tau` for you. --- ## Layout ``` pathqa/ pathqa-app / .bat # ONE-COMMAND LAUNCHER (venv + deps + open browser) pathqa/ model.py # ResNet18/34 binary tumor/normal head + TemperatureScaler data.py # 3 sources: PatchCamelyon | your ImageFolder | synthetic (tests) engine.py # train / evaluate (AUROC, ECE) / temperature fitting qa.py # SecondReader — patch-level disagreement + flagging engine wsi.py # whole-slide tiling + tissue detection slide.py # slide aggregation (top-K), slide-level QA, heatmap gradcam.py # Grad-CAM explainer (why the model flagged it) cli.py # `pathqa serve|demo|slide-demo|train` dispatcher backend/ # stdlib HTTP server + stateful QA session frontend/ # single-file React UI (Patch QA + Whole-slide QA tabs) demo.py # patch QA demo (stage 1) slide_demo.py # whole-slide QA demo train_on_your_data.py # fine-tune on the lab's own labeled patches (stage 2) train_pcam.py # real PatchCamelyon training + AUROC/ECE requirements.txt ``` ## Install ```bash pip install -r requirements.txt # torch, torchvision, h5py ``` ## Run — Stage 1: patch-classifier demo No download, verifies the whole pipeline in ~1 minute on CPU: ```bash python demo.py --synthetic --epochs 1 --no-pretrained ``` Real public data (downloads PatchCamelyon on first run; use a GPU or Colab): ```bash python demo.py --pcam --subset 20000 --epochs 3 --budget 0.05 ``` What it does: loads patches → fine-tunes ResNet18 → temperature-calibrates → simulates a sign-out queue with a small injected human-error rate → runs the QA second reader → prints a report and writes `qa_out/worklist.csv` + `qa_out/qa_report.json`. Sample output: ``` PathQA second-reader report cases reviewed : 128 model/pathologist disagreements: 17 (13.3%) flagged for re-check : 6 (4.7%) at confidence >= 0.85 -> 122 cases pass QA untouched; pathologist reviews only the 6 flagged. [QA effectiveness] of 17 simulated sign-out errors, the second reader flagged 6 for re-check. ``` ## Run — Stage 2: train on your data Lay your labeled patches out as: ``` my_lab_data/ train/normal/*.png train/tumor/*.png val/normal/*.png val/tumor/*.png ``` ```bash python train_on_your_data.py --data my_lab_data --epochs 5 --out model.pt ``` Saves the fine-tuned weights **and** the fitted temperature, so the QA engine gets calibrated confidences out of the box. Everything stays on the machine. --- ## Run — the local app (one command) A local, on-prem app so a pathologist (non-coder) can use it. The backend is **Python stdlib only** (no framework to install, nothing phones home — chosen for an air-gapped lab), and the frontend is a single-file React UI it serves. ```bash ./pathqa-app # macOS/Linux — makes a venv, installs deps, opens the browser pathqa-app.bat # Windows ./pathqa-app demo # patch QA demo (headless) ./pathqa-app slide-demo # whole-slide QA demo (headless) ./pathqa-app train --help ``` The launcher creates a `.venv`, installs `requirements.txt`, then starts the server and opens `http://127.0.0.1:8000` (localhost only). Under the hood it calls `pathqa/cli.py`; you can also run the pieces directly: ```bash PYTHONPATH=. python backend/server.py --open ``` Out of the box it fine-tunes a small demo model on synthetic patches so there's a working worklist immediately. To serve a model you trained on your own data: ```bash PATHQA_MODEL=model.pt PYTHONPATH=. python backend/server.py ``` What the UI does: shows the flagged re-check queue (patch thumbnail, sign-out vs model read, confidence), a live τ slider to tune the queue length, and two actions per case — **Confirm sign-out** or **Amend (model was right)**. Every decision is appended to `audit_log.jsonl` with model read, confidence and a note — the governance trail. No sign-out is ever changed automatically. API (stable; maps 1:1 onto FastAPI path operations if you later swap frameworks): `GET /api/summary`, `GET /api/worklist`, `GET /api/patch/{id}.png`, `POST /api/decision`, `POST /api/settings`. Air-gapped frontend: run `frontend/vendor_offline.sh` once to pull React+Babel locally, then point the three `