Shubhambhandari commited on
Commit
f93c1b8
·
verified ·
1 Parent(s): 13f90f2

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ samples/HE_benign_low.png filter=lfs diff=lfs merge=lfs -text
37
+ samples/HE_borderline_mid.png filter=lfs diff=lfs merge=lfs -text
38
+ samples/HE_tumor_high.png filter=lfs diff=lfs merge=lfs -text
39
+ zigWmHRR filter=lfs diff=lfs merge=lfs -text
DOCS.md ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PathQA — an AI second-reader QA safety-net for pathology labs
2
+
3
+ **Positioning:** quality assurance / workflow, **not** diagnosis. PathQA never
4
+ issues a diagnosis and never changes a pathologist's sign-out. It runs quietly
5
+ behind the sign-out and does exactly one thing: when it *confidently disagrees*
6
+ with the pathologist, it raises a hand — "case N, worth a second look, here's
7
+ why." A human decides. The pathologist stays in control.
8
+
9
+ This repo is the **v1 build**, in two stages exactly as scoped:
10
+
11
+ 1. **Patch-classifier demo** on public data (PatchCamelyon) — proves the model +
12
+ the QA logic end-to-end.
13
+ 2. **Train-on-your-data** version — the model comes to the lab's own labeled
14
+ slides, which is what fixes domain shift, and nothing leaves the machine.
15
+
16
+ ---
17
+
18
+ ## Why this design (the three product requirements)
19
+
20
+ **1. Trains on the lab's own labeled slides → solves domain shift + keeps data private.**
21
+ Off-the-shelf histopathology models degrade badly across stains, scanners and
22
+ tissue mixes. `train_on_your_data.py` fine-tunes on a folder of the lab's own
23
+ patches, so the model learns *that* lab's distribution. All I/O is local — the
24
+ model comes to the data.
25
+
26
+ **2. Flags only disagreements → a human re-checks.**
27
+ The QA engine (`pathqa/qa.py`) compares the model's read to the pathologist's
28
+ label and flags a case only when the model **disagrees** *and* is **confident**
29
+ (`confidence ≥ tau`). Everything else passes untouched. Output is a prioritized
30
+ re-check worklist, sorted by confidence — the queue a pathologist actually opens.
31
+
32
+ **3. Assist, not replace.**
33
+ No case is ever auto-relabeled. The only output is a "recommend re-review" flag
34
+ with a plain-language reason. Every artifact carries that reminder.
35
+
36
+ Two extra design choices that matter for a *QA* tool specifically:
37
+
38
+ - **Calibration.** A QA threshold is only meaningful if "0.9 confidence" behaves
39
+ like 0.9. Raw softmax is over-confident, so I apply **temperature scaling**
40
+ (Guo et al., 2017) on the validation split. In the smoke test this dropped
41
+ validation loss from 0.265 → 0.231.
42
+ - **Workload budget.** Instead of a fixed `tau`, a lab can say "flag the top 5%
43
+ most-confident disagreements" (`--budget 0.05`) so the QA queue fits the time
44
+ the lab actually has. The engine backs out the effective `tau` for you.
45
+
46
+ ---
47
+
48
+ ## Layout
49
+
50
+ ```
51
+ pathqa/
52
+ pathqa-app / .bat # ONE-COMMAND LAUNCHER (venv + deps + open browser)
53
+ pathqa/
54
+ model.py # ResNet18/34 binary tumor/normal head + TemperatureScaler
55
+ data.py # 3 sources: PatchCamelyon | your ImageFolder | synthetic (tests)
56
+ engine.py # train / evaluate (AUROC, ECE) / temperature fitting
57
+ qa.py # SecondReader — patch-level disagreement + flagging engine
58
+ wsi.py # whole-slide tiling + tissue detection
59
+ slide.py # slide aggregation (top-K), slide-level QA, heatmap
60
+ gradcam.py # Grad-CAM explainer (why the model flagged it)
61
+ cli.py # `pathqa serve|demo|slide-demo|train` dispatcher
62
+ backend/ # stdlib HTTP server + stateful QA session
63
+ frontend/ # single-file React UI (Patch QA + Whole-slide QA tabs)
64
+ demo.py # patch QA demo (stage 1)
65
+ slide_demo.py # whole-slide QA demo
66
+ train_on_your_data.py # fine-tune on the lab's own labeled patches (stage 2)
67
+ train_pcam.py # real PatchCamelyon training + AUROC/ECE
68
+ requirements.txt
69
+ ```
70
+
71
+ ## Install
72
+
73
+ ```bash
74
+ pip install -r requirements.txt # torch, torchvision, h5py
75
+ ```
76
+
77
+ ## Run — Stage 1: patch-classifier demo
78
+
79
+ No download, verifies the whole pipeline in ~1 minute on CPU:
80
+
81
+ ```bash
82
+ python demo.py --synthetic --epochs 1 --no-pretrained
83
+ ```
84
+
85
+ Real public data (downloads PatchCamelyon on first run; use a GPU or Colab):
86
+
87
+ ```bash
88
+ python demo.py --pcam --subset 20000 --epochs 3 --budget 0.05
89
+ ```
90
+
91
+ What it does: loads patches → fine-tunes ResNet18 → temperature-calibrates →
92
+ simulates a sign-out queue with a small injected human-error rate → runs the QA
93
+ second reader → prints a report and writes `qa_out/worklist.csv` +
94
+ `qa_out/qa_report.json`.
95
+
96
+ Sample output:
97
+
98
+ ```
99
+ PathQA second-reader report
100
+ cases reviewed : 128
101
+ model/pathologist disagreements: 17 (13.3%)
102
+ flagged for re-check : 6 (4.7%) at confidence >= 0.85
103
+ -> 122 cases pass QA untouched; pathologist reviews only the 6 flagged.
104
+ [QA effectiveness] of 17 simulated sign-out errors, the second reader flagged 6 for re-check.
105
+ ```
106
+
107
+ ## Run — Stage 2: train on your data
108
+
109
+ Lay your labeled patches out as:
110
+
111
+ ```
112
+ my_lab_data/
113
+ train/normal/*.png train/tumor/*.png
114
+ val/normal/*.png val/tumor/*.png
115
+ ```
116
+
117
+ ```bash
118
+ python train_on_your_data.py --data my_lab_data --epochs 5 --out model.pt
119
+ ```
120
+
121
+ Saves the fine-tuned weights **and** the fitted temperature, so the QA engine
122
+ gets calibrated confidences out of the box. Everything stays on the machine.
123
+
124
+ ---
125
+
126
+ ## Run — the local app (one command)
127
+
128
+ A local, on-prem app so a pathologist (non-coder) can use it. The backend is
129
+ **Python stdlib only** (no framework to install, nothing phones home — chosen
130
+ for an air-gapped lab), and the frontend is a single-file React UI it serves.
131
+
132
+ ```bash
133
+ ./pathqa-app # macOS/Linux — makes a venv, installs deps, opens the browser
134
+ pathqa-app.bat # Windows
135
+
136
+ ./pathqa-app demo # patch QA demo (headless)
137
+ ./pathqa-app slide-demo # whole-slide QA demo (headless)
138
+ ./pathqa-app train --help
139
+ ```
140
+
141
+ The launcher creates a `.venv`, installs `requirements.txt`, then starts the
142
+ server and opens `http://127.0.0.1:8000` (localhost only). Under the hood it
143
+ calls `pathqa/cli.py`; you can also run the pieces directly:
144
+
145
+ ```bash
146
+ PYTHONPATH=. python backend/server.py --open
147
+ ```
148
+
149
+ Out of the box it fine-tunes a small demo model on synthetic patches so there's
150
+ a working worklist immediately. To serve a model you trained on your own data:
151
+
152
+ ```bash
153
+ PATHQA_MODEL=model.pt PYTHONPATH=. python backend/server.py
154
+ ```
155
+
156
+ What the UI does: shows the flagged re-check queue (patch thumbnail, sign-out vs
157
+ model read, confidence), a live τ slider to tune the queue length, and two
158
+ actions per case — **Confirm sign-out** or **Amend (model was right)**. Every
159
+ decision is appended to `audit_log.jsonl` with model read, confidence and a note
160
+ — the governance trail. No sign-out is ever changed automatically.
161
+
162
+ API (stable; maps 1:1 onto FastAPI path operations if you later swap frameworks):
163
+ `GET /api/summary`, `GET /api/worklist`, `GET /api/patch/{id}.png`,
164
+ `POST /api/decision`, `POST /api/settings`.
165
+
166
+ Air-gapped frontend: run `frontend/vendor_offline.sh` once to pull React+Babel
167
+ locally, then point the three `<script>` tags in `index.html` at `./vendor/...`.
168
+
169
+ ## Whole-slide QA (patch → slide)
170
+
171
+ A real sign-out is per-slide, not per-patch. The whole-slide layer tiles a slide,
172
+ scores every tissue tile, and aggregates into one slide-level decision:
173
+
174
+ - `pathqa/wsi.py` — tiling + tissue/background detection (keeps stained tissue,
175
+ drops glass). Opens large PIL images, true WSI via OpenSlide (`.svs/.ndpi`,
176
+ optional lazy import), or a synthetic slide for the demo.
177
+ - `pathqa/slide.py` — **top-K mean pooling**: a slide is called tumor if its most
178
+ suspicious regions are tumor (matches metastasis detection — one focus is
179
+ enough — far better than averaging tumor away across a big slide). Also emits a
180
+ tumor-probability **heatmap** and the slide-level QA flags.
181
+
182
+ Run the slide demo (synthetic cohort, writes a heatmap per slide + a worklist):
183
+
184
+ ```bash
185
+ python slide_demo.py --n-slides 8 --tau 0.7 --outdir slide_out
186
+ ```
187
+
188
+ For a real slide, swap `SyntheticSlide` for `open_slide_image("case.svs")` — the
189
+ rest is unchanged. OpenSlide is only needed for native WSI formats:
190
+ `pip install openslide-python` (plus the system OpenSlide library).
191
+
192
+ In the app, the **Whole-slide QA** tab shows each flagged slide as a heatmap card
193
+ (sign-out vs model, slide score, suspicious-tile count) with Confirm / Amend, and
194
+ its own τ slider. Slide decisions log to the same `audit_log.jsonl` with
195
+ `"level":"slide"`.
196
+
197
+ ## Analyze an image (real model + stain), and the train-better loop
198
+
199
+ The app's "Analyze image" tab runs an uploaded H&E image through BOTH methods
200
+ and combines them:
201
+
202
+ - the trained CNN (`pathqa/infer.py`) with test-time augmentation, giving a
203
+ calibrated tumour probability plus an uncertainty estimate (so it can say
204
+ "not sure" instead of guessing), and a Grad-CAM overlay (patch) or a tiled
205
+ tumour heatmap with the top suspicious tiles (slide);
206
+ - the stain/colour method (dense-nuclei density) as an independent check.
207
+
208
+ The two are merged into one verdict: if they agree, confidence goes up; if they
209
+ disagree, it returns "needs review" rather than a false certainty.
210
+
211
+ Endpoints: `POST /api/analyze-image` (base64 image in, verdict plus two overlay
212
+ images out), `POST /api/feedback` (save a labelled image as training data),
213
+ `GET /api/feedback/stats`.
214
+
215
+ Train-better loop: every image you label in the app is saved under
216
+ `data/feedback/{normal,tumor}/`. When you have enough, fine-tune on exactly the
217
+ cases your lab sees:
218
+
219
+ ```bash
220
+ python finetune_from_feedback.py --base pcam_model.pt --out pcam_model.pt
221
+ # prints held-out AUROC + ECE, saves a calibrated checkpoint the app loads
222
+ PATHQA_MODEL=pcam_model.pt ./pathqa-app
223
+ ```
224
+
225
+ So it gets better the more it is used, and always reports honest metrics before
226
+ you adopt a new checkpoint.
227
+
228
+ ## Explainability — Grad-CAM
229
+
230
+ A flag is only actionable if the pathologist can see *why* the model disagreed.
231
+ `pathqa/gradcam.py` runs Grad-CAM on the classifier's last conv block and
232
+ overlays a heat map on the patch showing which pixels drove the call. In the
233
+ app, clicking a flagged patch opens the patch next to its "model attention"
234
+ overlay. This is explanation, not diagnosis — it never changes a call.
235
+
236
+ ## Real training on PatchCamelyon
237
+
238
+ `train_pcam.py` trains on real PCam and reports honest held-out metrics — AUROC
239
+ and Expected Calibration Error (ECE) before/after temperature scaling — then
240
+ saves an app-ready checkpoint.
241
+
242
+ ```bash
243
+ # GPU (full run)
244
+ python train_pcam.py --epochs 5 --batch-size 256 --out pcam_model.pt
245
+
246
+ # quick CPU subset
247
+ python train_pcam.py --subset 8000 --epochs 1 --batch-size 64 --out pcam_model.pt
248
+
249
+ # pipeline check, no download
250
+ python train_pcam.py --synthetic --no-pretrained --epochs 1 --out demo_model.pt
251
+ ```
252
+
253
+ Colab (free GPU) — PCam is ~7 GB so run it there or on a lab GPU box:
254
+
255
+ ```python
256
+ !pip -q install torch torchvision h5py
257
+ !python train_pcam.py --epochs 5 --batch-size 256 --out pcam_model.pt
258
+ ```
259
+
260
+ It prints something like `AUROC: 0.96 · ECE: 0.08 → 0.02 (calibrated)`. Then:
261
+
262
+ ```bash
263
+ PATHQA_MODEL=pcam_model.pt ./pathqa-app # the app now uses your real model
264
+ ```
265
+
266
+ Note: full PCam training needs a GPU and the ~7 GB download; the synthetic
267
+ `--synthetic` path exists to verify the training/metrics/calibration code runs
268
+ end-to-end without either. The pipeline was verified this way (AUROC/ECE/
269
+ checkpoint all produced correctly); real clinical numbers come from your run.
270
+
271
+ ## Key parameters
272
+
273
+ | Flag | Meaning |
274
+ |---|---|
275
+ | `--tau 0.9` | Flag disagreements at/above this confidence. |
276
+ | `--budget 0.05` | Instead of `tau`, flag only the top 5% most-confident disagreements (fits a workload). |
277
+ | `--path-error-rate` | (demo only) simulated pathologist error rate, to show the safety-net catching misses. |
278
+ | `--subset` / `--syn-train` | Cap dataset size for CPU-friendly runs. |
279
+
280
+ `tau` is the single most important dial. Lower it → catch more true misses but a
281
+ longer re-check queue; raise it → shorter queue but you may miss borderline
282
+ errors. Tune it against the lab's tolerated false-flag rate on a labeled
283
+ holdout, then re-check monthly.
284
+
285
+ ---
286
+
287
+ ## What was verified
288
+
289
+ Ran end-to-end on CPU (ARM64): training converges, temperature calibration
290
+ lowers validation loss, both threshold and workload-budget flagging modes
291
+ produce a correct prioritized worklist, and the JSON report round-trips. The
292
+ real-data path uses the same code with `--pcam` or `--data`.
293
+
294
+ ## Roadmap (v2+, out of scope for this build)
295
+
296
+ - **Slide-level, not just patch-level:** tile a whole-slide image, aggregate
297
+ patch scores into a slide decision, and flag at the slide level.
298
+ - **Uncertainty on top of calibration:** MC-dropout / deep ensembles to separate
299
+ "confident disagreement" from "model has no idea."
300
+ - **Active learning loop:** feed re-checked flags back as new labels so the model
301
+ improves on the lab's hard cases over time.
302
+ - **Human factors:** a viewer that jumps to the flagged region with a heatmap
303
+ (Grad-CAM) so re-review takes seconds.
304
+ - **Governance:** audit log of every flag + outcome, and drift monitoring on the
305
+ incoming slide distribution.
306
+
307
+ ## Regulatory framing (important, not legal advice)
308
+
309
+ Framing PathQA as an internal **QA / workflow** tool that only surfaces cases for
310
+ human re-review — never rendering or altering a diagnosis — is a deliberately
311
+ conservative posture. Anything that outputs a diagnosis is a different, much
312
+ heavier regulatory category. Keep the "assist, not replace, human-in-the-loop"
313
+ boundary bright, and involve regulatory/clinical governance before any use on
314
+ real patient material. I'm not a lawyer or a regulatory advisor; validate the
315
+ intended-use claim with someone who is.
316
+
317
+ ## Limitations
318
+
319
+ Binary tumor/normal patches only; no whole-slide aggregation yet; PatchCamelyon
320
+ is lymph-node metastasis and is not representative of your tissue types — the
321
+ public-data demo proves the *mechanism*, not clinical performance. Clinical
322
+ performance must be established on your own validated data.
323
+ ```
Dockerfile ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Pathify — container for free hosting (e.g. Hugging Face Spaces, Docker SDK).
2
+ FROM python:3.10-slim
3
+
4
+ WORKDIR /app
5
+
6
+ # CPU-only PyTorch + light deps (no CUDA, keeps the image small).
7
+ RUN pip install --no-cache-dir torch==2.4.1 torchvision==0.19.1 \
8
+ --index-url https://download.pytorch.org/whl/cpu \
9
+ && pip install --no-cache-dir pillow numpy h5py
10
+
11
+ COPY . .
12
+
13
+ # Writable, ephemeral locations so it runs even as a non-root container user.
14
+ ENV PYTHONPATH=/app:/app/backend \
15
+ OMP_NUM_THREADS=2 \
16
+ PATHQA_AUDIT_LOG=/tmp/audit_log.jsonl \
17
+ PATHQA_FEEDBACK_DIR=/tmp/feedback
18
+
19
+ EXPOSE 7860
20
+
21
+ # Bind to 0.0.0.0 so the host can reach it. Small demo cohort = fast boot.
22
+ CMD ["python", "backend/server.py", "--host", "0.0.0.0", "--port", "7860", \
23
+ "--cases", "60", "--slides", "4", "--slide-grid", "12", "--demo-train-steps", "2"]
HOSTING.md ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Host Pathify online for free (Hugging Face Spaces)
2
+
3
+ This gives you a public link anyone can open, no server to manage, no cost.
4
+ You will use `pathify_hfspace.zip` (the deploy bundle).
5
+
6
+ ## What you need
7
+ - A free Hugging Face account: https://huggingface.co/join
8
+ - The file `pathify_hfspace.zip`, unzipped on your computer.
9
+
10
+ ## Steps (about 10 minutes, most of it waiting for the build)
11
+
12
+ 1. Sign in at https://huggingface.co
13
+
14
+ 2. Create a Space:
15
+ - Go to https://huggingface.co/new-space
16
+ - Owner: you. Space name: `pathify`
17
+ - License: MIT
18
+ - Select the Space SDK: **Docker** → template **Blank**
19
+ - Hardware: **CPU basic** (free). Visibility: **Public**
20
+ - Click **Create Space**
21
+
22
+ 3. Unzip `pathify_hfspace.zip` on your computer. You will see `Dockerfile`,
23
+ `README.md`, and the folders `backend`, `frontend`, `pathqa`, `samples`, etc.
24
+
25
+ 4. Upload the files to the Space:
26
+ - On your new Space page, open the **Files** tab
27
+ - Click **Add file → Upload files**
28
+ - Drag in EVERYTHING from the unzipped folder (the `Dockerfile`, `README.md`,
29
+ and all the folders). Upload the *contents*, not the outer folder.
30
+ - Scroll down and click **Commit changes to main**
31
+
32
+ 5. The Space builds itself automatically (it installs PyTorch, so the first
33
+ build takes ~5-10 minutes). Watch the status at the top:
34
+ **Building → Running**. You can click **Logs** to watch progress.
35
+
36
+ 6. When it says **Running**, open the app at:
37
+ `https://<your-username>-pathify.hf.space`
38
+ Try the **Analyze image** tab and upload a sample from the `samples` folder.
39
+
40
+ ## Good to know
41
+ - Free CPU Spaces "sleep" after a while of no use. The next visit wakes it in
42
+ ~30 seconds. That is normal.
43
+ - On start it trains a tiny demo model (about a minute), so the first page load
44
+ after a build/wake can be slow. After that it is quick.
45
+ - It is running the DEMO model on synthetic data, so results show how it works,
46
+ not real accuracy. To make it real, train on labelled slides
47
+ (`train_pcam.py` / `finetune_from_feedback.py`) and put the resulting
48
+ `model.pt` in the Space, then set the env var `PATHQA_MODEL=model.pt` in the
49
+ Space Settings.
50
+
51
+ ## Editing later
52
+ Change a file in the Space **Files** tab (or we update it here and you
53
+ re-upload). Every commit triggers an automatic rebuild, so your edits go live
54
+ on the same link.
55
+
56
+ ## Faster alternative (no account, temporary)
57
+ Keep running it locally with `bash pathqa-app`, then in another terminal expose
58
+ it with a tunnel, e.g. `npx cloudflared tunnel --url http://127.0.0.1:8000`.
59
+ You get a temporary public link that lasts only while your Mac keeps it running.
README.md CHANGED
@@ -1,12 +1,25 @@
1
  ---
2
  title: Pathify
3
- emoji: 🏆
4
- colorFrom: gray
5
- colorTo: red
6
- sdk: static
 
7
  pinned: false
8
  license: mit
9
- short_description: Second arm for Pathologist
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: Pathify
3
+ emoji: 🔬
4
+ colorFrom: blue
5
+ colorTo: indigo
6
+ sdk: docker
7
+ app_port: 7860
8
  pinned: false
9
  license: mit
 
10
  ---
11
 
12
+ # Pathify — pathology QA second reader (demo)
13
+
14
+ A quality-assurance assistant for pathology, not a diagnostic tool. It gives an
15
+ independent second read and flags cases worth a human re-check. It never
16
+ diagnoses and never changes a pathologist's sign-out.
17
+
18
+ - Patch QA and Whole-slide QA worklists (with tumour heatmaps).
19
+ - Analyze image: upload an H&E image, get the trained model's read plus a stain
20
+ check, combined into one verdict, with a Grad-CAM / heatmap overlay.
21
+ - Teach the model: label images to build training data, then fine-tune.
22
+
23
+ This Space runs on a small demo model trained on synthetic data, so results show
24
+ how the workflow behaves, not clinical accuracy. For real use, train on labelled
25
+ slides and validate before relying on it.
audit_log.jsonl ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ {"ts": "2026-07-27T11:03:31", "case_id": "case_000017", "action": "amend", "note": "confirmed micromet on re-read", "pathologist_label": 0, "model_read": "tumor", "model_confidence": 1.0}
2
+ {"ts": "2026-07-27T11:39:36", "level": "slide", "slide_id": "slide_006", "action": "amend", "note": "micromet on re-read", "pathologist_label": 0, "model_read": "tumor", "slide_score": 1.0}
backend/qa_service.py ADDED
@@ -0,0 +1,423 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """QA session service — the stateful layer the app talks to.
2
+
3
+ Holds one review session in memory: the per-case reviews from the SecondReader,
4
+ the patch image for each case (so the UI can show it), and the pathologist's
5
+ decisions. Recomputes flags live when the QA threshold / workload changes, and
6
+ appends every decision to an audit log (governance requirement).
7
+
8
+ The model is loaded from a checkpoint if PATHQA_MODEL points at one; otherwise a
9
+ small demo model is fine-tuned on synthetic patches at first boot and cached, so
10
+ the app is runnable out of the box with nothing to set up.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import io
15
+ import json
16
+ import os
17
+ import threading
18
+ import time
19
+ from pathlib import Path
20
+ from typing import Dict, List, Optional
21
+
22
+ import torch
23
+ from PIL import Image
24
+
25
+ from pathqa.data import (IMAGENET_MEAN, IMAGENET_STD, SyntheticPatches,
26
+ get_synthetic_loaders)
27
+ from pathqa.engine import fit_temperature, train_one_epoch
28
+ from pathqa.model import TemperatureScaler, build_model
29
+ from pathqa.qa import SecondReader
30
+ from pathqa.slide import SlideScorer, render_heatmap, review_slides
31
+ from pathqa.wsi import SlideTiler, SyntheticSlide
32
+
33
+ _MEAN = torch.tensor(IMAGENET_MEAN).view(3, 1, 1)
34
+ _STD = torch.tensor(IMAGENET_STD).view(3, 1, 1)
35
+
36
+
37
+ def tensor_to_png(x: torch.Tensor) -> bytes:
38
+ """De-normalize a CHW patch tensor back to a viewable PNG."""
39
+ img = (x.detach().cpu() * _STD + _MEAN).clamp(0, 1)
40
+ arr = (img.permute(1, 2, 0).numpy() * 255).astype("uint8")
41
+ buf = io.BytesIO()
42
+ Image.fromarray(arr).save(buf, format="PNG")
43
+ return buf.getvalue()
44
+
45
+
46
+ class QASession:
47
+ def __init__(
48
+ self,
49
+ model_path: Optional[str] = None,
50
+ audit_log: Optional[str] = None,
51
+ tau: float = 0.9,
52
+ budget: Optional[float] = None,
53
+ n_cases: int = 200,
54
+ path_error_rate: float = 0.08,
55
+ demo_train_steps: int = 3,
56
+ n_slides: int = 6,
57
+ slide_grid: int = 14,
58
+ slide_tau: float = 0.7,
59
+ ):
60
+ self.lock = threading.Lock()
61
+ self.audit_log = audit_log or os.environ.get("PATHQA_AUDIT_LOG", "audit_log.jsonl")
62
+ self.feedback_dir = os.environ.get("PATHQA_FEEDBACK_DIR", "data/feedback")
63
+ # Images the bundled model already learned from: PathMNIST train (89,996)
64
+ # + PatchCamelyon train (262,144). Pathologist submissions add on top.
65
+ self.BASE_IMAGES = int(os.environ.get("PATHQA_BASE_IMAGES", "352140"))
66
+ self.tau = tau
67
+ self.budget = budget
68
+ self.n_cases = n_cases
69
+ self.path_error_rate = path_error_rate
70
+ self.slide_tau = slide_tau
71
+ self.device = torch.device("cpu")
72
+ self.decisions: Dict[str, dict] = {}
73
+ self.patches: Dict[str, torch.Tensor] = {}
74
+ self.truth: Dict[str, int] = {}
75
+ # slide state
76
+ self.slide_scores: dict = {}
77
+ self.slide_labels: Dict[str, int] = {}
78
+ self.slide_truth: Dict[str, int] = {}
79
+ self.slide_heatmaps: Dict[str, bytes] = {}
80
+ self.slide_decisions: Dict[str, dict] = {}
81
+
82
+ self.model, self.scaler = self._load_or_train(model_path, demo_train_steps)
83
+ self.reader = SecondReader(self.model, self.scaler, self.device)
84
+ self._build_signout()
85
+ self.recompute()
86
+ self._n_slides, self._slide_grid = n_slides, slide_grid
87
+ if n_slides > 0:
88
+ self._build_slides(n_slides, slide_grid)
89
+
90
+ # ----- model -----
91
+ def _load_or_train(self, model_path, steps):
92
+ model = build_model("resnet18", pretrained=False)
93
+ scaler = TemperatureScaler()
94
+ # If no model given, use a bundled model.pt shipped next to the app.
95
+ if not model_path:
96
+ here = os.path.dirname(__file__)
97
+ for cand in ("model.pt", os.path.join(here, "..", "model.pt")):
98
+ if os.path.exists(cand):
99
+ model_path = cand; break
100
+ if model_path and Path(model_path).exists():
101
+ ckpt = torch.load(model_path, map_location="cpu")
102
+ model.load_state_dict(ckpt["state_dict"])
103
+ scaler.set_temperature(float(ckpt.get("temperature", 1.0)))
104
+ self.model_info = {"source": "trained", "metrics": ckpt.get("metrics", {}),
105
+ "file": Path(model_path).name}
106
+ return model, scaler
107
+ # Demo: quick fine-tune on synthetic patches so confidences are meaningful.
108
+ train_dl, val_dl, _ = get_synthetic_loaders(n_train=256, n_eval=128, batch_size=32)
109
+ optim = torch.optim.Adam(model.parameters(), lr=1e-3)
110
+ for _ in range(max(1, steps)):
111
+ train_one_epoch(model, train_dl, optim, self.device)
112
+ scaler.set_temperature(fit_temperature(model, val_dl, self.device))
113
+ self.model_info = {"source": "demo", "metrics": {}}
114
+ return model, scaler
115
+
116
+ # ----- data / sign-out queue -----
117
+ def _build_signout(self):
118
+ ds = SyntheticPatches(n=self.n_cases, seed=99)
119
+ rng = torch.Generator().manual_seed(7)
120
+ for i in range(len(ds)):
121
+ x, true_label = ds[i]
122
+ cid = f"case_{i:06d}"
123
+ path_label = true_label
124
+ if torch.rand(1, generator=rng).item() < self.path_error_rate:
125
+ path_label = 1 - true_label # simulated human miss
126
+ self.patches[cid] = x
127
+ self.truth[cid] = int(true_label)
128
+ self.decisions.setdefault(cid, {"case_id": cid, "pathologist_label": int(path_label)})
129
+
130
+ # ----- QA compute -----
131
+ def recompute(self):
132
+ with self.lock:
133
+ ids = sorted(self.patches.keys())
134
+ xb = torch.stack([self.patches[c] for c in ids])
135
+ yb = torch.tensor([self.decisions[c]["pathologist_label"] for c in ids])
136
+
137
+ class _One:
138
+ def __iter__(self_):
139
+ yield xb, yb
140
+
141
+ self.report = self.reader.review_loader(
142
+ _One(), tau=self.tau, workload_budget=self.budget, case_ids=ids
143
+ )
144
+ self._by_id = {r.case_id: r for r in self.report.reviews}
145
+
146
+ def set_threshold(self, tau: Optional[float] = None, budget: Optional[float] = None):
147
+ if budget is not None:
148
+ self.budget, self.tau = budget, 0.9
149
+ elif tau is not None:
150
+ self.tau, self.budget = tau, None
151
+ self.recompute()
152
+
153
+ # ----- views -----
154
+ def summary(self) -> dict:
155
+ r = self.report
156
+ resolved = sum(1 for d in self.decisions.values() if d.get("action"))
157
+ return {
158
+ "n_cases": r.n_cases,
159
+ "n_disagreements": r.n_disagreements,
160
+ "n_flagged": r.n_flagged,
161
+ "disagreement_rate": r.disagreement_rate,
162
+ "flag_rate": r.flag_rate,
163
+ "tau": r.tau,
164
+ "mode": "budget" if self.budget is not None else "threshold",
165
+ "budget": self.budget,
166
+ "resolved": resolved,
167
+ }
168
+
169
+ def worklist(self) -> List[dict]:
170
+ flagged = sorted(self.report.flagged, key=lambda r: r.model_confidence, reverse=True)
171
+ out = []
172
+ for i, r in enumerate(flagged, 1):
173
+ d = self.decisions.get(r.case_id, {})
174
+ out.append({
175
+ "priority": i,
176
+ "case_id": r.case_id,
177
+ "pathologist_read": r.pathologist_read,
178
+ "model_read": r.model_read,
179
+ "model_confidence": round(r.model_confidence, 3),
180
+ "model_prob_tumor": round(r.model_prob_tumor, 3),
181
+ "reason": r.reason,
182
+ "decision": d.get("action"),
183
+ "note": d.get("note"),
184
+ })
185
+ return out
186
+
187
+ def patch_png(self, case_id: str) -> Optional[bytes]:
188
+ x = self.patches.get(case_id)
189
+ return tensor_to_png(x) if x is not None else None
190
+
191
+ def patch_cam_png(self, case_id: str) -> Optional[bytes]:
192
+ """Grad-CAM overlay showing where the model looked on this patch."""
193
+ x = self.patches.get(case_id)
194
+ if x is None:
195
+ return None
196
+ from pathqa.gradcam import gradcam_png
197
+ return gradcam_png(self.model, x, device=self.device)
198
+
199
+ # ----- hot-swap the model from an uploaded checkpoint -----
200
+ def load_model_from_upload(self, data_url: str) -> dict:
201
+ import base64
202
+ from io import BytesIO
203
+ raw = base64.b64decode(data_url.split(",", 1)[-1])
204
+ ck = torch.load(BytesIO(raw), map_location="cpu")
205
+ model = build_model(ck.get("backbone", "resnet18"), pretrained=False)
206
+ model.load_state_dict(ck["state_dict"])
207
+ scaler = TemperatureScaler(); scaler.set_temperature(float(ck.get("temperature", 1.0)))
208
+ with self.lock:
209
+ self.model = model.to(self.device).eval()
210
+ self.scaler = scaler
211
+ self.reader = SecondReader(self.model, self.scaler, self.device)
212
+ self.model_info = {"source": "uploaded", "metrics": ck.get("metrics", {})}
213
+ self.recompute()
214
+ if self._n_slides > 0:
215
+ self.slide_scores, self.slide_labels, self.slide_truth = {}, {}, {}
216
+ self.slide_heatmaps, self.slide_decisions = {}, {}
217
+ self._build_slides(self._n_slides, self._slide_grid)
218
+ return {"ok": True, "metrics": ck.get("metrics", {}), "labels": ck.get("labels", {}),
219
+ "note": ck.get("note", "")}
220
+
221
+ # ----- real image analysis (the trained CNN, not the browser heuristic) -----
222
+ def analyze_image(self, data_url: str) -> dict:
223
+ import base64
224
+ from io import BytesIO
225
+ from PIL import Image
226
+ from pathqa.infer import analyze_image as _analyze
227
+ b64 = data_url.split(",", 1)[-1]
228
+ img = Image.open(BytesIO(base64.b64decode(b64))).convert("RGB")
229
+ res = _analyze(self.model, self.scaler, img, self.device)
230
+ enc = lambda b: "data:image/png;base64," + base64.b64encode(b).decode()
231
+ for src, dst in (("overlay_png", "overlay"), ("stain_overlay_png", "stain_overlay")):
232
+ blob = res.pop(src, None)
233
+ if blob is not None:
234
+ res[dst] = enc(blob)
235
+ for t in res.get("tiles", []):
236
+ if "tile_png" in t:
237
+ t["tile"] = enc(t.pop("tile_png"))
238
+ if "cam_png" in t:
239
+ t["cam"] = enc(t.pop("cam_png"))
240
+ return res
241
+
242
+ # ----- feedback: turn a reviewed image into training data -----
243
+ def save_feedback(self, data_url: str, label: str, feedback_dir: Optional[str] = None,
244
+ auto_learn: bool = False) -> dict:
245
+ import base64, time
246
+ from io import BytesIO
247
+ from PIL import Image
248
+ feedback_dir = feedback_dir or self.feedback_dir
249
+ if label not in ("normal", "tumor"):
250
+ raise ValueError("label must be 'normal' or 'tumor'")
251
+ d = Path(feedback_dir) / label
252
+ d.mkdir(parents=True, exist_ok=True)
253
+ img = Image.open(BytesIO(base64.b64decode(data_url.split(",", 1)[-1]))).convert("RGB")
254
+ fn = d / f"{label}_{int(time.time()*1000)}.png"
255
+ img.save(fn)
256
+ stats = self.feedback_stats(feedback_dir)
257
+ out = {"stats": stats, "retrained": False}
258
+ # Auto-learn: once there are a few of each label, fold every new
259
+ # submission into the model and save it, so the next analysis uses it.
260
+ if auto_learn and stats["normal"] >= 3 and stats["tumor"] >= 3:
261
+ try:
262
+ r = self.retrain_on_feedback(epochs=1)
263
+ out["retrained"] = True
264
+ out["val_auroc"] = r["val_auroc"]
265
+ out["saved_to"] = r["saved_to"]
266
+ except Exception as e: # keep the submission even if training hiccups
267
+ out["error"] = str(e)
268
+ return out
269
+
270
+ def retrain_on_feedback(self, epochs: int = 3) -> dict:
271
+ """Continue training the CURRENT model on the labels submitted so far,
272
+ save the updated model.pt, and hot-swap it in. This is the 'learn from
273
+ pathologist submissions' loop, one click instead of a script."""
274
+ from torch.utils.data import DataLoader, random_split
275
+ from torchvision import datasets
276
+ from pathqa.data import _eval_tfms, _train_tfms
277
+ from pathqa.engine import evaluate as _eval
278
+
279
+ root = Path(self.feedback_dir)
280
+ counts = {c: len(list((root / c).glob("*.png"))) if (root / c).exists() else 0
281
+ for c in ("normal", "tumor")}
282
+ if counts["normal"] < 3 or counts["tumor"] < 3:
283
+ raise ValueError(f"Need at least 3 of each label first (have {counts}). Submit more cases.")
284
+
285
+ full = datasets.ImageFolder(str(root))
286
+ if full.class_to_idx != {"normal": 0, "tumor": 1}:
287
+ raise ValueError(f"Unexpected label folders: {full.class_to_idx}")
288
+ n = len(full); n_val = max(1, int(0.25 * n))
289
+ g = torch.Generator().manual_seed(0)
290
+ tr, va = random_split(full, [n - n_val, n_val], generator=g)
291
+ tr.dataset = datasets.ImageFolder(str(root), transform=_train_tfms())
292
+ va.dataset = datasets.ImageFolder(str(root), transform=_eval_tfms())
293
+ train_dl = DataLoader(tr, batch_size=16, shuffle=True)
294
+ val_dl = DataLoader(va, batch_size=16)
295
+
296
+ with self.lock:
297
+ optim = torch.optim.Adam(self.model.parameters(), lr=1e-4)
298
+ for _ in range(max(1, epochs)):
299
+ train_one_epoch(self.model, train_dl, optim, self.device)
300
+ res = _eval(self.model, val_dl, self.device)
301
+ T = fit_temperature(self.model, val_dl, self.device)
302
+ self.scaler.set_temperature(T)
303
+ self.reader = SecondReader(self.model, self.scaler, self.device)
304
+ # save to the model file in use (fall back to /tmp if read-only)
305
+ save_to = os.environ.get("PATHQA_MODEL") or "model.pt"
306
+ ckpt = {"state_dict": self.model.state_dict(), "backbone": "resnet18",
307
+ "temperature": T, "labels": {0: "normal", 1: "tumor"},
308
+ "metrics": {"val_auroc": res.auroc, "val_acc": res.accuracy},
309
+ "note": "Pathify model, continued training on submitted labels."}
310
+ try:
311
+ torch.save(ckpt, save_to)
312
+ except OSError:
313
+ save_to = "/tmp/model.pt"; torch.save(ckpt, save_to)
314
+ self.model_info = {"source": "retrained",
315
+ "metrics": {"test_auroc": res.auroc, "val_acc": res.accuracy}}
316
+ self.recompute()
317
+ if self._n_slides > 0:
318
+ self.slide_scores, self.slide_labels, self.slide_truth = {}, {}, {}
319
+ self.slide_heatmaps, self.slide_decisions = {}, {}
320
+ self._build_slides(self._n_slides, self._slide_grid)
321
+ return {"ok": True, "n_train": n - n_val, "n_val": n_val,
322
+ "val_auroc": round(res.auroc, 3), "saved_to": save_to, "counts": counts}
323
+
324
+ def feedback_stats(self, feedback_dir: Optional[str] = None) -> dict:
325
+ base = Path(feedback_dir or self.feedback_dir)
326
+ counts = {}
327
+ for lab in ("normal", "tumor"):
328
+ p = base / lab
329
+ counts[lab] = len(list(p.glob("*.png"))) if p.exists() else 0
330
+ counts["total"] = counts["normal"] + counts["tumor"]
331
+ counts["ready_to_train"] = counts["normal"] >= 10 and counts["tumor"] >= 10
332
+ return counts
333
+
334
+ # ----- slides -----
335
+ def _build_slides(self, n_slides: int, grid: int):
336
+ import random as _r
337
+ rng = _r.Random(11)
338
+ scorer = SlideScorer(self.model, self.scaler, self.device, topk_frac=0.02, min_topk=4)
339
+ for i in range(n_slides):
340
+ has_tumor = (i % 2 == 0)
341
+ slide = SyntheticSlide(grid=grid, tumor=has_tumor, seed=100 + i)
342
+ sid = f"slide_{i:03d}"
343
+ tiler = SlideTiler(slide.image(), tile_size=slide.tile, model_size=96)
344
+ sc = scorer.score_slide(sid, tiler)
345
+ lb = int(has_tumor)
346
+ if rng.random() < 0.25:
347
+ lb = 1 - lb # simulated sign-out error
348
+ self.slide_scores[sid] = sc
349
+ self.slide_truth[sid] = int(has_tumor)
350
+ self.slide_labels[sid] = lb
351
+ self.slide_heatmaps[sid] = render_heatmap(sc, base_image=slide.image())
352
+ self.slide_decisions.setdefault(sid, {"slide_id": sid, "pathologist_label": lb})
353
+
354
+ def slide_summary(self) -> dict:
355
+ reviews = review_slides(self.slide_scores, self.slide_labels, tau=self.slide_tau)
356
+ flagged = sum(1 for r in reviews if r.flagged)
357
+ resolved = sum(1 for d in self.slide_decisions.values() if d.get("action"))
358
+ return {"n_slides": len(reviews), "n_flagged": flagged,
359
+ "resolved": resolved, "slide_tau": self.slide_tau}
360
+
361
+ def slide_worklist(self) -> List[dict]:
362
+ reviews = review_slides(self.slide_scores, self.slide_labels, tau=self.slide_tau)
363
+ flagged = sorted([r for r in reviews if r.flagged],
364
+ key=lambda r: r.confidence, reverse=True)
365
+ out = []
366
+ for i, r in enumerate(flagged, 1):
367
+ sc = self.slide_scores[r.slide_id]
368
+ d = self.slide_decisions.get(r.slide_id, {})
369
+ out.append({
370
+ "priority": i, "slide_id": r.slide_id,
371
+ "pathologist_read": r.pathologist_read, "model_read": r.model_read,
372
+ "slide_score": round(r.slide_score, 3), "confidence": round(r.confidence, 3),
373
+ "n_tumor_tiles": r.n_tumor_tiles, "n_tissue_tiles": sc.n_tissue_tiles,
374
+ "reason": r.reason, "decision": d.get("action"),
375
+ })
376
+ return out
377
+
378
+ def slide_heatmap_png(self, slide_id: str) -> Optional[bytes]:
379
+ return self.slide_heatmaps.get(slide_id)
380
+
381
+ def set_slide_tau(self, tau: float):
382
+ self.slide_tau = float(tau)
383
+
384
+ def record_slide_decision(self, slide_id: str, action: str, note: str = "") -> dict:
385
+ if slide_id not in self.slide_decisions:
386
+ raise KeyError(slide_id)
387
+ if action not in ("confirm_signout", "amend"):
388
+ raise ValueError("action must be 'confirm_signout' or 'amend'")
389
+ sc = self.slide_scores.get(slide_id)
390
+ with self.lock:
391
+ entry = {
392
+ "ts": time.strftime("%Y-%m-%dT%H:%M:%S"), "level": "slide",
393
+ "slide_id": slide_id, "action": action, "note": note,
394
+ "pathologist_label": self.slide_decisions[slide_id]["pathologist_label"],
395
+ "model_read": sc.model_read if sc else None,
396
+ "slide_score": round(sc.slide_score, 3) if sc else None,
397
+ }
398
+ self.slide_decisions[slide_id].update({"action": action, "note": note})
399
+ with open(self.audit_log, "a") as f:
400
+ f.write(json.dumps(entry) + "\n")
401
+ return entry
402
+
403
+ def record_decision(self, case_id: str, action: str, note: str = "") -> dict:
404
+ if case_id not in self.decisions:
405
+ raise KeyError(case_id)
406
+ if action not in ("confirm_signout", "amend"):
407
+ raise ValueError("action must be 'confirm_signout' or 'amend'")
408
+ with self.lock:
409
+ entry = {
410
+ "ts": time.strftime("%Y-%m-%dT%H:%M:%S"),
411
+ "case_id": case_id,
412
+ "action": action, # confirm_signout = pathologist kept their read
413
+ # amend = re-review changed the read (model caught it)
414
+ "note": note,
415
+ "pathologist_label": self.decisions[case_id]["pathologist_label"],
416
+ "model_read": self._by_id[case_id].model_read if case_id in self._by_id else None,
417
+ "model_confidence": (round(self._by_id[case_id].model_confidence, 3)
418
+ if case_id in self._by_id else None),
419
+ }
420
+ self.decisions[case_id].update({"action": action, "note": note})
421
+ with open(self.audit_log, "a") as f:
422
+ f.write(json.dumps(entry) + "\n")
423
+ return entry
backend/server.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """PathQA local server.
3
+
4
+ A zero-extra-dependency backend (Python stdlib only, beyond torch) chosen for an
5
+ on-prem / air-gapped lab: nothing to install, nothing phones home, slide data
6
+ never leaves the machine. Serves the JSON API and the single-file React UI.
7
+
8
+ Run:
9
+ PYTHONPATH=. python backend/server.py # demo model, synthetic data
10
+ PATHQA_MODEL=model.pt PYTHONPATH=. python backend/server.py --port 8000
11
+
12
+ Then open http://127.0.0.1:8000 (binds to localhost only by design).
13
+
14
+ To swap in FastAPI+uvicorn later, the QASession API in qa_service.py maps 1:1
15
+ onto path operations; the routing here is deliberately thin.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import json
21
+ import os
22
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
23
+ from pathlib import Path
24
+ from urllib.parse import urlparse
25
+
26
+ from qa_service import QASession
27
+
28
+ FRONTEND = Path(__file__).resolve().parent.parent / "frontend"
29
+ SESSION: QASession = None # set in main()
30
+
31
+
32
+ class Handler(BaseHTTPRequestHandler):
33
+ server_version = "PathQA/0.1"
34
+
35
+ # -- helpers --
36
+ def _send(self, code, body: bytes, ctype="application/json"):
37
+ self.send_response(code)
38
+ self.send_header("Content-Type", ctype)
39
+ self.send_header("Content-Length", str(len(body)))
40
+ self.send_header("Cache-Control", "no-store")
41
+ self.end_headers()
42
+ self.wfile.write(body)
43
+
44
+ def _json(self, obj, code=200):
45
+ self._send(code, json.dumps(obj).encode(), "application/json")
46
+
47
+ def _file(self, path: Path, ctype):
48
+ if not path.exists():
49
+ return self._json({"error": f"not found: {path.name}"}, 404)
50
+ self._send(200, path.read_bytes(), ctype)
51
+
52
+ def log_message(self, *a): # quieter logs
53
+ pass
54
+
55
+ # -- routes --
56
+ def do_GET(self):
57
+ p = urlparse(self.path).path
58
+ if p in ("/", "/index.html"):
59
+ return self._file(FRONTEND / "index.html", "text/html; charset=utf-8")
60
+ if p == "/app.jsx":
61
+ return self._file(FRONTEND / "app.jsx", "text/babel; charset=utf-8")
62
+ if p == "/api/summary":
63
+ return self._json(SESSION.summary())
64
+ if p == "/api/worklist":
65
+ return self._json({"items": SESSION.worklist()})
66
+ if p.startswith("/api/patch/") and p.endswith("/cam.png"):
67
+ cid = p[len("/api/patch/"):-len("/cam.png")]
68
+ png = SESSION.patch_cam_png(cid)
69
+ return self._send(200, png, "image/png") if png else self._json({"error": "no patch"}, 404)
70
+ if p.startswith("/api/patch/"):
71
+ cid = p.rsplit("/", 1)[-1].replace(".png", "")
72
+ png = SESSION.patch_png(cid)
73
+ return self._send(200, png, "image/png") if png else self._json({"error": "no patch"}, 404)
74
+ if p == "/api/feedback/stats":
75
+ return self._json(SESSION.feedback_stats())
76
+ if p == "/api/model-info":
77
+ mi = dict(getattr(SESSION, "model_info", {"source": "demo", "metrics": {}}))
78
+ base = getattr(SESSION, "BASE_IMAGES", 0)
79
+ contrib = SESSION.feedback_stats().get("total", 0)
80
+ mi.update(base_images=base, contributions=contrib, total_images=base + contrib)
81
+ return self._json(mi)
82
+ if p == "/api/slides/summary":
83
+ return self._json(SESSION.slide_summary())
84
+ if p == "/api/slides/worklist":
85
+ return self._json({"items": SESSION.slide_worklist()})
86
+ if p.startswith("/api/slide/") and p.endswith("/heatmap.png"):
87
+ sid = p[len("/api/slide/"):-len("/heatmap.png")]
88
+ png = SESSION.slide_heatmap_png(sid)
89
+ return self._send(200, png, "image/png") if png else self._json({"error": "no slide"}, 404)
90
+ return self._json({"error": "not found"}, 404)
91
+
92
+ def do_POST(self):
93
+ p = urlparse(self.path).path
94
+ length = int(self.headers.get("Content-Length", 0))
95
+ payload = json.loads(self.rfile.read(length) or b"{}")
96
+ try:
97
+ if p == "/api/decision":
98
+ entry = SESSION.record_decision(
99
+ payload["case_id"], payload["action"], payload.get("note", ""))
100
+ return self._json({"ok": True, "entry": entry})
101
+ if p == "/api/settings":
102
+ SESSION.set_threshold(tau=payload.get("tau"), budget=payload.get("budget"))
103
+ return self._json({"ok": True, "summary": SESSION.summary()})
104
+ if p == "/api/analyze-image":
105
+ return self._json(SESSION.analyze_image(payload["image"]))
106
+ if p == "/api/load-model":
107
+ return self._json(SESSION.load_model_from_upload(payload["model"]))
108
+ if p == "/api/retrain":
109
+ return self._json(SESSION.retrain_on_feedback(int(payload.get("epochs", 3))))
110
+ if p == "/api/feedback":
111
+ res = SESSION.save_feedback(payload["image"], payload["label"],
112
+ auto_learn=payload.get("auto_learn", False))
113
+ return self._json({"ok": True, **res})
114
+ if p == "/api/slides/decision":
115
+ entry = SESSION.record_slide_decision(
116
+ payload["slide_id"], payload["action"], payload.get("note", ""))
117
+ return self._json({"ok": True, "entry": entry})
118
+ if p == "/api/slides/settings":
119
+ SESSION.set_slide_tau(payload["tau"])
120
+ return self._json({"ok": True, "summary": SESSION.slide_summary()})
121
+ except (KeyError, ValueError) as e:
122
+ return self._json({"error": str(e)}, 400)
123
+ return self._json({"error": "not found"}, 404)
124
+
125
+
126
+ def serve(host="127.0.0.1", port=8000, open_browser=False, **session_kwargs):
127
+ """Build the QA session and serve until interrupted."""
128
+ global SESSION
129
+ print("[PathQA] preparing QA session (loading/fine-tuning model, scoring slides)...")
130
+ SESSION = QASession(model_path=os.environ.get("PATHQA_MODEL"), **session_kwargs)
131
+ s = SESSION.summary()
132
+ print(f"[PathQA] ready: {s['n_flagged']}/{s['n_cases']} patch cases flagged "
133
+ f"({s['flag_rate']:.1%}) at tau={s['tau']:.2f}")
134
+ url = f"http://{host}:{port}"
135
+ print(f"[PathQA] serving on {url} (localhost only — Ctrl+C to stop)")
136
+ if open_browser:
137
+ import threading, webbrowser
138
+ threading.Timer(1.0, lambda: webbrowser.open(url)).start()
139
+ try:
140
+ ThreadingHTTPServer((host, port), Handler).serve_forever()
141
+ except KeyboardInterrupt:
142
+ print("\n[PathQA] stopped.")
143
+
144
+
145
+ def main():
146
+ ap = argparse.ArgumentParser()
147
+ ap.add_argument("--host", default="127.0.0.1")
148
+ ap.add_argument("--port", type=int, default=8000)
149
+ ap.add_argument("--tau", type=float, default=0.9)
150
+ ap.add_argument("--budget", type=float, default=None)
151
+ ap.add_argument("--cases", type=int, default=200)
152
+ ap.add_argument("--slides", type=int, default=6)
153
+ ap.add_argument("--slide-grid", type=int, default=14)
154
+ ap.add_argument("--demo-train-steps", type=int, default=3)
155
+ ap.add_argument("--open", action="store_true", help="open the browser")
156
+ args = ap.parse_args()
157
+ serve(host=args.host, port=args.port, open_browser=args.open,
158
+ tau=args.tau, budget=args.budget, n_cases=args.cases,
159
+ demo_train_steps=args.demo_train_steps,
160
+ n_slides=args.slides, slide_grid=args.slide_grid)
161
+
162
+
163
+ if __name__ == "__main__":
164
+ main()
demo.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """PathQA end-to-end demo.
3
+
4
+ Runs the whole second-reader pipeline on one command:
5
+
6
+ 1. load patches (PCam public data, or --synthetic for a no-download demo)
7
+ 2. fine-tune the classifier
8
+ 3. calibrate confidences (temperature scaling on the val split)
9
+ 4. simulate a sign-out queue with a realistic pathologist error rate
10
+ 5. run the QA second reader and print + save a prioritized re-check worklist
11
+
12
+ Examples
13
+ --------
14
+ # Fast, no download (verifies the pipeline):
15
+ python demo.py --synthetic --epochs 1
16
+
17
+ # Real public data (downloads PatchCamelyon on first run):
18
+ python demo.py --pcam --subset 4000 --epochs 2 --budget 0.05
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import copy
24
+ import random
25
+ from pathlib import Path
26
+
27
+ import torch
28
+
29
+ from pathqa.data import get_pcam_loaders, get_synthetic_loaders
30
+ from pathqa.engine import (evaluate, expected_calibration_error, fit_temperature,
31
+ train_one_epoch)
32
+ from pathqa.model import TemperatureScaler, build_model
33
+ from pathqa.qa import SecondReader
34
+
35
+
36
+ def _inject_pathologist_labels(loader, error_rate: float, seed: int = 0):
37
+ """Build a 'sign-out' set: true labels with a small fraction flipped to
38
+ simulate the rare human misses a QA layer is meant to catch.
39
+
40
+ Returns (batches, truth): `batches` is a list of (image_batch, path_label_batch)
41
+ preserving the original batching so QA review stays fast, and `truth` is the
42
+ flat list of ground-truth labels in the same order.
43
+ """
44
+ rng = random.Random(seed)
45
+ batches, truth = [], []
46
+ for x, y in loader:
47
+ path_labels = y.clone()
48
+ for i in range(x.size(0)):
49
+ true_label = int(y[i])
50
+ if rng.random() < error_rate:
51
+ path_labels[i] = 1 - true_label # simulated human error
52
+ truth.append(true_label)
53
+ batches.append((x, path_labels))
54
+ return batches, truth
55
+
56
+
57
+ def main() -> None:
58
+ ap = argparse.ArgumentParser(description="PathQA second-reader demo")
59
+ src = ap.add_mutually_exclusive_group()
60
+ src.add_argument("--pcam", action="store_true", help="use PatchCamelyon (downloads)")
61
+ src.add_argument("--synthetic", action="store_true", help="use synthetic patches (no download)")
62
+ ap.add_argument("--data-root", default="./data")
63
+ ap.add_argument("--subset", type=int, default=4000, help="PCam samples per split")
64
+ ap.add_argument("--syn-train", type=int, default=1024, help="synthetic train size")
65
+ ap.add_argument("--syn-eval", type=int, default=512, help="synthetic val/test size")
66
+ ap.add_argument("--epochs", type=int, default=2)
67
+ ap.add_argument("--lr", type=float, default=1e-4)
68
+ ap.add_argument("--batch-size", type=int, default=64)
69
+ ap.add_argument("--max-train-batches", type=int, default=None)
70
+ ap.add_argument("--tau", type=float, default=0.9, help="flag confident disagreements above this")
71
+ ap.add_argument("--budget", type=float, default=None, help="flag only top-X%% disagreements (overrides tau)")
72
+ ap.add_argument("--path-error-rate", type=float, default=0.05, help="simulated pathologist error rate")
73
+ ap.add_argument("--outdir", default="./qa_out")
74
+ ap.add_argument("--no-pretrained", action="store_true")
75
+ args = ap.parse_args()
76
+
77
+ if not args.pcam and not args.synthetic:
78
+ args.synthetic = True # safe default
79
+
80
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
81
+ torch.manual_seed(0)
82
+ print(f"[PathQA] device={device} source={'PCam' if args.pcam else 'synthetic'}")
83
+
84
+ # 1. data
85
+ if args.pcam:
86
+ train_dl, val_dl, test_dl = get_pcam_loaders(
87
+ root=args.data_root, batch_size=args.batch_size,
88
+ num_workers=2, subset=args.subset)
89
+ else:
90
+ train_dl, val_dl, test_dl = get_synthetic_loaders(
91
+ n_train=args.syn_train, n_eval=args.syn_eval, batch_size=args.batch_size)
92
+
93
+ # 2. model + fine-tune
94
+ model = build_model("resnet18", pretrained=not args.no_pretrained).to(device)
95
+ optim = torch.optim.Adam(model.parameters(), lr=args.lr)
96
+ for ep in range(args.epochs):
97
+ loss = train_one_epoch(model, train_dl, optim, device, args.max_train_batches)
98
+ res = evaluate(model, val_dl, device, max_batches=args.max_train_batches)
99
+ print(f"[train] epoch {ep+1}/{args.epochs} loss={loss:.3f} "
100
+ f"val_acc={res.accuracy:.3f} val_auroc={res.auroc:.3f}")
101
+
102
+ # 3. calibrate
103
+ T = fit_temperature(model, val_dl, device, max_batches=args.max_train_batches)
104
+ scaler = TemperatureScaler(); scaler.set_temperature(T)
105
+ raw = evaluate(model, val_dl, device, max_batches=args.max_train_batches)
106
+ cal = evaluate(model, val_dl, device, scaler=scaler, max_batches=args.max_train_batches)
107
+ print(f"[calibrate] temperature T={T:.3f} val_loss raw={raw.loss:.3f} -> cal={cal.loss:.3f}")
108
+
109
+ # 4. build a sign-out queue with simulated human error
110
+ signout, truth = _inject_pathologist_labels(test_dl, args.path_error_rate, seed=7)
111
+
112
+ class _ListLoader:
113
+ def __init__(self, items): self.items = items
114
+ def __iter__(self): return iter(self.items)
115
+
116
+ # 5. QA second reader
117
+ reader = SecondReader(model, scaler=scaler, device=device)
118
+ report = reader.review_loader(_ListLoader(signout), tau=args.tau, workload_budget=args.budget)
119
+
120
+ print("\n" + report.summary())
121
+
122
+ # How well did flagging catch the *injected* human errors?
123
+ truth_t = torch.tensor(truth)
124
+ caught = sum(1 for r, t in zip(report.reviews, truth)
125
+ if r.flagged and r.pathologist_label != t)
126
+ n_errors = int((truth_t != torch.tensor([r.pathologist_label for r in report.reviews])).sum())
127
+ if n_errors:
128
+ print(f"\n[QA effectiveness] of {n_errors} simulated sign-out errors, "
129
+ f"the second reader flagged {caught} ({caught/n_errors:.0%}) for re-check.")
130
+
131
+ out = Path(args.outdir); out.mkdir(parents=True, exist_ok=True)
132
+ report.to_json(str(out / "qa_report.json"))
133
+ report.worklist_to_csv(str(out / "worklist.csv"))
134
+ print(f"\n[saved] {out/'qa_report.json'} and {out/'worklist.csv'}")
135
+ print("Reminder: PathQA outputs re-check recommendations only. It does not "
136
+ "diagnose and does not change any sign-out. The pathologist decides.")
137
+
138
+
139
+ if __name__ == "__main__":
140
+ main()
finetune_from_feedback.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Train-better loop: fine-tune on the cases your team reviewed.
3
+
4
+ Every image you save from the app (with a normal/tumour label) lands in
5
+ data/feedback/. This script trains on that growing pile, so the model keeps
6
+ getting better at exactly the cases your lab sees, and it reports honest
7
+ held-out AUROC + calibration before saving a new checkpoint the app can load.
8
+
9
+ python finetune_from_feedback.py --out pcam_model.pt # start fresh
10
+ python finetune_from_feedback.py --base pcam_model.pt --out pcam_model.pt # continue
11
+
12
+ Layout it reads:
13
+ data/feedback/normal/*.png
14
+ data/feedback/tumor/*.png
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ from pathlib import Path
20
+
21
+ import torch
22
+ from torch.utils.data import DataLoader, random_split
23
+ from torchvision import datasets
24
+
25
+ from pathqa.data import _eval_tfms, _train_tfms
26
+ from pathqa.engine import (evaluate, expected_calibration_error, fit_temperature,
27
+ train_one_epoch)
28
+ from pathqa.model import TemperatureScaler, build_model
29
+
30
+
31
+ @torch.no_grad()
32
+ def _probs_labels(model, loader, device, scaler=None):
33
+ import torch.nn.functional as F
34
+ model.eval(); ps, ys = [], []
35
+ for x, y in loader:
36
+ logits = model(x.to(device))
37
+ if scaler is not None:
38
+ logits = scaler(logits)
39
+ ps.append(F.softmax(logits, 1)[:, 1].cpu()); ys.append(y)
40
+ return torch.cat(ps), torch.cat(ys)
41
+
42
+
43
+ def main():
44
+ ap = argparse.ArgumentParser()
45
+ ap.add_argument("--feedback", default="data/feedback")
46
+ ap.add_argument("--base", default=None, help="checkpoint to continue from")
47
+ ap.add_argument("--out", default="pcam_model.pt")
48
+ ap.add_argument("--epochs", type=int, default=5)
49
+ ap.add_argument("--lr", type=float, default=1e-4)
50
+ ap.add_argument("--batch-size", type=int, default=32)
51
+ ap.add_argument("--val-frac", type=float, default=0.25)
52
+ ap.add_argument("--no-pretrained", action="store_true", help="skip ImageNet weights (offline)")
53
+ args = ap.parse_args()
54
+
55
+ root = Path(args.feedback)
56
+ if not (root / "normal").exists() or not (root / "tumor").exists():
57
+ raise SystemExit(f"Need {root}/normal and {root}/tumor. Save some cases from the app first.")
58
+
59
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
60
+ full = datasets.ImageFolder(str(root)) # classes: normal=0, tumor=1 (alphabetical)
61
+ assert full.class_to_idx == {"normal": 0, "tumor": 1}, full.class_to_idx
62
+ n_val = max(1, int(len(full) * args.val_frac))
63
+ n_train = len(full) - n_val
64
+ g = torch.Generator().manual_seed(0)
65
+ tr, va = random_split(full, [n_train, n_val], generator=g)
66
+ tr.dataset = datasets.ImageFolder(str(root), transform=_train_tfms())
67
+ va.dataset = datasets.ImageFolder(str(root), transform=_eval_tfms())
68
+ train_dl = DataLoader(tr, batch_size=args.batch_size, shuffle=True)
69
+ val_dl = DataLoader(va, batch_size=args.batch_size)
70
+ print(f"[finetune] {n_train} train / {n_val} val images from {root}")
71
+
72
+ model = build_model("resnet18", pretrained=not args.no_pretrained).to(device)
73
+ if args.base and Path(args.base).exists():
74
+ model.load_state_dict(torch.load(args.base, map_location=device)["state_dict"])
75
+ print(f"[finetune] continuing from {args.base}")
76
+ optim = torch.optim.Adam(model.parameters(), lr=args.lr)
77
+
78
+ best, best_state = -1.0, None
79
+ for ep in range(args.epochs):
80
+ loss = train_one_epoch(model, train_dl, optim, device)
81
+ res = evaluate(model, val_dl, device)
82
+ print(f"[epoch {ep+1}/{args.epochs}] loss={loss:.3f} val_acc={res.accuracy:.3f} val_auroc={res.auroc:.3f}")
83
+ if res.auroc >= best:
84
+ best, best_state = res.auroc, {k: v.cpu().clone() for k, v in model.state_dict().items()}
85
+ if best_state:
86
+ model.load_state_dict(best_state)
87
+
88
+ T = fit_temperature(model, val_dl, device)
89
+ scaler = TemperatureScaler(); scaler.set_temperature(T)
90
+ p, y = _probs_labels(model, val_dl, device, scaler)
91
+ ece = expected_calibration_error(p, y)
92
+ print(f"\n[metrics] best val AUROC={best:.3f} ECE(calibrated)={ece:.3f} T={T:.3f}")
93
+
94
+ torch.save({"state_dict": model.state_dict(), "backbone": "resnet18", "temperature": T,
95
+ "labels": {0: "normal", 1: "tumor"},
96
+ "metrics": {"val_auroc": best, "ece": ece},
97
+ "note": "PathQA/Pathify model fine-tuned on lab feedback. QA aid, not a diagnosis."},
98
+ args.out)
99
+ print(f"[saved] {args.out} -> PATHQA_MODEL={args.out} ./pathqa-app")
100
+
101
+
102
+ if __name__ == "__main__":
103
+ main()
frontend/app.jsx ADDED
@@ -0,0 +1,478 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Pathify — pathologist/intern app (single-file React).
2
+ Main flow is ONE guided path: upload a case -> see the whole-slide overview and
3
+ verdict -> zoom into the flagged patches -> confirm the read (which also teaches
4
+ the model). The batch worklists live under a secondary "Review queue" tab.
5
+ Pathify never changes a sign-out and never diagnoses. */
6
+ const {useState, useEffect, useCallback} = React;
7
+
8
+ const POST = (u, b) => fetch(u, {method:"POST", headers:{"Content-Type":"application/json"}, body:JSON.stringify(b)}).then(r=>r.json());
9
+ const api = {
10
+ summary: () => fetch("/api/summary").then(r=>r.json()),
11
+ worklist: () => fetch("/api/worklist").then(r=>r.json()),
12
+ settings: (b) => POST("/api/settings", b),
13
+ decision: (b) => POST("/api/decision", b),
14
+ slideSummary: () => fetch("/api/slides/summary").then(r=>r.json()),
15
+ slideWorklist: () => fetch("/api/slides/worklist").then(r=>r.json()),
16
+ slideSettings: (b) => POST("/api/slides/settings", b),
17
+ slideDecision: (b) => POST("/api/slides/decision", b),
18
+ analyzeImage: (image) => POST("/api/analyze-image", {image}),
19
+ feedback: (image, label, autoLearn) => POST("/api/feedback", {image, label, auto_learn: !!autoLearn}),
20
+ feedbackStats: () => fetch("/api/feedback/stats").then(r=>r.json()),
21
+ loadModel: (model) => POST("/api/load-model", {model}),
22
+ modelInfo: () => fetch("/api/model-info").then(r=>r.json()),
23
+ retrain: (epochs) => POST("/api/retrain", {epochs}),
24
+ };
25
+
26
+ const pct = (x) => (100*x).toFixed(1) + "%";
27
+ const Read = ({v}) => <span className={"pill " + v}>{v}</span>;
28
+ const Card = ({k, v, sub}) => <div className="card"><div className="k">{k}</div>
29
+ <div className="v">{v} {sub && <small>{sub}</small>}</div></div>;
30
+ const readLabel = (r)=> r==="tumor"?"tumour":r;
31
+ const readPill = (r)=> <span className={"pill "+(r==="tumor"?"tumor":r==="normal"?"normal":"uncertain")}>{readLabel(r)}</span>;
32
+ const IMG = {width:150,height:150,objectFit:"cover",border:"1px solid var(--line)",borderRadius:10};
33
+
34
+ /* ---- text report classifier (client-side, 5 buckets, negation-aware) ---- */
35
+ const CATS = {
36
+ benign:{label:"benign / negative",rank:0,bg:"#0f241d",fg:"#a7f3d0"},
37
+ atypical:{label:"atypical / suspicious",rank:1,bg:"#2a1c0a",fg:"#fcd34d"},
38
+ dysplasia:{label:"dysplasia / pre-malignant",rank:2,bg:"#2a1c0a",fg:"#fcd34d"},
39
+ malignant:{label:"malignant / carcinoma",rank:3,bg:"#2a1414",fg:"#fca5a5"},
40
+ nondiag:{label:"non-diagnostic / insufficient",rank:null,bg:"#1c242e",fg:"#8b98a5"},
41
+ uncertain:{label:"uncertain",rank:null,bg:"#1c242e",fg:"#8b98a5"},
42
+ };
43
+ const catPill = (c)=>{ const x=CATS[c]||CATS.uncertain;
44
+ return <span style={{background:x.bg,color:x.fg,padding:"3px 10px",borderRadius:999,fontSize:13,fontWeight:600}}>{x.label}</span>; };
45
+ function scoreCats(t){
46
+ t=" "+(t||"").toLowerCase().replace(/\s+/g," ")+" ";
47
+ const s={malignant:0,dysplasia:0,atypical:0,benign:0,nondiag:0}; const terms=[];
48
+ const add=(k,w,lab,side)=>{s[k]+=w; terms.push({label:lab,w,side});};
49
+ [[/non[- ]?diagnostic/g,2,"non-diagnostic"],[/insufficient|inadequate|scant|paucicellular|acellular/g,1.5,"insufficient sample"],[/cannot be (assessed|evaluated|interpreted)/g,1.5,"cannot be assessed"],[/no (epithelial|diagnostic) (cells|material)/g,1.5,"no diagnostic material"]].forEach(([re,w,lab])=>{const m=t.match(re); if(m)add("nondiag",w*m.length,lab,"nd");});
50
+ const negMal=/(no|negative for|without|absence of|free of)\s+(evidence of\s+)?((?:\w+\s+){0,2})(malignan\w*|tumou?rs?|carcinoma|dysplasi\w*|atypi\w*|neoplas\w*)/g;
51
+ const neg=t.match(negMal); if(neg){neg.forEach(x=>add("benign",3,'"'+x.trim()+'"',"ben")); t=t.replace(negMal," ");}
52
+ [[/benign/g,2.5,"benign"],[/within normal limits/g,2.5,"within normal limits"],[/unremarkable/g,1.5,"unremarkable"],[/reactive/g,1,"reactive changes"],[/preserved (crypt )?architecture/g,1.5,"preserved architecture"]].forEach(([re,w,lab])=>{const m=t.match(re); if(m)add("benign",w*m.length,lab,"ben");});
53
+ [[/adenocarcinoma/g,4,"adenocarcinoma"],[/carcinoma/g,3,"carcinoma"],[/sarcoma/g,3,"sarcoma"],[/malignan\w*/g,3,"malignant"],[/invasiv\w*|invasion/g,2,"invasion"],[/metasta\w*/g,3,"metastasis"]].forEach(([re,w,lab])=>{const m=t.match(re); if(m)add("malignant",w*m.length,lab,"mal");});
54
+ [[/high[- ]grade dysplasia/g,3,"high grade dysplasia"],[/low[- ]grade dysplasia/g,2,"low grade dysplasia"],[/dysplas\w*/g,1.5,"dysplasia"],[/intraepithelial neoplasi\w*/g,2,"intraepithelial neoplasia"]].forEach(([re,w,lab])=>{const m=t.match(re); if(m)add("dysplasia",w*m.length,lab,"warn");});
55
+ [[/atypi\w*/g,1.5,"atypia"],[/suspicious/g,2,"suspicious"],[/cannot exclude|cannot rule out/g,1.5,"cannot exclude malignancy"],[/indeterminate/g,1.5,"indeterminate"]].forEach(([re,w,lab])=>{const m=t.match(re); if(m)add("atypical",w*m.length,lab,"warn");});
56
+ return {s,terms};
57
+ }
58
+ function classifyReport(t){
59
+ const base=scoreCats(t); const s={...base.s};
60
+ const idx=(t||"").toLowerCase().search(/impression|diagnosis|conclusion/);
61
+ if(idx>=0){const si=scoreCats(t.slice(idx)).s; for(const k in s) s[k]+=2*si[k];}
62
+ const axis=["malignant","dysplasia","atypical","benign"];
63
+ const total=Object.values(s).reduce((a,b)=>a+b,0);
64
+ if(total===0) return {cat:"uncertain",conf:0.45,terms:base.terms};
65
+ const axisSum=axis.reduce((a,k)=>a+s[k],0);
66
+ if(s.nondiag>0 && s.nondiag>=axisSum) return {cat:"nondiag",conf:Math.min(0.95,s.nondiag/total+0.3),terms:base.terms};
67
+ const sorted=axis.map(k=>[k,s[k]]).sort((a,b)=>b[1]-a[1]);
68
+ const topK=sorted[0][0], topV=sorted[0][1], secV=sorted[1][1];
69
+ if(topV===0) return {cat:"uncertain",conf:0.5,terms:base.terms};
70
+ return {cat:topK,conf:Math.min(0.96,Math.max(0.55,0.55+0.41*(topV-secV)/(axisSum||1))),terms:base.terms};
71
+ }
72
+
73
+ function Actions({onConfirm, onAmend, note, setNote}) {
74
+ return <div style={{display:"flex",gap:6,alignItems:"center",flexWrap:"wrap"}}>
75
+ <button className="btn confirm" onClick={onConfirm}>Confirm sign-out</button>
76
+ <button className="btn amend" onClick={onAmend}>Amend (model was right)</button>
77
+ <input placeholder="note…" value={note||""} onChange={e=>setNote(e.target.value)}
78
+ style={{background:"var(--panel2)",border:"1px solid var(--line)",color:"var(--text)",borderRadius:6,padding:"5px 7px",fontSize:12,width:110}}/>
79
+ </div>;
80
+ }
81
+ const Tag = ({d}) => <span className={"tag " + d}>{d === "amend" ? "Amended" : "Sign-out confirmed"}</span>;
82
+
83
+ /* =================== GUIDED FLOW (the front door) =================== */
84
+ function Step({n, title, children}) {
85
+ return <div className="card" style={{display:"flex",gap:12,alignItems:"flex-start"}}>
86
+ <div style={{flex:"none",width:26,height:26,borderRadius:"50%",background:"var(--accent)",color:"#0b1418",
87
+ fontWeight:700,fontSize:13,display:"flex",alignItems:"center",justifyContent:"center",marginTop:1}}>{n}</div>
88
+ <div style={{flex:1}}>{title && <div style={{fontSize:15,fontWeight:600,marginBottom:8}}>{title}</div>}{children}</div>
89
+ </div>;
90
+ }
91
+
92
+ function GuidedFlow() {
93
+ const [img, setImg] = useState(null);
94
+ const [res, setRes] = useState(null);
95
+ const [busy, setBusy] = useState(false);
96
+ const [stats, setStats] = useState(null);
97
+ const [decision, setDecision] = useState(null);
98
+ const [zoom, setZoom] = useState(null);
99
+ const [modelMsg, setModelMsg] = useState("Checking model…");
100
+ const [retrainMsg, setRetrainMsg] = useState("");
101
+
102
+ useEffect(() => { api.feedbackStats().then(setStats);
103
+ api.modelInfo().then(mi => {
104
+ const a = mi.metrics && mi.metrics.test_auroc;
105
+ if (mi.source === "trained") setModelMsg("Using the bundled trained model" + (a ? " · AUROC " + a.toFixed(2) : "") + ".");
106
+ else if (mi.source === "uploaded") setModelMsg("Using your loaded model" + (a ? " · AUROC " + a.toFixed(2) : "") + ".");
107
+ else setModelMsg("Using the built-in demo model (train and load one for real reads).");
108
+ }).catch(()=>setModelMsg("")); }, []);
109
+ const loadModel = (e) => { const f=e.target.files[0]; if(!f)return; setModelMsg("Loading "+f.name+"…");
110
+ const r=new FileReader(); r.onload=async()=>{ try{ const res=await api.loadModel(r.result);
111
+ const a=res.metrics&&res.metrics.test_auroc; setModelMsg("Loaded "+f.name+(a?" · test AUROC "+a.toFixed(2):"")+". Analyze an image to use it.");
112
+ }catch(err){ setModelMsg("Could not load that file."); } }; r.readAsDataURL(f); };
113
+ const pick = (e) => { const f=e.target.files[0]; if(!f)return; const r=new FileReader();
114
+ r.onload=()=>{ setImg(r.result); setRes(null); setDecision(null); }; r.readAsDataURL(f); };
115
+ const run = async () => { if(!img)return; setBusy(true); setRes(null); setDecision(null);
116
+ try{ setRes(await api.analyzeImage(img)); } finally{ setBusy(false); } };
117
+ const confirmRead = async (label) => {
118
+ const matched = res.combined.read===label;
119
+ setDecision({label, matched, saving:true});
120
+ const r = await api.feedback(img, label, true); // auto-learn on
121
+ if (r.stats) setStats(r.stats);
122
+ setDecision({label, matched, learned: r.retrained, auroc: r.val_auroc});
123
+ if (r.retrained) setModelMsg("Model updated from submissions"+(r.val_auroc?" · val AUROC "+r.val_auroc:"")+" (saved).");
124
+ };
125
+ const reset = () => { setImg(null); setRes(null); setDecision(null); };
126
+ const retrain = async () => { setRetrainMsg("Fine-tuning on your submitted labels… this can take a minute.");
127
+ try { const r = await api.retrain(3);
128
+ setModelMsg("Retrained on your labels · val AUROC " + r.val_auroc + ". Now in use.");
129
+ setRetrainMsg("Done. Trained on " + r.n_train + " images; updated model saved and live.");
130
+ api.feedbackStats().then(setStats);
131
+ } catch(e) { setRetrainMsg("Need at least 3 'normal' and 3 'tumour' labels before fine-tuning."); } };
132
+
133
+ const verdictColor = (r)=> r==="tumor"?"var(--tumor,#f87171)":r==="normal"?"var(--ok,#34d399)":"var(--warn,#f59e0b)";
134
+
135
+ return <>
136
+ <div className="card" style={{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap",padding:"10px 14px"}}>
137
+ <span style={{fontSize:13,color:"var(--muted)"}}>{modelMsg}</span>
138
+ <label className="btn" style={{cursor:"pointer",marginLeft:"auto"}}>Load model.pt
139
+ <input type="file" accept=".pt" style={{display:"none"}} onChange={loadModel}/></label>
140
+ </div>
141
+ <Step n="1" title="Upload a case">
142
+ <div style={{fontSize:13,color:"var(--muted)",marginBottom:8}}>Choose an H&E image (a small patch or a whole slide). Nothing leaves this machine.</div>
143
+ <input type="file" accept="image/*" onChange={pick}/>
144
+ {img && <button className="btn primary" style={{marginLeft:10}} disabled={busy} onClick={run}>{busy?"Analyzing…":"Analyze case"}</button>}
145
+ {img && !res && <div style={{marginTop:10}}><img src={img} style={IMG}/></div>}
146
+ </Step>
147
+
148
+ {res && <>
149
+ <Step n="2" title="Pathify's read">
150
+ <div className="card" style={{borderLeft:"4px solid "+verdictColor(res.combined.read),marginTop:0}}>
151
+ <div style={{fontSize:18,fontWeight:600}}>{readPill(res.combined.read)} <span style={{fontSize:13,color:"var(--muted)",fontWeight:400}}>combined verdict · {(100*res.combined.confidence).toFixed(0)}% · {res.combined.agree?"model + stain agree":"needs review"}</span></div>
152
+ <div style={{fontSize:13,color:"var(--muted)",marginTop:6}}>{res.combined.note}</div>
153
+ </div>
154
+ <div className="cards" style={{gridTemplateColumns:"repeat(2,1fr)",marginTop:12}}>
155
+ <div className="card"><div className="k">Trained model</div>
156
+ <div className="v" style={{fontSize:17}}>{readPill(res.model.read)}</div>
157
+ <div style={{fontSize:12,color:"var(--muted)",marginTop:6}}>P(tumour) {(100*res.model.prob_tumor).toFixed(0)}%{res.model.uncertainty!=null?` · uncertainty ${(100*res.model.uncertainty).toFixed(0)}%`:""}</div></div>
158
+ <div className="card"><div className="k">Stain check</div>
159
+ <div className="v" style={{fontSize:17}}>{(100*res.stain.suspicion).toFixed(0)}%</div>
160
+ <div style={{fontSize:12,color:"var(--muted)",marginTop:6}}>dense nuclei {(100*res.stain.frac).toFixed(0)}% of tissue</div></div>
161
+ </div>
162
+ <div style={{display:"flex",gap:14,flexWrap:"wrap",marginTop:12}}>
163
+ <figure style={{margin:0,textAlign:"center"}}><img src={img} style={IMG}/><figcaption style={{fontSize:11,color:"var(--muted)"}}>uploaded</figcaption></figure>
164
+ <figure style={{margin:0,textAlign:"center"}}><img src={res.overlay} style={IMG}/><figcaption style={{fontSize:11,color:"var(--muted)"}}>{res.mode==="slide"?"tumour heatmap":"model attention"}</figcaption></figure>
165
+ <figure style={{margin:0,textAlign:"center"}}><img src={res.stain_overlay} style={IMG}/><figcaption style={{fontSize:11,color:"var(--muted)"}}>stain highlight</figcaption></figure>
166
+ </div>
167
+ </Step>
168
+
169
+ {res.mode==="slide" && res.tiles && res.tiles.length>0 &&
170
+ <Step n="3" title="Zoom into the most-suspicious regions">
171
+ <div style={{fontSize:13,color:"var(--muted)",marginBottom:10}}>The specific patches the model reacted to most, with what it looked at (Grad-CAM). This is the "show me where" step.</div>
172
+ <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill,minmax(150px,1fr))",gap:12}}>
173
+ {res.tiles.map((t,i)=><div key={i} className="card" style={{padding:10}}>
174
+ <div style={{display:"flex",gap:6}}>
175
+ <img src={t.tile} style={{width:"50%",borderRadius:6,border:"1px solid var(--line)"}}/>
176
+ <img src={t.cam} style={{width:"50%",borderRadius:6,border:"1px solid var(--line)"}}/>
177
+ </div>
178
+ <div style={{fontSize:11,color:"var(--muted)",marginTop:6}}>tile ({t.row},{t.col}) · P(tumour) {(100*t.prob).toFixed(0)}%</div>
179
+ </div>)}
180
+ </div>
181
+ </Step>}
182
+
183
+ <Step n={res.mode==="slide"?"4":"3"} title="Your call">
184
+ {!decision ? <>
185
+ <div style={{fontSize:13,color:"var(--muted)",marginBottom:8}}>What is your read? This is recorded, and your answer becomes a training example so the model improves.</div>
186
+ <button className="btn confirm" onClick={()=>confirmRead("normal")}>This is normal</button>
187
+ <button className="btn amend" style={{marginLeft:8}} onClick={()=>confirmRead("tumor")}>This is tumour (cancer)</button>
188
+ </> : <>
189
+ <div style={{fontSize:14}}>You marked {readPill(decision.label)}. {decision.matched
190
+ ? <span style={{color:"var(--ok,#34d399)"}}>Pathify agreed, no discrepancy.</span>
191
+ : <span style={{color:"var(--warn,#f59e0b)"}}>This differs from Pathify's read, exactly the kind of case worth a second look. Your correction now trains it.</span>}</div>
192
+ {decision.saving && <div style={{fontSize:12,color:"var(--muted)",marginTop:8}}>Saving and updating the model…</div>}
193
+ {decision.learned && <div style={{fontSize:12,color:"var(--ok,#34d399)",marginTop:8}}>Saved and folded into the model{decision.auroc?` (val AUROC ${decision.auroc})`:""}. It will use this from the next case on.</div>}
194
+ {!decision.saving && !decision.learned && stats && (stats.normal<3||stats.tumor<3) &&
195
+ <div style={{fontSize:12,color:"var(--muted)",marginTop:8}}>Saved. Auto-learning kicks in once there are 3+ of each label (have {stats.normal} normal, {stats.tumor} tumour).</div>}
196
+ <div style={{marginTop:12}}>
197
+ <button className="btn primary" onClick={reset}>Analyze another case</button>
198
+ </div>
199
+ </>}
200
+ </Step>
201
+ </>}
202
+
203
+ {zoom && <div className="modal" onClick={()=>setZoom(null)}><div className="box" onClick={e=>e.stopPropagation()}>
204
+ <img src={zoom} alt="zoom"/></div></div>}
205
+ </>;
206
+ }
207
+
208
+ /* =================== Batch worklists (secondary "Review queue") =================== */
209
+ function PatchesView() {
210
+ const [summary, setSummary] = useState(null);
211
+ const [items, setItems] = useState([]);
212
+ const [tau, setTau] = useState(0.90);
213
+ const [zoom, setZoom] = useState(null);
214
+ const [notes, setNotes] = useState({});
215
+
216
+ const refresh = useCallback(async () => {
217
+ const [s, w] = await Promise.all([api.summary(), api.worklist()]);
218
+ setSummary(s); setItems(w.items || []);
219
+ if (s && typeof s.tau === "number") setTau(s.tau);
220
+ }, []);
221
+ useEffect(() => { refresh(); }, [refresh]);
222
+
223
+ const applyTau = async (v) => { setTau(v); const s = await api.settings({tau:v});
224
+ if (s.summary) setSummary(s.summary); const w = await api.worklist(); setItems(w.items||[]); };
225
+ const decide = async (id, a) => { await api.decision({case_id:id, action:a, note:notes[id]||""}); refresh(); };
226
+
227
+ if (!summary) return <div className="empty">Loading patch QA…</div>;
228
+ const pending = items.filter(i => !i.decision);
229
+
230
+ return <>
231
+ <div className="cards">
232
+ <Card k="Cases reviewed" v={summary.n_cases} />
233
+ <Card k="Disagreements" v={summary.n_disagreements} sub={"· " + pct(summary.disagreement_rate)} />
234
+ <Card k="Flagged for re-check" v={summary.n_flagged} sub={"· " + pct(summary.flag_rate)} />
235
+ <Card k="Resolved" v={summary.resolved + " / " + summary.n_flagged} />
236
+ </div>
237
+ <div className="controls">
238
+ <label>Flag confidence threshold (τ)</label>
239
+ <input type="range" min="0.5" max="0.999" step="0.005" value={tau}
240
+ onChange={e=>setTau(parseFloat(e.target.value))}
241
+ onMouseUp={e=>applyTau(parseFloat(e.target.value))}
242
+ onTouchEnd={e=>applyTau(parseFloat(e.target.value))} />
243
+ <span className="mono">τ = {Number(tau).toFixed(3)}</span>
244
+ <span style={{color:"var(--muted)",fontSize:12}}>lower τ → catch more · higher τ → shorter queue</span>
245
+ </div>
246
+ {pending.length === 0
247
+ ? <div className="empty">Nothing left to re-check at this threshold. ✅</div>
248
+ : <table><thead><tr>
249
+ <th>#</th><th>Patch</th><th>Case</th><th>Sign-out</th><th>Model reads</th><th>Confidence</th><th>Re-review outcome</th>
250
+ </tr></thead><tbody>
251
+ {items.map(it => <tr key={it.case_id} className={it.decision?"done":""}>
252
+ <td>{it.priority}</td>
253
+ <td><img className="thumb" src={"/api/patch/"+it.case_id+".png"} onClick={()=>setZoom(it)} alt="patch"/></td>
254
+ <td className="mono">{it.case_id}</td>
255
+ <td><Read v={it.pathologist_read}/></td>
256
+ <td><Read v={it.model_read}/></td>
257
+ <td><div className="confbar"><span style={{width:(100*it.model_confidence)+"%"}}/></div>
258
+ <span className="mono" style={{fontSize:11}}>{it.model_confidence.toFixed(3)}</span></td>
259
+ <td>{it.decision ? <Tag d={it.decision}/> :
260
+ <Actions onConfirm={()=>decide(it.case_id,"confirm_signout")} onAmend={()=>decide(it.case_id,"amend")}
261
+ note={notes[it.case_id]} setNote={v=>setNotes({...notes,[it.case_id]:v})}/>}</td>
262
+ </tr>)}
263
+ </tbody></table>}
264
+ {zoom && <div className="modal" onClick={()=>setZoom(null)}><div className="box" onClick={e=>e.stopPropagation()}>
265
+ <div style={{display:"flex",justifyContent:"space-between",marginBottom:10}}>
266
+ <span className="mono">{zoom.case_id}</span>
267
+ <span style={{cursor:"pointer",color:"var(--muted)"}} onClick={()=>setZoom(null)}>✕</span></div>
268
+ <div style={{display:"flex",gap:10}}>
269
+ <div style={{flex:1,textAlign:"center"}}><img src={"/api/patch/"+zoom.case_id+".png"} alt="patch"/>
270
+ <div style={{fontSize:11,color:"var(--muted)",marginTop:4}}>patch</div></div>
271
+ <div style={{flex:1,textAlign:"center"}}><img src={"/api/patch/"+zoom.case_id+"/cam.png"} alt="grad-cam"/>
272
+ <div style={{fontSize:11,color:"var(--muted)",marginTop:4}}>model attention (Grad-CAM)</div></div>
273
+ </div>
274
+ <p style={{fontSize:13,color:"var(--muted)",marginTop:12}}>{zoom.reason}</p></div></div>}
275
+ </>;
276
+ }
277
+
278
+ function SlidesView() {
279
+ const [summary, setSummary] = useState(null);
280
+ const [items, setItems] = useState([]);
281
+ const [tau, setTau] = useState(0.70);
282
+ const [notes, setNotes] = useState({});
283
+ const [zoom, setZoom] = useState(null);
284
+
285
+ const refresh = useCallback(async () => {
286
+ const [s, w] = await Promise.all([api.slideSummary(), api.slideWorklist()]);
287
+ setSummary(s); setItems(w.items || []);
288
+ if (s && typeof s.slide_tau === "number") setTau(s.slide_tau);
289
+ }, []);
290
+ useEffect(() => { refresh(); }, [refresh]);
291
+
292
+ const applyTau = async (v) => { setTau(v); await api.slideSettings({tau:v}); refresh(); };
293
+ const decide = async (id, a) => { await api.slideDecision({slide_id:id, action:a, note:notes[id]||""}); refresh(); };
294
+
295
+ if (!summary) return <div className="empty">Loading slide QA…</div>;
296
+
297
+ return <>
298
+ <div className="cards" style={{gridTemplateColumns:"repeat(3,1fr)"}}>
299
+ <Card k="Slides reviewed" v={summary.n_slides} />
300
+ <Card k="Flagged for re-review" v={summary.n_flagged} />
301
+ <Card k="Resolved" v={summary.resolved + " / " + summary.n_flagged} />
302
+ </div>
303
+ <div className="controls">
304
+ <label>Slide flag threshold (τ)</label>
305
+ <input type="range" min="0.5" max="0.999" step="0.005" value={tau}
306
+ onChange={e=>setTau(parseFloat(e.target.value))}
307
+ onMouseUp={e=>applyTau(parseFloat(e.target.value))}
308
+ onTouchEnd={e=>applyTau(parseFloat(e.target.value))} />
309
+ <span className="mono">τ = {Number(tau).toFixed(3)}</span>
310
+ <span style={{color:"var(--muted)",fontSize:12}}>heatmap: green = normal, red = suspicious tissue</span>
311
+ </div>
312
+ {items.length === 0
313
+ ? <div className="empty">No slides flagged at this threshold. ✅</div>
314
+ : <div className="slidegrid">
315
+ {items.map(it => <div key={it.slide_id} className={"slidecard" + (it.decision?" done":"")}>
316
+ <img className="heat" src={"/api/slide/"+it.slide_id+"/heatmap.png"} onClick={()=>setZoom(it)} alt="heatmap"/>
317
+ <div className="scbody">
318
+ <div style={{display:"flex",justifyContent:"space-between",alignItems:"center"}}>
319
+ <span className="mono">#{it.priority} · {it.slide_id}</span>
320
+ <span className="mono" style={{fontSize:11,color:"var(--muted)"}}>score {it.slide_score.toFixed(2)}</span>
321
+ </div>
322
+ <div style={{margin:"8px 0",fontSize:13}}>sign-out <Read v={it.pathologist_read}/> &nbsp;vs&nbsp; model <Read v={it.model_read}/></div>
323
+ <div style={{fontSize:12,color:"var(--muted)",marginBottom:10}}>{it.n_tumor_tiles} suspicious / {it.n_tissue_tiles} tissue tiles · conf {it.confidence.toFixed(2)}</div>
324
+ {it.decision ? <Tag d={it.decision}/> :
325
+ <Actions onConfirm={()=>decide(it.slide_id,"confirm_signout")} onAmend={()=>decide(it.slide_id,"amend")}
326
+ note={notes[it.slide_id]} setNote={v=>setNotes({...notes,[it.slide_id]:v})}/>}
327
+ </div>
328
+ </div>)}
329
+ </div>}
330
+ {zoom && <div className="modal" onClick={()=>setZoom(null)}><div className="box" onClick={e=>e.stopPropagation()}>
331
+ <div style={{display:"flex",justifyContent:"space-between",marginBottom:10}}>
332
+ <span className="mono">{zoom.slide_id}</span>
333
+ <span style={{cursor:"pointer",color:"var(--muted)"}} onClick={()=>setZoom(null)}>✕</span></div>
334
+ <img src={"/api/slide/"+zoom.slide_id+"/heatmap.png"} alt="heatmap"/>
335
+ <p style={{fontSize:13,color:"var(--muted)",marginTop:12}}>{zoom.reason}</p></div></div>}
336
+ </>;
337
+ }
338
+
339
+ function ReviewQueue() {
340
+ const [q, setQ] = useState("patches");
341
+ return <>
342
+ <div className="tabs" style={{marginBottom:12}}>
343
+ <button className={"tab"+(q==="patches"?" active":"")} onClick={()=>setQ("patches")}>Patches</button>
344
+ <button className={"tab"+(q==="slides"?" active":"")} onClick={()=>setQ("slides")}>Whole slides</button>
345
+ </div>
346
+ <div style={{fontSize:12,color:"var(--muted)",marginBottom:10}}>Demo review queues: a batch of already signed-out cases; Pathify lists only the ones it disagrees with.</div>
347
+ {q==="patches" ? <PatchesView/> : <SlidesView/>}
348
+ </>;
349
+ }
350
+
351
+ /* =================== Report check (text, client-side) =================== */
352
+ const FIELD = {width:"100%",background:"var(--panel2)",border:"1px solid var(--line)",color:"var(--text)",borderRadius:8,padding:"9px 11px",fontSize:14,fontFamily:"inherit"};
353
+ const EXAMPLE_RPT = "SPECIMEN: Sigmoid colon, biopsy.\nMICROSCOPIC: Irregular cribriform glands with hyperchromatic, pleomorphic nuclei and desmoplastic stroma; foci suggest submucosal invasion.\nIMPRESSION: Findings consistent with invasive adenocarcinoma.";
354
+ function ReportCheck() {
355
+ const [report, setReport] = useState("");
356
+ const [concl, setConcl] = useState(null);
357
+ const [free, setFree] = useState("");
358
+ const [res, setRes] = useState(null);
359
+
360
+ const run = () => { if(!report.trim()){ setRes({error:true}); return; } setRes(classifyReport(report)); };
361
+ const patho = free.trim() ? classifyReport(free).cat : concl;
362
+ const segBtn = (id) => <button key={id} onClick={()=>{setConcl(id); setFree("");}}
363
+ style={{textAlign:"left",border:"1.5px solid "+(concl===id?"var(--accent)":"var(--line)"),
364
+ background:concl===id?"var(--panel2)":"var(--panel)",color:"var(--text)",borderRadius:10,padding:"9px 11px",cursor:"pointer",fontSize:13}}>
365
+ {CATS[id].label}</button>;
366
+
367
+ const verdict = () => {
368
+ if(!res || res.error) return null;
369
+ const a=res.cat;
370
+ if(!patho) return <div className="card" style={{borderLeft:"4px solid #6b7280"}}><b>Read only.</b> Pick or type the pathologist's conclusion to compare.</div>;
371
+ if(a==="uncertain") return <div className="card" style={{borderLeft:"4px solid var(--warn,#f59e0b)"}}><b>Pathify is not sure.</b> Add more report text or confirm with the pathologist.</div>;
372
+ if(a==="nondiag"||patho==="nondiag"){
373
+ const both=a==="nondiag"&&patho==="nondiag";
374
+ return <div className="card" style={{borderLeft:"4px solid "+(both?"var(--ok,#34d399)":"var(--warn,#f59e0b)")}}>
375
+ {both?<><b>Both say non-diagnostic.</b> Request a better sample.</>:<><b>Adequacy mismatch.</b> Confirm sample adequacy with the pathologist.</>}</div>;
376
+ }
377
+ const gap=Math.abs(CATS[a].rank-CATS[patho].rank);
378
+ const col=gap===0?"var(--ok,#34d399)":gap===1?"var(--warn,#f59e0b)":"var(--tumor,#f87171)";
379
+ return <div className="card" style={{borderLeft:"4px solid "+col}}>
380
+ <div style={{marginBottom:6}}>Pathologist {catPill(patho)} &nbsp;vs&nbsp; Pathify {catPill(a)}</div>
381
+ {gap===0 ? <><b>Matches.</b> No discrepancy, safe to proceed.</>
382
+ : gap===1 ? <><b>Borderline difference.</b> Worth a quick confirm with the pathologist.</>
383
+ : <><b>Clear discrepancy, second look needed.</b> Take it back to the pathologist before sign-out. Do not change the read yourself.</>}</div>;
384
+ };
385
+
386
+ return <>
387
+ <Step n="1" title="Paste the pathologist's report">
388
+ <textarea style={{...FIELD,minHeight:130,resize:"vertical"}} value={report}
389
+ onChange={e=>setReport(e.target.value)} placeholder="Paste the report or impression here…"/>
390
+ <button className="btn" style={{marginTop:8}} onClick={()=>setReport(EXAMPLE_RPT)}>Load example</button>
391
+ </Step>
392
+ <Step n="2" title="What did the pathologist conclude?">
393
+ <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(180px,1fr))",gap:8}}>
394
+ {["benign","atypical","dysplasia","malignant","nondiag"].map(segBtn)}
395
+ </div>
396
+ <div style={{fontSize:12,color:"var(--muted)",margin:"10px 0 4px"}}>or type it in their words</div>
397
+ <input style={FIELD} value={free} onChange={e=>{setFree(e.target.value); setConcl(null);}}
398
+ placeholder='e.g. "atypical glandular cells, cannot exclude malignancy"'/>
399
+ {free.trim() && <div style={{fontSize:13,color:"var(--muted)",marginTop:6}}>Pathify reads your text as {catPill(classifyReport(free).cat)}</div>}
400
+ </Step>
401
+ <Step n="3" title="Check">
402
+ <button className="btn primary" onClick={run}>Run report check</button>
403
+ {res && res.error && <span style={{marginLeft:10,color:"var(--warn,#f59e0b)",fontSize:13}}>Paste a report first.</span>}
404
+ </Step>
405
+ {res && !res.error && <>
406
+ <div className="card">
407
+ <div style={{fontSize:15,fontWeight:600,marginBottom:6}}>Pathify's independent read: {catPill(res.cat)} <span style={{fontSize:13,color:"var(--muted)",fontWeight:400}}>· {(100*res.conf).toFixed(0)}%</span></div>
408
+ <div style={{fontSize:12,color:"var(--muted)",marginBottom:6}}>Reading the words in the report (not the tissue). Terms it weighted:</div>
409
+ <div>{res.terms.slice().sort((a,b)=>b.w-a.w).map((t,i)=>{const c=t.side==="mal"?CATS.malignant:t.side==="ben"?CATS.benign:t.side==="nd"?CATS.nondiag:CATS.atypical;
410
+ return <span key={i} style={{background:c.bg,color:c.fg,fontSize:12,padding:"3px 9px",borderRadius:999,margin:"4px 6px 0 0",display:"inline-block"}}>{t.label} +{(+t.w).toFixed(1)}</span>;})}
411
+ {res.terms.length===0 && <span style={{fontSize:12,color:"var(--muted)"}}>No clear diagnostic terms found.</span>}</div>
412
+ </div>
413
+ {verdict()}
414
+ </>}
415
+ </>;
416
+ }
417
+
418
+ /* =================== Model details (live database size) =================== */
419
+ function ModelInfoView() {
420
+ const [mi, setMi] = useState(null);
421
+ const load = useCallback(() => api.modelInfo().then(setMi), []);
422
+ useEffect(() => { load(); const t=setInterval(load, 5000); return ()=>clearInterval(t); }, [load]);
423
+ if (!mi) return <div className="empty">Loading model info…</div>;
424
+ const auroc = mi.metrics && (mi.metrics.test_auroc || mi.metrics.pcam_auroc || mi.metrics.val_auroc);
425
+ const n = (x)=> (x||0).toLocaleString();
426
+ const srcLabel = {trained:"trained model", uploaded:"your loaded model", retrained:"model (learning from submissions)", demo:"demo model"}[mi.source] || mi.source;
427
+ return <>
428
+ <div className="cards">
429
+ <div className="card"><div className="k">Images in the database</div>
430
+ <div className="v" style={{fontSize:26}}>{n(mi.total_images)}</div>
431
+ <div style={{fontSize:12,color:"var(--muted)",marginTop:6}}>grows by 1 with every scan a pathologist submits</div></div>
432
+ <div className="card"><div className="k">Model score (AUROC)</div>
433
+ <div className="v" style={{fontSize:26}}>{auroc? auroc.toFixed(3):"—"}</div>
434
+ <div style={{fontSize:12,color:"var(--muted)",marginTop:6}}>{srcLabel}</div></div>
435
+ </div>
436
+ <div className="card">
437
+ <div className="stitle" style={{fontSize:15,fontWeight:600,marginBottom:8}}>Where the data comes from</div>
438
+ <table style={{width:"100%",fontSize:13}}>
439
+ <tbody>
440
+ <tr><td style={{padding:"6px 0",color:"var(--muted)"}}>Base training data (PathMNIST + PatchCamelyon)</td><td style={{textAlign:"right"}}>{n(mi.base_images)}</td></tr>
441
+ <tr><td style={{padding:"6px 0",color:"var(--muted)"}}>Pathologist contributions (submitted scans)</td><td style={{textAlign:"right"}}>+ {n(mi.contributions)}</td></tr>
442
+ <tr style={{borderTop:"1px solid var(--line)"}}><td style={{padding:"8px 0",fontWeight:600}}>Total</td><td style={{textAlign:"right",fontWeight:600}}>{n(mi.total_images)}</td></tr>
443
+ </tbody>
444
+ </table>
445
+ <div style={{fontSize:12,color:"var(--muted)",marginTop:10}}>
446
+ Every read submitted in <b>Analyze a case</b> is saved and folded into the model, so this number climbs (352,140 → 352,141 → …) and the model keeps improving. Updates automatically every few seconds.
447
+ </div>
448
+ </div>
449
+ </>;
450
+ }
451
+
452
+ /* =================== Shell =================== */
453
+ function App() {
454
+ const [mode, setMode] = useState("analyze");
455
+ const Tab = ({id, label}) => <button className={"tab"+(mode===id?" active":"")} onClick={()=>setMode(id)}>{label}</button>;
456
+ return <div className="wrap">
457
+ <header>
458
+ <h1>Pathify · second-reader QA</h1>
459
+ <div className="sub">An AI safety-net for the pathology sign-out. Quality assurance, not diagnosis.</div>
460
+ </header>
461
+ <div className="banner">
462
+ <b>Assist, not replace.</b> Pathify gives an independent second read and flags anything worth a second look. You decide the outcome; it never changes a sign-out.
463
+ </div>
464
+ <div className="tabs">
465
+ <Tab id="analyze" label="Analyze a case"/>
466
+ <Tab id="report" label="Report check"/>
467
+ <Tab id="review" label="Review queue"/>
468
+ <Tab id="model" label="Model"/>
469
+ </div>
470
+ {mode==="analyze" ? <GuidedFlow/> : mode==="report" ? <ReportCheck/> : mode==="review" ? <ReviewQueue/> : <ModelInfoView/>}
471
+ <div className="foot">
472
+ Every decision is appended to a local audit log (<span className="mono">audit_log.jsonl</span>).
473
+ Data never leaves this machine. Pathify outputs re-check recommendations only; it does not diagnose.
474
+ </div>
475
+ </div>;
476
+ }
477
+
478
+ ReactDOM.createRoot(document.getElementById("root")).render(<App/>);
frontend/index.html ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>Pathify · second-reader QA</title>
7
+ <!--
8
+ React + Babel are loaded from a CDN for convenience. For an AIR-GAPPED / on-prem
9
+ deploy with no internet, run ./frontend/vendor_offline.sh once to download
10
+ react, react-dom and babel into ./frontend/vendor/, then switch the three <script>
11
+ srcs below to ./vendor/... . Nothing else changes.
12
+ -->
13
+ <script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
14
+ <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
15
+ <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
16
+ <style>
17
+ :root{
18
+ --bg:#0f1419; --panel:#161c24; --panel2:#1c242e; --line:#2a343f;
19
+ --text:#e6edf3; --muted:#8b98a5; --accent:#2dd4bf; --accent2:#38bdf8;
20
+ --warn:#f59e0b; --danger:#f87171; --ok:#34d399;
21
+ }
22
+ *{box-sizing:border-box}
23
+ body{margin:0;background:var(--bg);color:var(--text);
24
+ font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;}
25
+ a{color:var(--accent2)}
26
+ .wrap{max-width:1120px;margin:0 auto;padding:24px}
27
+ header h1{margin:0;font-size:20px;letter-spacing:.2px}
28
+ header .sub{color:var(--muted);font-size:13px;margin-top:2px}
29
+ .banner{margin:14px 0 20px;padding:10px 14px;border:1px solid var(--line);
30
+ border-left:3px solid var(--accent);background:var(--panel);border-radius:8px;
31
+ font-size:13px;color:var(--muted)}
32
+ .banner b{color:var(--text)}
33
+ .cards{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:16px}
34
+ .card{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:14px}
35
+ .card .k{color:var(--muted);font-size:12px;text-transform:uppercase;letter-spacing:.4px}
36
+ .card .v{font-size:24px;font-weight:600;margin-top:6px}
37
+ .card .v small{font-size:13px;color:var(--muted);font-weight:400}
38
+ .controls{display:flex;align-items:center;gap:16px;background:var(--panel);
39
+ border:1px solid var(--line);border-radius:10px;padding:14px;margin-bottom:16px;flex-wrap:wrap}
40
+ .controls label{font-size:13px;color:var(--muted)}
41
+ .controls input[type=range]{accent-color:var(--accent);width:220px;vertical-align:middle}
42
+ .pill{font-size:12px;padding:3px 8px;border-radius:999px;border:1px solid var(--line)}
43
+ .pill.tumor{color:#fca5a5;border-color:#5b2b2b;background:#2a1414}
44
+ .pill.normal{color:#a7f3d0;border-color:#1f4d3d;background:#0f241d}
45
+ table{width:100%;border-collapse:collapse;background:var(--panel);
46
+ border:1px solid var(--line);border-radius:10px;overflow:hidden}
47
+ th,td{padding:10px 12px;text-align:left;font-size:13px;border-bottom:1px solid var(--line)}
48
+ th{color:var(--muted);font-weight:500;text-transform:uppercase;font-size:11px;letter-spacing:.5px}
49
+ tr:last-child td{border-bottom:none}
50
+ tr.done{opacity:.5}
51
+ .mono{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px}
52
+ .thumb{width:52px;height:52px;border-radius:6px;border:1px solid var(--line);cursor:pointer;object-fit:cover}
53
+ .confbar{height:6px;background:var(--panel2);border-radius:3px;overflow:hidden;width:90px}
54
+ .confbar>span{display:block;height:100%;background:linear-gradient(90deg,var(--accent),var(--accent2))}
55
+ .btn{font-size:12px;padding:6px 10px;border-radius:7px;border:1px solid var(--line);
56
+ background:var(--panel2);color:var(--text);cursor:pointer}
57
+ .btn:hover{border-color:var(--accent)}
58
+ .btn.amend{border-color:#7a4a12;color:#fcd34d}
59
+ .btn.confirm{border-color:#1f4d3d;color:#a7f3d0}
60
+ .tag{font-size:11px;padding:2px 8px;border-radius:999px}
61
+ .tag.confirm_signout{background:#0f241d;color:#a7f3d0}
62
+ .tag.amend{background:#2a1c0a;color:#fcd34d}
63
+ .empty{padding:40px;text-align:center;color:var(--muted)}
64
+ .modal{position:fixed;inset:0;background:rgba(0,0,0,.6);display:flex;align-items:center;justify-content:center;z-index:20}
65
+ .modal .box{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:20px;max-width:420px;width:90%}
66
+ .modal img{width:100%;image-rendering:pixelated;border-radius:8px;border:1px solid var(--line)}
67
+ .foot{color:var(--muted);font-size:12px;margin-top:22px;line-height:1.6}
68
+ .tabs{display:flex;gap:8px;margin-bottom:16px}
69
+ .tab{background:var(--panel);border:1px solid var(--line);color:var(--muted);
70
+ padding:8px 14px;border-radius:8px;font-size:13px;cursor:pointer}
71
+ .tab.active{color:var(--text);border-color:var(--accent);background:var(--panel2)}
72
+ .slidegrid{display:grid;grid-template-columns:repeat(2,1fr);gap:14px}
73
+ .slidecard{background:var(--panel);border:1px solid var(--line);border-radius:12px;overflow:hidden}
74
+ .slidecard.done{opacity:.55}
75
+ .slidecard .heat{width:100%;display:block;cursor:pointer;image-rendering:pixelated;border-bottom:1px solid var(--line)}
76
+ .scbody{padding:12px 14px}
77
+ </style>
78
+ </head>
79
+ <body>
80
+ <div id="root"></div>
81
+ <script type="text/babel" src="/app.jsx"></script>
82
+ </body>
83
+ </html>
frontend/vendor_offline.sh ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # One-time: pull React + Babel locally so the UI runs with NO internet (air-gapped lab).
3
+ # After running, edit index.html to point the three <script> srcs at ./vendor/... .
4
+ set -e
5
+ cd "$(dirname "$0")"
6
+ mkdir -p vendor
7
+ curl -L -o vendor/react.production.min.js https://unpkg.com/react@18/umd/react.production.min.js
8
+ curl -L -o vendor/react-dom.production.min.js https://unpkg.com/react-dom@18/umd/react-dom.production.min.js
9
+ curl -L -o vendor/babel.min.js https://unpkg.com/@babel/standalone/babel.min.js
10
+ echo "Done. Now change index.html script srcs to ./vendor/react.production.min.js etc."
model.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e6f3af49daa79181a6189b4ca80a09262e3a7fd77d843986ef460c23e01b1467
3
+ size 44782987
pathqa-app ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # PathQA one-command launcher.
3
+ # ./pathqa-app -> start the app and open the browser
4
+ # ./pathqa-app demo -> patch QA demo
5
+ # ./pathqa-app slide-demo -> whole-slide QA demo
6
+ # ./pathqa-app train ... -> train on PatchCamelyon
7
+ # On first run it creates a local venv and installs requirements.
8
+ set -e
9
+ DIR="$(cd "$(dirname "$0")" && pwd)"
10
+ cd "$DIR"
11
+
12
+ PY="${PYTHON:-python3}"
13
+ if [ ! -d ".venv" ]; then
14
+ echo "[PathQA] first run: creating .venv and installing requirements (torch etc.)…"
15
+ "$PY" -m venv .venv
16
+ ./.venv/bin/pip install --upgrade pip >/dev/null
17
+ ./.venv/bin/pip install -r requirements.txt
18
+ fi
19
+
20
+ export PYTHONPATH="$DIR:$DIR/backend:$PYTHONPATH"
21
+ exec ./.venv/bin/python "$DIR/pathqa/cli.py" "${@:-serve}"
pathqa-app.bat ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ REM PathQA one-command launcher (Windows).
3
+ REM pathqa-app.bat start the app and open the browser
4
+ REM pathqa-app.bat demo patch QA demo
5
+ REM pathqa-app.bat slide-demo whole-slide QA demo
6
+ setlocal
7
+ set DIR=%~dp0
8
+ cd /d "%DIR%"
9
+ if not exist ".venv" (
10
+ echo [PathQA] first run: creating .venv and installing requirements...
11
+ python -m venv .venv
12
+ call .venv\Scripts\pip install --upgrade pip
13
+ call .venv\Scripts\pip install -r requirements.txt
14
+ )
15
+ set PYTHONPATH=%DIR%;%DIR%backend;%PYTHONPATH%
16
+ if "%~1"=="" (
17
+ .venv\Scripts\python "%DIR%pathqa\cli.py" serve
18
+ ) else (
19
+ .venv\Scripts\python "%DIR%pathqa\cli.py" %*
20
+ )
21
+ endlocal
pathqa/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ """PathQA — an AI second-reader QA safety-net for pathology labs.
2
+
3
+ Positioned as quality assurance / workflow, NOT diagnosis. The model never
4
+ issues a diagnosis; it flags cases where it confidently disagrees with the
5
+ pathologist so a human can take a second look. The pathologist stays in control.
6
+ """
7
+
8
+ __version__ = "0.1.0"
pathqa/cli.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """PathQA command-line entry point — one command to run everything.
3
+
4
+ pathqa serve # start the local app + open the browser (default)
5
+ pathqa demo [...] # patch-level QA demo (see demo.py --help)
6
+ pathqa slide-demo [...] # whole-slide QA demo (see slide_demo.py --help)
7
+ pathqa train [...] # train on PatchCamelyon (see train_pcam.py --help)
8
+
9
+ `serve` fine-tunes a small demo model on first boot so the UI works out of the
10
+ box; point it at a trained checkpoint with PATHQA_MODEL=model.pt pathqa serve.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ ROOT = Path(__file__).resolve().parent.parent
19
+ BACKEND = ROOT / "backend"
20
+ for p in (str(ROOT), str(BACKEND)):
21
+ if p not in sys.path:
22
+ sys.path.insert(0, p)
23
+
24
+
25
+ def _run_script_main(module_name: str, argv):
26
+ """Call a top-level script's main() with a synthesized argv."""
27
+ sys.argv = [module_name] + list(argv)
28
+ mod = __import__(module_name)
29
+ mod.main()
30
+
31
+
32
+ def main():
33
+ args = sys.argv[1:]
34
+ cmd = args[0] if args else "serve"
35
+ rest = args[1:]
36
+
37
+ if cmd in ("serve", "app", "start"):
38
+ import argparse
39
+ ap = argparse.ArgumentParser(prog="pathqa serve")
40
+ ap.add_argument("--port", type=int, default=8000)
41
+ ap.add_argument("--host", default="127.0.0.1")
42
+ ap.add_argument("--no-open", action="store_true", help="don't open the browser")
43
+ ap.add_argument("--cases", type=int, default=200)
44
+ ap.add_argument("--slides", type=int, default=6)
45
+ ap.add_argument("--slide-grid", type=int, default=14)
46
+ a = ap.parse_args(rest)
47
+ from server import serve
48
+ serve(host=a.host, port=a.port, open_browser=not a.no_open,
49
+ n_cases=a.cases, n_slides=a.slides, slide_grid=a.slide_grid)
50
+ elif cmd == "demo":
51
+ _run_script_main("demo", rest)
52
+ elif cmd in ("slide-demo", "slides"):
53
+ _run_script_main("slide_demo", rest)
54
+ elif cmd == "train":
55
+ _run_script_main("train_pcam", rest)
56
+ elif cmd in ("-h", "--help", "help"):
57
+ print(__doc__)
58
+ else:
59
+ print(f"Unknown command: {cmd}\n")
60
+ print(__doc__)
61
+ sys.exit(1)
62
+
63
+
64
+ if __name__ == "__main__":
65
+ main()
pathqa/data.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Data pipelines.
2
+
3
+ Three sources, one interface:
4
+
5
+ 1. PatchCamelyon (PCam) -> `get_pcam_loaders`
6
+ 96x96 H&E patches from lymph-node sections, binary tumor/normal. Downloaded
7
+ via torchvision. This is the public-data demo.
8
+
9
+ 2. Your own labeled slides -> `get_folder_loaders`
10
+ An ImageFolder layout (train/normal, train/tumor, ...). This is the
11
+ "train-on-your-data" path: the model learns YOUR lab's stain, scanner and
12
+ tissue distribution, which is what fixes domain shift. Nothing leaves disk.
13
+
14
+ 3. Synthetic patches -> `get_synthetic_loaders`
15
+ Deterministic fake H&E-like patches, used only for fast CI / smoke tests so
16
+ the pipeline can be verified without downloading gigabytes.
17
+
18
+ Every loader yields (image_tensor, label) with label 0=normal, 1=tumor and
19
+ normalizes with ImageNet stats (matches the pretrained backbone).
20
+ """
21
+ from __future__ import annotations
22
+
23
+ from pathlib import Path
24
+ from typing import Tuple
25
+
26
+ import torch
27
+ from torch.utils.data import DataLoader, Dataset
28
+ from torchvision import datasets, transforms
29
+
30
+ IMAGENET_MEAN = [0.485, 0.456, 0.406]
31
+ IMAGENET_STD = [0.229, 0.224, 0.225]
32
+ IMG_SIZE = 96 # PCam native patch size
33
+
34
+
35
+ def _train_tfms() -> transforms.Compose:
36
+ # Augmentations safe for histopathology: patches are rotation/flip invariant
37
+ # (no canonical "up"), and mild color jitter approximates stain variation.
38
+ return transforms.Compose([
39
+ transforms.RandomHorizontalFlip(),
40
+ transforms.RandomVerticalFlip(),
41
+ transforms.RandomRotation(20),
42
+ transforms.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.02),
43
+ transforms.ToTensor(),
44
+ transforms.Normalize(IMAGENET_MEAN, IMAGENET_STD),
45
+ ])
46
+
47
+
48
+ def _eval_tfms() -> transforms.Compose:
49
+ return transforms.Compose([
50
+ transforms.ToTensor(),
51
+ transforms.Normalize(IMAGENET_MEAN, IMAGENET_STD),
52
+ ])
53
+
54
+
55
+ # --------------------------------------------------------------------------- #
56
+ # 1. PatchCamelyon (public data)
57
+ # --------------------------------------------------------------------------- #
58
+ def get_pcam_loaders(
59
+ root: str = "./data",
60
+ batch_size: int = 128,
61
+ num_workers: int = 4,
62
+ subset: int | None = None,
63
+ download: bool = True,
64
+ ) -> Tuple[DataLoader, DataLoader, DataLoader]:
65
+ """PatchCamelyon train/val/test loaders.
66
+
67
+ Args:
68
+ subset: if set, use only the first N samples of each split (CPU-friendly
69
+ demo). Full PCam is ~262k/32k/32k patches.
70
+ """
71
+ train = datasets.PCAM(root, split="train", transform=_train_tfms(), download=download)
72
+ val = datasets.PCAM(root, split="val", transform=_eval_tfms(), download=download)
73
+ test = datasets.PCAM(root, split="test", transform=_eval_tfms(), download=download)
74
+
75
+ if subset is not None:
76
+ train = torch.utils.data.Subset(train, range(min(subset, len(train))))
77
+ val = torch.utils.data.Subset(val, range(min(subset // 4 or 1, len(val))))
78
+ test = torch.utils.data.Subset(test, range(min(subset // 4 or 1, len(test))))
79
+
80
+ return (
81
+ DataLoader(train, batch_size=batch_size, shuffle=True, num_workers=num_workers),
82
+ DataLoader(val, batch_size=batch_size, shuffle=False, num_workers=num_workers),
83
+ DataLoader(test, batch_size=batch_size, shuffle=False, num_workers=num_workers),
84
+ )
85
+
86
+
87
+ # --------------------------------------------------------------------------- #
88
+ # 2. Train-on-your-data (ImageFolder)
89
+ # --------------------------------------------------------------------------- #
90
+ def get_folder_loaders(
91
+ root: str,
92
+ batch_size: int = 128,
93
+ num_workers: int = 4,
94
+ ) -> Tuple[DataLoader, DataLoader]:
95
+ """Loaders from a local ImageFolder layout:
96
+
97
+ root/train/normal/*.png
98
+ root/train/tumor/*.png
99
+ root/val/normal/*.png
100
+ root/val/tumor/*.png
101
+
102
+ This keeps all slide data local — the model comes to the data, not the other
103
+ way around.
104
+ """
105
+ root_p = Path(root)
106
+ train = datasets.ImageFolder(root_p / "train", transform=_train_tfms())
107
+ val = datasets.ImageFolder(root_p / "val", transform=_eval_tfms())
108
+ # Enforce the label convention 0=normal, 1=tumor regardless of folder order.
109
+ _assert_class_order(train)
110
+ _assert_class_order(val)
111
+ return (
112
+ DataLoader(train, batch_size=batch_size, shuffle=True, num_workers=num_workers),
113
+ DataLoader(val, batch_size=batch_size, shuffle=False, num_workers=num_workers),
114
+ )
115
+
116
+
117
+ def _assert_class_order(ds: datasets.ImageFolder) -> None:
118
+ expected = {"normal": 0, "tumor": 1}
119
+ if ds.class_to_idx != expected:
120
+ raise ValueError(
121
+ f"Expected class folders 'normal' and 'tumor' mapping to {expected}, "
122
+ f"got {ds.class_to_idx}. Rename folders so labels are unambiguous."
123
+ )
124
+
125
+
126
+ # --------------------------------------------------------------------------- #
127
+ # 3. Synthetic (smoke test only)
128
+ # --------------------------------------------------------------------------- #
129
+ class SyntheticPatches(Dataset):
130
+ """Fake but learnable H&E-ish patches for offline testing.
131
+
132
+ Tumor patches carry slightly more high-frequency purple (hematoxylin-like)
133
+ texture; normal patches are pinker and smoother. A small model can learn
134
+ this in a few steps, which is enough to exercise the whole pipeline.
135
+ """
136
+
137
+ def __init__(self, n: int = 512, seed: int = 0):
138
+ self.n = n
139
+ self.seed = seed
140
+ self.tfms = _eval_tfms()
141
+
142
+ def __len__(self) -> int:
143
+ return self.n
144
+
145
+ def __getitem__(self, idx: int):
146
+ g = torch.Generator().manual_seed(self.seed * 100003 + idx)
147
+ label = int(idx % 2)
148
+ base = torch.rand(3, IMG_SIZE, IMG_SIZE, generator=g)
149
+ if label == 1: # tumor: more blue/purple, more texture
150
+ base[2] = base[2] * 0.6 + 0.4
151
+ noise = torch.rand(3, IMG_SIZE, IMG_SIZE, generator=g) * 0.5
152
+ base = torch.clamp(base + noise - 0.25, 0, 1)
153
+ else: # normal: pinker, smoother
154
+ base[0] = base[0] * 0.6 + 0.4
155
+ base = base * 0.7 + 0.15
156
+ base = (base - torch.tensor(IMAGENET_MEAN).view(3, 1, 1)) / torch.tensor(IMAGENET_STD).view(3, 1, 1)
157
+ return base, label
158
+
159
+
160
+ def get_synthetic_loaders(
161
+ n_train: int = 512, n_eval: int = 256, batch_size: int = 64
162
+ ) -> Tuple[DataLoader, DataLoader, DataLoader]:
163
+ train = SyntheticPatches(n_train, seed=1)
164
+ val = SyntheticPatches(n_eval, seed=2)
165
+ test = SyntheticPatches(n_eval, seed=3)
166
+ return (
167
+ DataLoader(train, batch_size=batch_size, shuffle=True),
168
+ DataLoader(val, batch_size=batch_size, shuffle=False),
169
+ DataLoader(test, batch_size=batch_size, shuffle=False),
170
+ )
pathqa/engine.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Training, evaluation and calibration engine."""
2
+ from __future__ import annotations
3
+
4
+ import math
5
+ from dataclasses import dataclass, field
6
+ from typing import Dict, List, Tuple
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+ from torch.utils.data import DataLoader
12
+
13
+
14
+ @dataclass
15
+ class EvalResult:
16
+ loss: float
17
+ accuracy: float
18
+ auroc: float
19
+ n: int
20
+
21
+
22
+ def _auroc(probs: torch.Tensor, labels: torch.Tensor) -> float:
23
+ """Rank-based AUROC (no sklearn dependency)."""
24
+ labels = labels.long()
25
+ n_pos = int((labels == 1).sum())
26
+ n_neg = int((labels == 0).sum())
27
+ if n_pos == 0 or n_neg == 0:
28
+ return float("nan")
29
+ order = torch.argsort(probs)
30
+ ranks = torch.empty_like(order, dtype=torch.double)
31
+ ranks[order] = torch.arange(1, len(probs) + 1, dtype=torch.double)
32
+ sum_ranks_pos = ranks[labels == 1].sum().item()
33
+ return (sum_ranks_pos - n_pos * (n_pos + 1) / 2) / (n_pos * n_neg)
34
+
35
+
36
+ def train_one_epoch(
37
+ model: nn.Module,
38
+ loader: DataLoader,
39
+ optimizer: torch.optim.Optimizer,
40
+ device: torch.device,
41
+ max_batches: int | None = None,
42
+ ) -> float:
43
+ model.train()
44
+ total, seen = 0.0, 0
45
+ for i, (x, y) in enumerate(loader):
46
+ if max_batches is not None and i >= max_batches:
47
+ break
48
+ x, y = x.to(device), y.to(device)
49
+ optimizer.zero_grad()
50
+ logits = model(x)
51
+ loss = F.cross_entropy(logits, y)
52
+ loss.backward()
53
+ optimizer.step()
54
+ total += loss.item() * x.size(0)
55
+ seen += x.size(0)
56
+ return total / max(seen, 1)
57
+
58
+
59
+ @torch.no_grad()
60
+ def evaluate(
61
+ model: nn.Module,
62
+ loader: DataLoader,
63
+ device: torch.device,
64
+ scaler: nn.Module | None = None,
65
+ max_batches: int | None = None,
66
+ ) -> EvalResult:
67
+ model.eval()
68
+ all_probs: List[torch.Tensor] = []
69
+ all_labels: List[torch.Tensor] = []
70
+ loss_sum, seen = 0.0, 0
71
+ for i, (x, y) in enumerate(loader):
72
+ if max_batches is not None and i >= max_batches:
73
+ break
74
+ x, y = x.to(device), y.to(device)
75
+ logits = model(x)
76
+ if scaler is not None:
77
+ logits = scaler(logits)
78
+ loss_sum += F.cross_entropy(logits, y).item() * x.size(0)
79
+ probs = F.softmax(logits, dim=1)[:, 1] # P(tumor)
80
+ all_probs.append(probs.cpu())
81
+ all_labels.append(y.cpu())
82
+ seen += x.size(0)
83
+ probs = torch.cat(all_probs)
84
+ labels = torch.cat(all_labels)
85
+ preds = (probs >= 0.5).long()
86
+ acc = (preds == labels).float().mean().item()
87
+ return EvalResult(loss_sum / max(seen, 1), acc, _auroc(probs, labels), seen)
88
+
89
+
90
+ @torch.no_grad()
91
+ def _collect_logits(model, loader, device, max_batches=None):
92
+ model.eval()
93
+ logits_all, labels_all = [], []
94
+ for i, (x, y) in enumerate(loader):
95
+ if max_batches is not None and i >= max_batches:
96
+ break
97
+ logits_all.append(model(x.to(device)).cpu())
98
+ labels_all.append(y)
99
+ return torch.cat(logits_all), torch.cat(labels_all)
100
+
101
+
102
+ def fit_temperature(model, val_loader, device, max_batches=None) -> float:
103
+ """Optimize a single temperature on the validation set (LBFGS on NLL).
104
+
105
+ Returns the fitted temperature T (>1 means the raw model was over-confident).
106
+ """
107
+ logits, labels = _collect_logits(model, val_loader, device, max_batches)
108
+ log_t = torch.zeros(1, requires_grad=True) # optimize log T for positivity
109
+ optim = torch.optim.LBFGS([log_t], lr=0.1, max_iter=50)
110
+
111
+ def closure():
112
+ optim.zero_grad()
113
+ loss = F.cross_entropy(logits / log_t.exp(), labels)
114
+ loss.backward()
115
+ return loss
116
+
117
+ optim.step(closure)
118
+ return float(log_t.exp().item())
119
+
120
+
121
+ def expected_calibration_error(probs: torch.Tensor, labels: torch.Tensor, bins: int = 10) -> float:
122
+ """ECE: mean gap between confidence and accuracy across probability bins."""
123
+ conf = torch.maximum(probs, 1 - probs) # confidence of the predicted class
124
+ pred = (probs >= 0.5).long()
125
+ correct = (pred == labels).float()
126
+ edges = torch.linspace(0, 1, bins + 1)
127
+ ece, n = 0.0, len(probs)
128
+ for b in range(bins):
129
+ lo, hi = edges[b], edges[b + 1]
130
+ m = (conf > lo) & (conf <= hi)
131
+ if m.any():
132
+ ece += (m.float().mean() * (correct[m].mean() - conf[m].mean()).abs()).item()
133
+ return ece
pathqa/gradcam.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Grad-CAM explainer.
2
+
3
+ A QA flag is only actionable if the pathologist can see *why* the model
4
+ disagreed. Grad-CAM (Selvaraju et al., 2017) highlights the pixels that drove
5
+ the model's call, so re-review is a glance ("it's reacting to that cluster")
6
+ rather than a hunt. This is explanation, not diagnosis — it never changes a call.
7
+
8
+ Works on the ResNet backbone by hooking the last conv block (`layer4`): grab its
9
+ activations and the gradient of the target-class logit w.r.t. them, weight the
10
+ activation maps by the pooled gradients, ReLU, upsample, and overlay.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import io
15
+ from typing import Optional
16
+
17
+ import torch
18
+ import torch.nn.functional as F
19
+ from PIL import Image
20
+
21
+ from .data import IMAGENET_MEAN, IMAGENET_STD
22
+
23
+ _MEAN = torch.tensor(IMAGENET_MEAN).view(3, 1, 1)
24
+ _STD = torch.tensor(IMAGENET_STD).view(3, 1, 1)
25
+
26
+
27
+ class GradCAM:
28
+ """Grad-CAM for a ResNet-style classifier. Target layer defaults to layer4."""
29
+
30
+ def __init__(self, model, target_layer=None, device: Optional[torch.device] = None):
31
+ self.model = model
32
+ self.device = device or torch.device("cpu")
33
+ self.model.to(self.device).eval()
34
+ self.target_layer = target_layer or self.model.layer4
35
+ self._acts = None
36
+ self._grads = None
37
+ self.target_layer.register_forward_hook(self._fwd)
38
+ self.target_layer.register_full_backward_hook(self._bwd)
39
+
40
+ def _fwd(self, module, inp, out):
41
+ self._acts = out.detach()
42
+
43
+ def _bwd(self, module, grad_in, grad_out):
44
+ self._grads = grad_out[0].detach()
45
+
46
+ def cam(self, x: torch.Tensor, target_class: Optional[int] = None) -> torch.Tensor:
47
+ """Return a [H,W] CAM in [0,1] for a single patch tensor x:[3,H,W]."""
48
+ x = x.unsqueeze(0).to(self.device).requires_grad_(True)
49
+ logits = self.model(x)
50
+ if target_class is None:
51
+ target_class = int(logits.argmax(dim=1))
52
+ self.model.zero_grad()
53
+ logits[0, target_class].backward()
54
+
55
+ weights = self._grads.mean(dim=(2, 3), keepdim=True) # GAP over spatial
56
+ cam = F.relu((weights * self._acts).sum(dim=1, keepdim=True))
57
+ cam = F.interpolate(cam, size=x.shape[-2:], mode="bilinear", align_corners=False)
58
+ cam = cam[0, 0]
59
+ cam = (cam - cam.min()) / (cam.max() - cam.min() + 1e-8)
60
+ return cam.cpu()
61
+
62
+
63
+ def _cam_to_rgba(cam: torch.Tensor, alpha: float = 0.5) -> Image.Image:
64
+ """Map CAM [H,W] in [0,1] to a red-hot RGBA overlay (transparent where cold)."""
65
+ h, w = cam.shape
66
+ img = Image.new("RGBA", (w, h))
67
+ px = img.load()
68
+ for y in range(h):
69
+ for x in range(w):
70
+ v = float(cam[y, x])
71
+ r = int(60 + v * 195)
72
+ g = int(60 * (1 - v))
73
+ b = int(80 * (1 - v))
74
+ a = int(alpha * 255 * v) # cold regions stay transparent
75
+ px[x, y] = (r, g, b, a)
76
+ return img
77
+
78
+
79
+ def gradcam_png(model, patch: torch.Tensor, target_class: Optional[int] = None,
80
+ device: Optional[torch.device] = None, upscale: int = 3) -> bytes:
81
+ """Grad-CAM overlay on a patch, returned as PNG bytes."""
82
+ cam = GradCAM(model, device=device).cam(patch, target_class)
83
+ base = ((patch.detach().cpu() * _STD + _MEAN).clamp(0, 1)
84
+ .permute(1, 2, 0).numpy() * 255).astype("uint8")
85
+ base_img = Image.fromarray(base).convert("RGBA")
86
+ overlay = _cam_to_rgba(cam)
87
+ out = Image.alpha_composite(base_img, overlay).convert("RGB")
88
+ if upscale > 1:
89
+ out = out.resize((out.width * upscale, out.height * upscale), Image.NEAREST)
90
+ buf = io.BytesIO(); out.save(buf, format="PNG")
91
+ return buf.getvalue()
pathqa/infer.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Real image inference: run an uploaded image through the trained CNN.
2
+
3
+ This is the genuine "look into the cells" path (not the browser color trick).
4
+ Given any H&E image it:
5
+
6
+ * decides patch vs whole-slide by size,
7
+ * runs the trained classifier with test-time augmentation (TTA) to get both a
8
+ calibrated tumour probability AND an uncertainty estimate (so it can say
9
+ "not sure" instead of guessing),
10
+ * produces a visual: Grad-CAM for a single patch, or a tiled tumour heatmap
11
+ plus the most suspicious tiles for a slide.
12
+
13
+ It never diagnoses; it returns a read + confidence + a picture for a human.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import io
18
+ from typing import Optional
19
+
20
+ import torch
21
+ import torch.nn.functional as F
22
+ from PIL import Image
23
+
24
+ from .data import IMAGENET_MEAN, IMAGENET_STD
25
+ from .gradcam import gradcam_png
26
+ from .slide import SlideScorer, render_heatmap
27
+ from .wsi import SlideTiler
28
+
29
+ _MEAN = torch.tensor(IMAGENET_MEAN).view(3, 1, 1)
30
+ _STD = torch.tensor(IMAGENET_STD).view(3, 1, 1)
31
+ PATCH_SIZE = 96
32
+ SLIDE_MIN = 192 # images at least this big on both sides are tiled as slides
33
+
34
+
35
+ def _to_tensor(img: Image.Image, size: int = PATCH_SIZE) -> torch.Tensor:
36
+ img = img.convert("RGB").resize((size, size))
37
+ arr = torch.frombuffer(bytearray(img.tobytes()), dtype=torch.uint8).float().div(255.0)
38
+ arr = arr.view(size, size, 3).permute(2, 0, 1)
39
+ return (arr - _MEAN) / _STD
40
+
41
+
42
+ @torch.no_grad()
43
+ def _tta_prob(model, scaler, x: torch.Tensor, device) -> tuple[float, float]:
44
+ """Mean tumour prob and its spread across flip/rotate views (uncertainty)."""
45
+ views = [x, torch.flip(x, [2]), torch.flip(x, [1]),
46
+ torch.rot90(x, 1, [1, 2]), torch.rot90(x, 3, [1, 2])]
47
+ batch = torch.stack(views).to(device)
48
+ logits = model(batch)
49
+ if scaler is not None:
50
+ logits = scaler(logits)
51
+ p = F.softmax(logits, dim=1)[:, 1]
52
+ return float(p.mean()), float(p.std())
53
+
54
+
55
+ def _read_from(prob: float, unc: float) -> tuple[str, float, str]:
56
+ """Map probability + uncertainty to a read, confidence and a note."""
57
+ if unc > 0.15 or 0.4 <= prob <= 0.6:
58
+ return ("uncertain", max(0.5, 1 - unc * 2),
59
+ "The model is not confident on this image. Treat as needs-review.")
60
+ if prob >= 0.6:
61
+ return ("tumor", min(0.99, prob), "Model reads tumour-like tissue.")
62
+ return ("normal", min(0.99, 1 - prob), "Model reads benign-like tissue.")
63
+
64
+
65
+ def stain_analysis(img: Image.Image, size: int = 160):
66
+ """Colour/stain method: fraction of tissue that is dense hematoxylin (nuclei),
67
+ plus a red-highlight overlay. Independent of the CNN, so it can corroborate
68
+ or contradict it."""
69
+ im = img.convert("RGB").resize((size, size))
70
+ px = im.load()
71
+ ov = im.copy(); op = ov.load()
72
+ nuclei = tissue = 0
73
+ for y in range(size):
74
+ for x in range(size):
75
+ r, g, b = px[x, y]; br = (r + g + b) / 3
76
+ if br > 245:
77
+ continue
78
+ tissue += 1
79
+ if b > 70 and r > 55 and g < r - 12 and g < b - 12 and br < 175:
80
+ nuclei += 1; op[x, y] = (220, 30, 30)
81
+ frac = nuclei / tissue if tissue else 0.0
82
+ susp = max(0.0, min(1.0, (frac - 0.06) / 0.22))
83
+ buf = io.BytesIO(); ov.save(buf, format="PNG")
84
+ return {"frac": round(frac, 3), "suspicion": round(susp, 3), "overlay_png": buf.getvalue()}
85
+
86
+
87
+ def _combine(model_read: str, model_conf: float, prob: float, susp: float) -> dict:
88
+ """Merge the CNN read and the stain suspicion into one verdict.
89
+
90
+ When the two clearly agree, confidence is boosted. Otherwise (they differ, or
91
+ the model is out of its depth on this image) we return a BLENDED score so the
92
+ verdict still responds to the image instead of collapsing to a flat 50%, and
93
+ we mark it needs-review.
94
+ """
95
+ agree = (model_read == "tumor" and susp >= 0.4) or (model_read == "normal" and susp <= 0.3)
96
+ if agree and model_read != "uncertain":
97
+ return {"read": model_read, "confidence": round(min(0.99, model_conf + 0.05), 3),
98
+ "agree": True, "note": "Trained model and stain check agree."}
99
+ # Weight the stain signal higher here: when the (demo) model is unsure or
100
+ # conflicts, the colour check is the one actually reacting to the image.
101
+ blended = 0.35 * prob + 0.65 * susp
102
+ if blended >= 0.6:
103
+ read, conf = "tumor", round(min(0.9, 0.5 + 0.5 * (blended - 0.5) / 0.5), 3)
104
+ elif blended <= 0.4:
105
+ read, conf = "normal", round(min(0.9, 0.5 + 0.5 * (0.5 - blended) / 0.5), 3)
106
+ else:
107
+ read, conf = "uncertain", 0.5
108
+ why = ("Model unsure on this image, so this is blended with the stain check."
109
+ if model_read == "uncertain"
110
+ else f"Model ({model_read}) and stain differ, showing a blended read.")
111
+ return {"read": read, "confidence": conf, "agree": False,
112
+ "note": why + " Treat as needs-review."}
113
+
114
+
115
+ def analyze_image(model, scaler, img: Image.Image, device=None) -> dict:
116
+ device = device or torch.device("cpu")
117
+ model.to(device).eval()
118
+ w, h = img.size
119
+ stain = stain_analysis(img)
120
+
121
+ # -------- whole-slide (large image): tile + aggregate --------
122
+ if min(w, h) >= SLIDE_MIN:
123
+ tile = max(PATCH_SIZE, min(w, h) // 16)
124
+ tiler = SlideTiler(img, tile_size=tile, model_size=PATCH_SIZE)
125
+ scorer = SlideScorer(model, scaler, device, topk_frac=0.02, min_topk=4)
126
+ sc = scorer.score_slide("upload", tiler)
127
+ read, conf, note = _read_from(sc.slide_score, 0.0)
128
+ tiles = []
129
+ for r in range(len(sc.prob_grid)):
130
+ for c in range(len(sc.prob_grid[r])):
131
+ p = sc.prob_grid[r][c]
132
+ if p >= 0.5:
133
+ tiles.append({"row": r, "col": c, "prob": round(p, 3)})
134
+ tiles.sort(key=lambda t: t["prob"], reverse=True)
135
+ # For the zoom-in, always show the top regions by probability (even if the
136
+ # slide is read as normal), so there is always something to inspect.
137
+ all_tiles = [{"row": r, "col": c, "prob": round(sc.prob_grid[r][c], 3)}
138
+ for r in range(len(sc.prob_grid)) for c in range(len(sc.prob_grid[r]))
139
+ if sc.prob_grid[r][c] >= 0]
140
+ all_tiles.sort(key=lambda t: t["prob"], reverse=True)
141
+ # crop the top regions + Grad-CAM so the UI can zoom in
142
+ previews = []
143
+ for t in all_tiles[:6]:
144
+ box = (t["col"] * tile, t["row"] * tile, (t["col"] + 1) * tile, (t["row"] + 1) * tile)
145
+ crop = img.crop(box)
146
+ xt = _to_tensor(crop, PATCH_SIZE)
147
+ cam = gradcam_png(model, xt, target_class=1, device=device, upscale=2)
148
+ bio = io.BytesIO(); crop.convert("RGB").resize((96, 96)).save(bio, format="PNG")
149
+ previews.append({"row": t["row"], "col": t["col"], "prob": t["prob"],
150
+ "tile_png": bio.getvalue(), "cam_png": cam})
151
+ combined = _combine(read, conf, sc.slide_score, stain["suspicion"])
152
+ return {
153
+ "mode": "slide",
154
+ "model": {"read": read, "prob_tumor": round(sc.slide_score, 3),
155
+ "confidence": round(conf, 3), "uncertainty": None, "note": note,
156
+ "n_tissue_tiles": sc.n_tissue_tiles, "n_tumor_tiles": sc.n_tumor_tiles,
157
+ "top_tiles": tiles[:8]},
158
+ "stain": {"frac": stain["frac"], "suspicion": stain["suspicion"]},
159
+ "combined": combined,
160
+ "tiles": previews,
161
+ "overlay_png": render_heatmap(sc, base_image=img),
162
+ "stain_overlay_png": stain["overlay_png"],
163
+ }
164
+
165
+ # -------- single patch: TTA + Grad-CAM --------
166
+ x = _to_tensor(img, PATCH_SIZE)
167
+ prob, unc = _tta_prob(model, scaler, x, device)
168
+ read, conf, note = _read_from(prob, unc)
169
+ combined = _combine(read, conf, prob, stain["suspicion"])
170
+ return {
171
+ "mode": "patch",
172
+ "model": {"read": read, "prob_tumor": round(prob, 3),
173
+ "confidence": round(conf, 3), "uncertainty": round(unc, 3), "note": note},
174
+ "stain": {"frac": stain["frac"], "suspicion": stain["suspicion"]},
175
+ "combined": combined,
176
+ "overlay_png": gradcam_png(model, x, target_class=1, device=device, upscale=3),
177
+ "stain_overlay_png": stain["overlay_png"],
178
+ }
179
+
180
+
181
+ def load_model_from_checkpoint(path: str, device=None):
182
+ """Load a trained checkpoint (state_dict + backbone + temperature)."""
183
+ from .model import TemperatureScaler, build_model
184
+ device = device or torch.device("cpu")
185
+ ck = torch.load(path, map_location=device)
186
+ model = build_model(ck.get("backbone", "resnet18"), pretrained=False)
187
+ model.load_state_dict(ck["state_dict"])
188
+ scaler = TemperatureScaler(); scaler.set_temperature(float(ck.get("temperature", 1.0)))
189
+ return model.to(device).eval(), scaler
pathqa/model.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Patch classifier model.
2
+
3
+ A small ResNet backbone adapted for binary tumor/normal patch classification.
4
+ Kept intentionally simple and swappable — the QA engine only needs calibrated
5
+ per-patch probabilities, so any backbone that outputs 2 logits works here.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from torchvision import models
12
+
13
+
14
+ def build_model(backbone: str = "resnet18", pretrained: bool = True) -> nn.Module:
15
+ """Build a binary patch classifier.
16
+
17
+ Args:
18
+ backbone: torchvision backbone name (resnet18 / resnet34).
19
+ pretrained: use ImageNet weights. Transfer learning from ImageNet is a
20
+ strong, standard starting point for H&E patch tasks and reduces the
21
+ amount of lab data needed to fine-tune.
22
+ Returns:
23
+ nn.Module producing logits of shape [B, 2] (class 0 = normal, 1 = tumor).
24
+ """
25
+ if backbone == "resnet18":
26
+ weights = models.ResNet18_Weights.IMAGENET1K_V1 if pretrained else None
27
+ net = models.resnet18(weights=weights)
28
+ in_features = net.fc.in_features
29
+ net.fc = nn.Linear(in_features, 2)
30
+ elif backbone == "resnet34":
31
+ weights = models.ResNet34_Weights.IMAGENET1K_V1 if pretrained else None
32
+ net = models.resnet34(weights=weights)
33
+ in_features = net.fc.in_features
34
+ net.fc = nn.Linear(in_features, 2)
35
+ else:
36
+ raise ValueError(f"Unknown backbone: {backbone}")
37
+ return net
38
+
39
+
40
+ class TemperatureScaler(nn.Module):
41
+ """Post-hoc temperature scaling for calibrated probabilities.
42
+
43
+ A QA tool lives or dies on whether "confidence" means what it says. Raw
44
+ softmax from a deep net is usually over-confident; temperature scaling
45
+ (Guo et al., 2017) rescales the logits on a held-out set so that a stated
46
+ 0.9 really behaves like 0.9. Thresholds in the QA engine assume this.
47
+ """
48
+
49
+ def __init__(self) -> None:
50
+ super().__init__()
51
+ self.temperature = nn.Parameter(torch.ones(1) * 1.0)
52
+
53
+ def forward(self, logits: torch.Tensor) -> torch.Tensor:
54
+ # .to(logits.device) so calibration works whether logits are on CPU or GPU
55
+ return logits / self.temperature.to(logits.device)
56
+
57
+ @torch.no_grad()
58
+ def set_temperature(self, value: float) -> None:
59
+ self.temperature.fill_(value)
pathqa/qa.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Second-reader QA engine — the safety net.
2
+
3
+ The design principle: this tool NEVER makes a diagnosis and NEVER auto-changes a
4
+ pathologist's call. It runs silently behind the sign-out, and its only action is
5
+ to raise a hand: "case N — worth a second look, here's why." A human decides.
6
+
7
+ Workflow per case (a patch, or an aggregated slide):
8
+ pathologist_label : the human's read (0 normal / 1 tumor)
9
+ model_prob : calibrated P(tumor) from the classifier
10
+ model_pred : argmax of the model
11
+ agree : model_pred == pathologist_label
12
+ model_confidence : max(model_prob, 1 - model_prob) in [0.5, 1.0]
13
+
14
+ A case is FLAGGED for re-check when the model DISAGREES with the pathologist and
15
+ does so CONFIDENTLY (confidence >= tau). Two ways to set the bar:
16
+
17
+ * fixed threshold `tau` — flag every confident disagreement, or
18
+ * `workload_budget` — flag only the top X% most-confident disagreements,
19
+ so the QA queue fits the time the lab actually has.
20
+
21
+ The output is a prioritized worklist, sorted by model confidence, plus summary
22
+ stats (flag rate, disagreement rate). That is the entire product surface.
23
+ """
24
+ from __future__ import annotations
25
+
26
+ import csv
27
+ import json
28
+ from dataclasses import dataclass, asdict
29
+ from pathlib import Path
30
+ from typing import List, Optional, Sequence
31
+
32
+ import torch
33
+ import torch.nn.functional as F
34
+ from torch.utils.data import DataLoader
35
+
36
+
37
+ @dataclass
38
+ class CaseReview:
39
+ case_id: str
40
+ pathologist_label: int # 0 normal, 1 tumor
41
+ model_pred: int # 0 normal, 1 tumor
42
+ model_prob_tumor: float # calibrated P(tumor)
43
+ model_confidence: float # in [0.5, 1.0]
44
+ agree: bool
45
+ flagged: bool
46
+ reason: str
47
+
48
+ @property
49
+ def pathologist_read(self) -> str:
50
+ return "tumor" if self.pathologist_label == 1 else "normal"
51
+
52
+ @property
53
+ def model_read(self) -> str:
54
+ return "tumor" if self.model_pred == 1 else "normal"
55
+
56
+
57
+ @dataclass
58
+ class QAReport:
59
+ reviews: List[CaseReview]
60
+ tau: float
61
+ n_cases: int
62
+ n_disagreements: int
63
+ n_flagged: int
64
+
65
+ @property
66
+ def disagreement_rate(self) -> float:
67
+ return self.n_disagreements / max(self.n_cases, 1)
68
+
69
+ @property
70
+ def flag_rate(self) -> float:
71
+ return self.n_flagged / max(self.n_cases, 1)
72
+
73
+ @property
74
+ def flagged(self) -> List[CaseReview]:
75
+ return [r for r in self.reviews if r.flagged]
76
+
77
+ def summary(self) -> str:
78
+ return (
79
+ f"PathQA second-reader report\n"
80
+ f" cases reviewed : {self.n_cases}\n"
81
+ f" model/pathologist disagreements: {self.n_disagreements} "
82
+ f"({self.disagreement_rate:.1%})\n"
83
+ f" flagged for re-check : {self.n_flagged} ({self.flag_rate:.1%}) "
84
+ f"at confidence >= {self.tau:.2f}\n"
85
+ f" -> {self.n_cases - self.n_flagged} cases pass QA untouched; "
86
+ f"pathologist reviews only the {self.n_flagged} flagged."
87
+ )
88
+
89
+ def to_json(self, path: str) -> None:
90
+ payload = {
91
+ "tau": self.tau,
92
+ "n_cases": self.n_cases,
93
+ "n_disagreements": self.n_disagreements,
94
+ "n_flagged": self.n_flagged,
95
+ "disagreement_rate": self.disagreement_rate,
96
+ "flag_rate": self.flag_rate,
97
+ "reviews": [asdict(r) for r in self.reviews],
98
+ }
99
+ Path(path).write_text(json.dumps(payload, indent=2))
100
+
101
+ def worklist_to_csv(self, path: str) -> None:
102
+ """Write ONLY the flagged cases, highest confidence first — the queue a
103
+ pathologist actually opens."""
104
+ rows = sorted(self.flagged, key=lambda r: r.model_confidence, reverse=True)
105
+ with open(path, "w", newline="") as f:
106
+ w = csv.writer(f)
107
+ w.writerow(["priority", "case_id", "pathologist_read", "model_read",
108
+ "model_confidence", "reason"])
109
+ for i, r in enumerate(rows, 1):
110
+ w.writerow([i, r.case_id, r.pathologist_read, r.model_read,
111
+ f"{r.model_confidence:.3f}", r.reason])
112
+
113
+
114
+ class SecondReader:
115
+ """Runs a trained, calibrated classifier as a QA second reader."""
116
+
117
+ def __init__(self, model, scaler=None, device: Optional[torch.device] = None):
118
+ self.model = model
119
+ self.scaler = scaler
120
+ self.device = device or torch.device("cpu")
121
+ self.model.to(self.device).eval()
122
+
123
+ @torch.no_grad()
124
+ def _probs(self, x: torch.Tensor) -> torch.Tensor:
125
+ logits = self.model(x.to(self.device))
126
+ if self.scaler is not None:
127
+ logits = self.scaler(logits)
128
+ return F.softmax(logits, dim=1)[:, 1].cpu() # P(tumor)
129
+
130
+ @torch.no_grad()
131
+ def review_loader(
132
+ self,
133
+ loader: DataLoader,
134
+ tau: float = 0.9,
135
+ workload_budget: Optional[float] = None,
136
+ case_ids: Optional[Sequence[str]] = None,
137
+ max_batches: Optional[int] = None,
138
+ ) -> QAReport:
139
+ """Review a labeled set. The loader must yield (image, pathologist_label).
140
+
141
+ Args:
142
+ tau: confidence threshold for flagging a disagreement (ignored if
143
+ workload_budget is set).
144
+ workload_budget: if set (e.g. 0.05), flag only the top 5% of
145
+ disagreements by confidence, and back out the effective tau.
146
+ """
147
+ probs_all, labels_all = [], []
148
+ for i, (x, y) in enumerate(loader):
149
+ if max_batches is not None and i >= max_batches:
150
+ break
151
+ probs_all.append(self._probs(x))
152
+ labels_all.append(y)
153
+ probs = torch.cat(probs_all)
154
+ labels = torch.cat(labels_all).long()
155
+ ids = list(case_ids) if case_ids is not None else [f"case_{i:06d}" for i in range(len(labels))]
156
+ return self._build_report(ids, probs, labels, tau, workload_budget)
157
+
158
+ @staticmethod
159
+ def _build_report(ids, probs, labels, tau, workload_budget) -> QAReport:
160
+ preds = (probs >= 0.5).long()
161
+ confidence = torch.maximum(probs, 1 - probs)
162
+ disagree = preds != labels
163
+
164
+ # If a workload budget is given, set tau to flag only the top-X% most
165
+ # confident disagreements.
166
+ if workload_budget is not None:
167
+ dis_conf = confidence[disagree]
168
+ if len(dis_conf) == 0:
169
+ tau = 1.01 # nothing to flag
170
+ else:
171
+ k = max(1, int(round(workload_budget * len(labels))))
172
+ k = min(k, len(dis_conf))
173
+ tau = float(torch.sort(dis_conf, descending=True).values[k - 1])
174
+
175
+ reviews: List[CaseReview] = []
176
+ for cid, p, lb, pr, cf, dg in zip(
177
+ ids, probs.tolist(), labels.tolist(), preds.tolist(),
178
+ confidence.tolist(), disagree.tolist()
179
+ ):
180
+ flagged = bool(dg and cf >= tau)
181
+ if flagged:
182
+ reason = (
183
+ f"Model reads {'tumor' if pr == 1 else 'normal'} "
184
+ f"(confidence {cf:.2f}) but sign-out is "
185
+ f"{'tumor' if lb == 1 else 'normal'} — recommend re-review."
186
+ )
187
+ elif dg:
188
+ reason = "Model disagrees but below confidence threshold — not flagged."
189
+ else:
190
+ reason = "Model agrees with pathologist."
191
+ reviews.append(CaseReview(
192
+ case_id=cid, pathologist_label=int(lb), model_pred=int(pr),
193
+ model_prob_tumor=float(p), model_confidence=float(cf),
194
+ agree=not bool(dg), flagged=flagged, reason=reason,
195
+ ))
196
+
197
+ return QAReport(
198
+ reviews=reviews,
199
+ tau=float(tau),
200
+ n_cases=len(reviews),
201
+ n_disagreements=int(disagree.sum()),
202
+ n_flagged=sum(r.flagged for r in reviews),
203
+ )
pathqa/slide.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Slide-level scoring, aggregation, QA and heatmap.
2
+
3
+ Pipeline: tile a slide -> score every tissue tile with the patch classifier ->
4
+ aggregate tile scores into ONE slide-level decision -> compare to the
5
+ pathologist's slide sign-out and flag confident disagreements.
6
+
7
+ Aggregation uses **top-K mean pooling**: a slide is called tumor if its most
8
+ suspicious regions are tumor, which matches metastasis detection (one focus is
9
+ enough) far better than averaging over the whole slide (which drowns a small
10
+ tumor in normal tissue).
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import io
15
+ from dataclasses import dataclass, field
16
+ from typing import Dict, List, Optional, Tuple
17
+
18
+ import torch
19
+ import torch.nn.functional as F
20
+ from PIL import Image
21
+
22
+ from .wsi import SlideTiler, Tile
23
+
24
+
25
+ @dataclass
26
+ class SlideScore:
27
+ slide_id: str
28
+ slide_score: float # aggregated P(tumor) for the slide
29
+ model_call: int # 0 normal / 1 tumor
30
+ confidence: float # in [0.5, 1.0]
31
+ n_tissue_tiles: int
32
+ n_tumor_tiles: int # tiles with P(tumor) >= 0.5
33
+ max_tile_prob: float
34
+ topk: int
35
+ grid_shape: Tuple[int, int]
36
+ prob_grid: List[List[float]] = field(default_factory=list) # -1 = background
37
+
38
+ @property
39
+ def model_read(self) -> str:
40
+ return "tumor" if self.model_call == 1 else "normal"
41
+
42
+
43
+ class SlideScorer:
44
+ def __init__(self, model, scaler=None, device: Optional[torch.device] = None,
45
+ topk_frac: float = 0.01, min_topk: int = 5, decision_thresh: float = 0.5):
46
+ self.model = model
47
+ self.scaler = scaler
48
+ self.device = device or torch.device("cpu")
49
+ self.topk_frac = topk_frac
50
+ self.min_topk = min_topk
51
+ self.decision_thresh = decision_thresh
52
+ self.model.to(self.device).eval()
53
+
54
+ @torch.no_grad()
55
+ def _tile_probs(self, tensors: torch.Tensor) -> torch.Tensor:
56
+ logits = self.model(tensors.to(self.device))
57
+ if self.scaler is not None:
58
+ logits = self.scaler(logits)
59
+ return F.softmax(logits, dim=1)[:, 1].cpu()
60
+
61
+ @torch.no_grad()
62
+ def score_slide(self, slide_id: str, tiler: SlideTiler, batch_size: int = 128) -> SlideScore:
63
+ rows, cols = tiler.grid_shape
64
+ prob_grid = [[-1.0] * cols for _ in range(rows)]
65
+ coords: List[Tuple[int, int]] = []
66
+ buf: List[torch.Tensor] = []
67
+ probs: List[float] = []
68
+
69
+ def flush():
70
+ if not buf:
71
+ return
72
+ p = self._tile_probs(torch.stack(buf))
73
+ for (r, c), pv in zip(coords[len(probs):], p.tolist()):
74
+ prob_grid[r][c] = pv
75
+ probs.append(pv)
76
+
77
+ for t in tiler.iter_tiles(skip_background=True):
78
+ buf.append(t.tensor)
79
+ coords.append((t.row, t.col))
80
+ if len(buf) >= batch_size:
81
+ flush(); buf = []
82
+ flush()
83
+
84
+ if not probs:
85
+ return SlideScore(slide_id, 0.0, 0, 1.0, 0, 0, 0.0, 0, (rows, cols), prob_grid)
86
+
87
+ pt = torch.tensor(probs)
88
+ k = max(self.min_topk, int(self.topk_frac * len(pt)))
89
+ k = min(k, len(pt))
90
+ slide_score = float(torch.topk(pt, k).values.mean())
91
+ call = int(slide_score >= self.decision_thresh)
92
+ conf = max(slide_score, 1 - slide_score)
93
+ return SlideScore(
94
+ slide_id=slide_id, slide_score=slide_score, model_call=call,
95
+ confidence=conf, n_tissue_tiles=len(pt),
96
+ n_tumor_tiles=int((pt >= 0.5).sum()), max_tile_prob=float(pt.max()),
97
+ topk=k, grid_shape=(rows, cols), prob_grid=prob_grid,
98
+ )
99
+
100
+
101
+ # --------------------------------------------------------------------------- #
102
+ # Slide-level QA second reader
103
+ # --------------------------------------------------------------------------- #
104
+ @dataclass
105
+ class SlideReview:
106
+ slide_id: str
107
+ pathologist_label: int
108
+ model_call: int
109
+ slide_score: float
110
+ confidence: float
111
+ n_tumor_tiles: int
112
+ flagged: bool
113
+ reason: str
114
+
115
+ @property
116
+ def pathologist_read(self) -> str:
117
+ return "tumor" if self.pathologist_label == 1 else "normal"
118
+
119
+ @property
120
+ def model_read(self) -> str:
121
+ return "tumor" if self.model_call == 1 else "normal"
122
+
123
+
124
+ def review_slides(scores: Dict[str, SlideScore], labels: Dict[str, int],
125
+ tau: float = 0.9) -> List[SlideReview]:
126
+ """Flag slides where the model confidently disagrees with the sign-out."""
127
+ out: List[SlideReview] = []
128
+ for sid, sc in scores.items():
129
+ lb = labels[sid]
130
+ disagree = sc.model_call != lb
131
+ flagged = bool(disagree and sc.confidence >= tau)
132
+ if flagged:
133
+ reason = (f"Model reads {sc.model_read} (slide score {sc.slide_score:.2f}, "
134
+ f"{sc.n_tumor_tiles} suspicious tiles) but sign-out is "
135
+ f"{'tumor' if lb == 1 else 'normal'} — recommend re-review.")
136
+ elif disagree:
137
+ reason = "Model disagrees but below confidence threshold — not flagged."
138
+ else:
139
+ reason = "Model agrees with pathologist."
140
+ out.append(SlideReview(sid, int(lb), sc.model_call, sc.slide_score,
141
+ sc.confidence, sc.n_tumor_tiles, flagged, reason))
142
+ return out
143
+
144
+
145
+ # --------------------------------------------------------------------------- #
146
+ # Heatmap
147
+ # --------------------------------------------------------------------------- #
148
+ def _prob_to_rgb(p: float) -> Tuple[int, int, int]:
149
+ """green (normal) -> amber -> red (tumor)."""
150
+ if p < 0:
151
+ return (0, 0, 0) # background, will be transparent
152
+ if p < 0.5:
153
+ t = p / 0.5
154
+ return (int(29 + t * (245 - 29)), int(158 + t * (199 - 158)), int(117 - t * 117 + t * 39))
155
+ t = (p - 0.5) / 0.5
156
+ return (int(245 - t * (245 - 226)), int(199 - t * 199 + t * 75), int(39 - t * 39 + t * 75))
157
+
158
+
159
+ def render_heatmap(score: SlideScore, base_image: Optional[Image.Image] = None,
160
+ cell: int = 24, alpha: float = 0.55) -> bytes:
161
+ """Render the tumor-probability grid as a PNG. If a base thumbnail is given,
162
+ overlay the heatmap on it; otherwise draw the grid alone."""
163
+ rows, cols = score.grid_shape
164
+ heat = Image.new("RGBA", (cols * cell, rows * cell), (0, 0, 0, 0))
165
+ px = heat.load()
166
+ for r in range(rows):
167
+ for c in range(cols):
168
+ p = score.prob_grid[r][c] if r < len(score.prob_grid) else -1
169
+ col = _prob_to_rgb(p)
170
+ a = 0 if p < 0 else int(alpha * 255)
171
+ for y in range(r * cell, (r + 1) * cell):
172
+ for x in range(c * cell, (c + 1) * cell):
173
+ px[x, y] = (col[0], col[1], col[2], a)
174
+ if base_image is not None:
175
+ base = base_image.convert("RGBA").resize((cols * cell, rows * cell))
176
+ out = Image.alpha_composite(base, heat)
177
+ else:
178
+ bg = Image.new("RGBA", heat.size, (20, 24, 30, 255))
179
+ out = Image.alpha_composite(bg, heat)
180
+ buf = io.BytesIO(); out.convert("RGB").save(buf, format="PNG")
181
+ return buf.getvalue()
pathqa/wsi.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Whole-slide tiling + tissue detection.
2
+
3
+ A sign-out is per-slide, not per-patch, so the QA layer has to work on slides.
4
+ This module turns a slide into a grid of tiles, throws away the background
5
+ (glass) tiles so we only score real tissue, and yields tiles ready for the
6
+ classifier.
7
+
8
+ Three slide sources behind one interface (`iter_tiles` returns tiles + grid
9
+ coords + a tissue mask):
10
+
11
+ 1. A large ordinary image (PNG/JPG/TIFF) openable by PIL — good enough for a
12
+ downsampled slide or an exported region.
13
+ 2. An OpenSlide-readable WSI (.svs/.ndpi/...) — used only if `openslide` is
14
+ installed; imported lazily so it's an optional dependency.
15
+ 3. A synthetic slide (`SyntheticSlide`) — a grid of H&E-like tiles with an
16
+ optional embedded tumor region, for the demo and tests.
17
+
18
+ Tissue detection is the standard cheap trick: tiles with enough colour
19
+ saturation (stained tissue) and not too bright (not glass) are kept.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ from dataclasses import dataclass
24
+ from typing import Iterator, List, Optional, Tuple
25
+
26
+ import torch
27
+ from PIL import Image
28
+
29
+ from .data import IMAGENET_MEAN, IMAGENET_STD
30
+
31
+ _MEAN = torch.tensor(IMAGENET_MEAN).view(3, 1, 1)
32
+ _STD = torch.tensor(IMAGENET_STD).view(3, 1, 1)
33
+
34
+
35
+ @dataclass
36
+ class Tile:
37
+ row: int
38
+ col: int
39
+ tensor: torch.Tensor # normalized CHW, ready for the model
40
+ is_tissue: bool
41
+
42
+
43
+ def _to_tensor(img: Image.Image, size: int) -> torch.Tensor:
44
+ img = img.convert("RGB").resize((size, size))
45
+ arr = torch.frombuffer(bytearray(img.tobytes()), dtype=torch.uint8).float().div(255.0)
46
+ arr = arr.view(size, size, 3).permute(2, 0, 1)
47
+ return (arr - _MEAN) / _STD
48
+
49
+
50
+ def is_tissue(img: Image.Image, sat_thresh: float = 0.10, bright_thresh: float = 0.92) -> bool:
51
+ """Keep tiles that look like stained tissue, drop glass/background."""
52
+ hsv = img.convert("HSV")
53
+ px = torch.frombuffer(bytearray(hsv.tobytes()), dtype=torch.uint8).float().div(255.0)
54
+ px = px.view(-1, 3)
55
+ mean_sat = px[:, 1].mean().item()
56
+ mean_val = px[:, 2].mean().item()
57
+ return mean_sat > sat_thresh and mean_val < bright_thresh
58
+
59
+
60
+ class SlideTiler:
61
+ """Tile a PIL-openable image (or a synthetic slide) into fixed tiles."""
62
+
63
+ def __init__(self, image: Image.Image, tile_size: int = 96, model_size: int = 96):
64
+ self.image = image.convert("RGB")
65
+ self.tile_size = tile_size
66
+ self.model_size = model_size
67
+ self.W, self.H = self.image.size
68
+ self.n_cols = self.W // tile_size
69
+ self.n_rows = self.H // tile_size
70
+
71
+ @property
72
+ def grid_shape(self) -> Tuple[int, int]:
73
+ return (self.n_rows, self.n_cols)
74
+
75
+ def iter_tiles(self, skip_background: bool = True) -> Iterator[Tile]:
76
+ for r in range(self.n_rows):
77
+ for c in range(self.n_cols):
78
+ box = (c * self.tile_size, r * self.tile_size,
79
+ (c + 1) * self.tile_size, (r + 1) * self.tile_size)
80
+ crop = self.image.crop(box)
81
+ tissue = is_tissue(crop)
82
+ if skip_background and not tissue:
83
+ continue
84
+ yield Tile(r, c, _to_tensor(crop, self.model_size), tissue)
85
+
86
+
87
+ def open_slide_image(path: str, level_downsample: int = 1) -> Image.Image:
88
+ """Open a slide as a PIL image. Uses OpenSlide for true WSI formats if
89
+ available, otherwise falls back to PIL (large images / exported regions)."""
90
+ lower = path.lower()
91
+ if lower.endswith((".svs", ".ndpi", ".mrxs", ".tif", ".tiff")):
92
+ try:
93
+ import openslide # optional, lazy
94
+ slide = openslide.OpenSlide(path)
95
+ level = min(level_downsample, slide.level_count - 1)
96
+ region = slide.read_region((0, 0), level, slide.level_dimensions[level])
97
+ return region.convert("RGB")
98
+ except ImportError:
99
+ pass # fall back to PIL for .tif/.tiff
100
+ Image.MAX_IMAGE_PIXELS = None
101
+ return Image.open(path).convert("RGB")
102
+
103
+
104
+ class SyntheticSlide:
105
+ """A synthetic H&E slide: a grid of tiles, optionally with a tumor blob.
106
+
107
+ Used for the demo/tests so the whole-slide pipeline can be exercised without
108
+ a real (huge, private) WSI. Returns a PIL image the SlideTiler can consume.
109
+ """
110
+
111
+ def __init__(self, grid: int = 16, tile: int = 96, tumor: bool = False,
112
+ tumor_frac: float = 0.12, seed: int = 0):
113
+ self.grid, self.tile = grid, tile
114
+ self.tumor = tumor
115
+ self.tumor_frac = tumor_frac
116
+ self.seed = seed
117
+ self.tumor_cells = set()
118
+ self._img = self._render()
119
+
120
+ def _render(self) -> Image.Image:
121
+ from .data import SyntheticPatches
122
+ g = torch.Generator().manual_seed(self.seed)
123
+ n = self.grid
124
+ canvas = Image.new("RGB", (n * self.tile, n * self.tile), (245, 240, 243))
125
+
126
+ # choose a contiguous-ish tumor region
127
+ if self.tumor:
128
+ k = max(1, int(self.tumor_frac * n * n))
129
+ cr = int(torch.randint(1, n - 1, (1,), generator=g))
130
+ cc = int(torch.randint(1, n - 1, (1,), generator=g))
131
+ cells = [(cr, cc)]
132
+ while len(cells) < k:
133
+ br, bc = cells[int(torch.randint(0, len(cells), (1,), generator=g))]
134
+ dr = int(torch.randint(-1, 2, (1,), generator=g))
135
+ dc = int(torch.randint(-1, 2, (1,), generator=g))
136
+ nr, nc = min(max(br + dr, 0), n - 1), min(max(bc + dc, 0), n - 1)
137
+ cells.append((nr, nc))
138
+ self.tumor_cells = set(cells)
139
+
140
+ # a rough tissue oval so background tiles exist and get filtered
141
+ for r in range(n):
142
+ for c in range(n):
143
+ dist = ((r - n / 2) / (n / 2)) ** 2 + ((c - n / 2) / (n / 2)) ** 2
144
+ if dist > 1.05:
145
+ continue # leave as background glass
146
+ is_tum = (r, c) in self.tumor_cells
147
+ patch = SyntheticPatches(n=2, seed=self.seed * 131 + r * n + c)[1 if is_tum else 0][0]
148
+ img = (patch * _STD + _MEAN).clamp(0, 1)
149
+ arr = (img.permute(1, 2, 0).numpy() * 255).astype("uint8")
150
+ canvas.paste(Image.fromarray(arr).resize((self.tile, self.tile)),
151
+ (c * self.tile, r * self.tile))
152
+ return canvas
153
+
154
+ def image(self) -> Image.Image:
155
+ return self._img
pathqa_check.html ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8"/>
5
+ <meta name="viewport" content="width=device-width, initial-scale=1"/>
6
+ <title>Pathify re-verify</title>
7
+ <style>
8
+ :root{ color-scheme: light;
9
+ --bg:#f7f8fa; --card:#ffffff; --text:#111827; --muted:#6b7280; --line:#e5e7eb;
10
+ --accent:#0f766e; --accentbg:#e6f4f1;
11
+ --tumor:#b91c1c; --tumorbg:#fee2e2; --normal:#047857; --normalbg:#d1fae5;
12
+ --warn:#b45309; --warnbg:#fef3c7;
13
+ }
14
+ *{box-sizing:border-box}
15
+ body{margin:0;background:var(--bg);color:var(--text);
16
+ font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;line-height:1.5}
17
+ .wrap{max-width:760px;margin:0 auto;padding:22px 18px 44px}
18
+ h1{font-size:20px;margin:0}
19
+ .sub{color:var(--muted);font-size:13px;margin-top:4px}
20
+ .chip{display:inline-block;font-size:11px;padding:3px 9px;border-radius:999px;background:var(--accentbg);color:var(--accent);margin-top:8px}
21
+ .story{background:#eef6f4;border:1px solid #cfe7e1;border-radius:12px;padding:12px 14px;margin-top:14px;font-size:13px;color:#0f5f57}
22
+ .story b{color:#0b463f}
23
+ .scope{margin-top:12px;background:var(--card);border:1px solid var(--line);border-radius:12px;padding:12px 14px}
24
+ .scope summary{cursor:pointer;font-size:14px;font-weight:600;color:var(--accent)}
25
+ .scope .scopebody{margin-top:8px}
26
+ .scope p{font-size:13px;margin:8px 0 0}
27
+ .card{background:var(--card);border:1px solid var(--line);border-radius:14px;padding:18px;margin-top:16px}
28
+ .step{display:flex;gap:10px;align-items:flex-start}
29
+ .num{flex:none;width:26px;height:26px;border-radius:50%;background:var(--accent);color:#fff;font-size:13px;font-weight:600;display:flex;align-items:center;justify-content:center;margin-top:1px}
30
+ .stitle{font-size:15px;font-weight:600}
31
+ .hint{font-size:12.5px;color:var(--muted);margin:2px 0 10px}
32
+ textarea,input[type=text]{width:100%;border:1px solid var(--line);border-radius:10px;padding:10px 12px;font-size:14px;font-family:inherit;background:#fff;color:var(--text)}
33
+ textarea#report{min-height:150px;resize:vertical}
34
+ .row{display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin-top:10px}
35
+ .btn{font-size:14px;padding:10px 16px;border-radius:10px;border:1px solid var(--line);background:#fff;color:var(--text);cursor:pointer}
36
+ .btn:hover{border-color:var(--accent)}
37
+ .btn.primary{background:var(--accent);border-color:var(--accent);color:#fff;font-weight:600;font-size:15px;padding:12px 20px}
38
+ .btn.primary:disabled{opacity:.5;cursor:default}
39
+ .btn.link{border:none;background:none;color:var(--accent);padding:4px 2px;cursor:pointer;font-size:13px}
40
+ input[type=file]{font-size:13px}
41
+ .seg{display:grid;grid-template-columns:repeat(2,1fr);gap:8px}
42
+ .seg button{border:1.5px solid var(--line);background:#fff;border-radius:10px;padding:11px 12px;cursor:pointer;text-align:left}
43
+ .seg button .t{font-weight:600;font-size:14px} .seg button .d{font-size:12px;color:var(--muted)}
44
+ .seg button.on{border-color:var(--accent);background:var(--accentbg)}
45
+ .seg button.on.tumor{border-color:var(--tumor);background:var(--tumorbg)}
46
+ .seg button.on.normal{border-color:var(--normal);background:var(--normalbg)}
47
+ .seg button.on.warn{border-color:var(--warn);background:var(--warnbg)}
48
+ .orline{display:flex;align-items:center;gap:10px;color:var(--muted);font-size:12px;margin:14px 0}
49
+ .orline::before,.orline::after{content:"";height:1px;background:var(--line);flex:1}
50
+ .detected{font-size:13px;margin-top:6px;color:var(--muted);min-height:20px}
51
+ .pill{display:inline-block;font-size:13px;font-weight:600;padding:4px 12px;border-radius:999px}
52
+ .pill.tumor{background:var(--tumorbg);color:var(--tumor)}
53
+ .pill.normal{background:var(--normalbg);color:var(--normal)}
54
+ .pill.warn{background:var(--warnbg);color:var(--warn)}
55
+ .pill.uncertain{background:#f3f4f6;color:#4b5563}
56
+ .confbar{height:9px;background:#eef0f2;border-radius:5px;overflow:hidden;max-width:280px;margin-top:5px}
57
+ .confbar>span{display:block;height:100%;width:0;background:var(--accent);transition:width .6s ease}
58
+ .why{margin-top:12px;border-top:1px solid var(--line);padding-top:10px}
59
+ .why summary{cursor:pointer;font-size:13px;color:var(--accent);font-weight:600}
60
+ .term{display:inline-block;font-size:12px;padding:3px 9px;border-radius:999px;margin:4px 6px 0 0}
61
+ .term.mal{background:var(--tumorbg);color:var(--tumor)} .term.ben{background:var(--normalbg);color:var(--normal)}
62
+ .term.warn{background:var(--warnbg);color:var(--warn)} .term.nd{background:#f3f4f6;color:#4b5563}
63
+ .verdict{border-radius:14px;padding:18px;margin-top:16px;border:1.5px solid}
64
+ .verdict.ok{background:var(--normalbg);border-color:#a7f3d0}
65
+ .verdict.flag{background:var(--tumorbg);border-color:#fca5a5}
66
+ .verdict.soft{background:var(--warnbg);border-color:#f59e0b}
67
+ .verdict.info{background:#eef2ff;border-color:#c7d2fe}
68
+ .verdict h3{margin:0 0 6px;font-size:17px}
69
+ .verdict.ok h3{color:var(--normal)} .verdict.flag h3{color:var(--tumor)} .verdict.soft h3{color:var(--warn)} .verdict.info h3{color:#4338ca}
70
+ .action{margin-top:10px;font-size:14px;font-weight:600}
71
+ .imgs{display:flex;gap:14px;flex-wrap:wrap;margin-top:12px}
72
+ .imgs figure{margin:0;text-align:center}
73
+ .imgs img{width:150px;height:150px;object-fit:cover;border:1px solid var(--line);border-radius:10px;display:block}
74
+ figcaption{font-size:11px;color:var(--muted);margin-top:4px}
75
+ .foot{color:var(--muted);font-size:12px;margin-top:22px;line-height:1.6}
76
+ .muted{color:var(--muted)}
77
+ .spinner{display:inline-block;width:14px;height:14px;border:2px solid #cbd5e1;border-top-color:var(--accent);border-radius:50%;animation:spin .7s linear infinite;vertical-align:-2px;margin-right:6px}
78
+ @keyframes spin{to{transform:rotate(360deg)}}
79
+ </style>
80
+ </head>
81
+ <body>
82
+ <div class="wrap">
83
+ <h1>Pathify · re-verify a read</h1>
84
+ <div class="sub">A fast second-reader check for trainees and interns. It tells you whether a pathologist's read holds up, or whether the case is worth a second look. This is a QA aid, not a diagnosis.</div>
85
+ <div class="chip">Assist, not replace</div>
86
+
87
+ <div class="story"><b>How this fits your day:</b> the pathologist hands you their written read. You paste it here, tell Pathify what they concluded, and it independently re-checks the wording. If the two agree, you are done. If they differ, you take it back to the pathologist for a second look.</div>
88
+
89
+ <details class="scope">
90
+ <summary>What can Pathify analyze?</summary>
91
+ <div class="scopebody">
92
+ <p><b>Best for:</b> free-text histopathology and surgical pathology reports, the microscopic description and the impression/diagnosis line, across common specimens (colon, breast, skin, prostate, cervix, lymph node, and similar). It sorts the conclusion into one of five buckets: benign/negative, atypical/suspicious, dysplasia/pre-malignant, malignant/carcinoma, or non-diagnostic/insufficient. You can also add an H&amp;E slide image for an optional stain-density check.</p>
93
+ <p class="muted"><b>Not built for (yet):</b> numeric lab panels, radiology reports, molecular/genetic reports, and cytology grading scales. On text, Pathify checks diagnostic wording in English, so it is a wording-consistency check, not a tissue judgment. Unusual phrasing can trip it up.</p>
94
+ </div>
95
+ </details>
96
+
97
+ <div class="card">
98
+ <div class="step"><div class="num">1</div><div style="flex:1">
99
+ <div class="stitle">Paste the pathologist's statement</div>
100
+ <div class="hint">Paste the report or the written impression. You can also upload a .txt file.</div>
101
+ <textarea id="report" placeholder="Paste the pathologist's report or impression here..."></textarea>
102
+ <div class="row">
103
+ <input type="file" id="reportFile" accept=".txt,text/plain">
104
+ <button class="btn link" id="example">Load example statement</button>
105
+ </div>
106
+ <div style="margin-top:14px" class="stitle">Add an H&amp;E image <span class="muted" style="font-weight:400;font-size:13px">(optional)</span></div>
107
+ <div class="hint">If you have the slide image, Pathify adds a stain density check with a highlight overlay.</div>
108
+ <input type="file" id="imgFile" accept="image/*">
109
+ </div></div>
110
+ </div>
111
+
112
+ <div class="card">
113
+ <div class="step"><div class="num">2</div><div style="flex:1">
114
+ <div class="stitle">What did the pathologist conclude?</div>
115
+ <div class="hint">Tap the closest category, so Pathify can compare its read to theirs.</div>
116
+ <div class="seg" id="seg">
117
+ <button data-v="benign"><div class="t">Benign / negative</div><div class="d">no tumour</div></button>
118
+ <button data-v="atypical"><div class="t">Atypical / suspicious</div><div class="d">not sure, worrying features</div></button>
119
+ <button data-v="dysplasia"><div class="t">Dysplasia / pre-malignant</div><div class="d">abnormal, not yet cancer</div></button>
120
+ <button data-v="malignant"><div class="t">Malignant / carcinoma</div><div class="d">cancer present</div></button>
121
+ <button data-v="nondiag"><div class="t">Non-diagnostic / insufficient</div><div class="d">sample not adequate</div></button>
122
+ <button data-v="unknown"><div class="t">Not stated</div><div class="d">just want Pathify's read</div></button>
123
+ </div>
124
+ <div class="orline">or type it in their words</div>
125
+ <input type="text" id="free" placeholder='e.g. "atypical glandular cells, cannot exclude malignancy"'>
126
+ <div class="detected" id="detected"></div>
127
+ </div></div>
128
+ </div>
129
+
130
+ <div class="card">
131
+ <div class="step"><div class="num">3</div><div style="flex:1">
132
+ <div class="stitle">Re-verify</div>
133
+ <div class="hint">Pathify reads the statement on its own, then compares.</div>
134
+ <div class="row">
135
+ <button class="btn primary" id="run">Re-verify this case</button>
136
+ <button class="btn" id="reset" style="display:none">Check another case</button>
137
+ <span id="status" class="muted" style="font-size:13px"></span>
138
+ </div>
139
+ </div></div>
140
+ </div>
141
+
142
+ <div id="result"></div>
143
+
144
+ <div class="foot">Pathify only gives a re-check recommendation. It never changes a read and never makes a diagnosis. When in doubt, the pathologist decides. Everything runs on this device.</div>
145
+ </div>
146
+
147
+ <script>
148
+ "use strict";
149
+ const $=id=>document.getElementById(id);
150
+ let selected=null, imgData=null;
151
+
152
+ const CATS={
153
+ benign:{label:"benign / negative", cls:"normal", rank:0},
154
+ atypical:{label:"atypical / suspicious", cls:"warn", rank:1},
155
+ dysplasia:{label:"dysplasia / pre-malignant", cls:"warn", rank:2},
156
+ malignant:{label:"malignant / carcinoma", cls:"tumor", rank:3},
157
+ nondiag:{label:"non-diagnostic / insufficient", cls:"uncertain", rank:null},
158
+ uncertain:{label:"uncertain", cls:"uncertain", rank:null}
159
+ };
160
+ const pill=c=>`<span class="pill ${(CATS[c]||CATS.uncertain).cls}">${(CATS[c]||CATS.uncertain).label}</span>`;
161
+
162
+ const EXAMPLE=`SPECIMEN: Sigmoid colon, endoscopic biopsy.
163
+ MICROSCOPIC: Sections show colonic mucosa with irregular, back to back and cribriform glands lined by cells with enlarged, hyperchromatic, pleomorphic nuclei and frequent mitoses. There is loss of normal crypt architecture with desmoplastic stroma. Foci suggest infiltration into the submucosa.
164
+ IMPRESSION: Findings consistent with a moderately differentiated invasive adenocarcinoma.`;
165
+ $("example").onclick=()=>{ $("report").value=EXAMPLE; };
166
+ $("reportFile").onchange=e=>{const f=e.target.files[0]; if(!f)return; const r=new FileReader(); r.onload=()=>{$("report").value=r.result;}; r.readAsText(f);};
167
+
168
+ document.querySelectorAll("#seg button").forEach(b=>{ b.onclick=()=>{
169
+ selected=b.dataset.v; $("free").value=""; $("detected").textContent="";
170
+ document.querySelectorAll("#seg button").forEach(x=>x.className="");
171
+ b.className="on "+((CATS[selected]||{}).cls||"");
172
+ };});
173
+ $("free").oninput=()=>{
174
+ const v=$("free").value.trim();
175
+ document.querySelectorAll("#seg button").forEach(x=>x.className=""); selected=null;
176
+ if(!v){$("detected").textContent="";return;}
177
+ const c=classify(v).cat;
178
+ $("detected").innerHTML="Pathify reads your text as "+pill(c);
179
+ };
180
+
181
+ /* ---------- image stain density heuristic ---------- */
182
+ $("imgFile").onchange=e=>{const f=e.target.files[0]; if(!f){imgData=null;return;} const r=new FileReader();
183
+ r.onload=()=>{const im=new Image(); im.onload=()=>analyzeImage(im); im.src=r.result;}; r.readAsDataURL(f);};
184
+ function analyzeImage(im){
185
+ const S=160, cv=document.createElement("canvas"); cv.width=S; cv.height=S; const g=cv.getContext("2d"); g.drawImage(im,0,0,S,S);
186
+ const a=g.getImageData(0,0,S,S).data;
187
+ const ov=document.createElement("canvas"); ov.width=S; ov.height=S; const go=ov.getContext("2d"); go.drawImage(im,0,0,S,S);
188
+ const od=go.getImageData(0,0,S,S), oa=od.data; let nuclei=0,tissue=0;
189
+ for(let i=0;i<a.length;i+=4){const r=a[i],gr=a[i+1],b=a[i+2],br=(r+gr+b)/3; if(br>245)continue; tissue++;
190
+ if(b>70&&r>55&&gr<r-12&&gr<b-12&&br<175){nuclei++;oa[i]=220;oa[i+1]=30;oa[i+2]=30;}}
191
+ go.putImageData(od,0,0); const frac=tissue?nuclei/tissue:0;
192
+ imgData={frac,suspicion:Math.max(0,Math.min(1,(frac-0.06)/0.22)),overlayURL:ov.toDataURL(),thumbURL:cv.toDataURL()};
193
+ }
194
+
195
+ /* ---------- report classifier into 5 buckets (on device, transparent) ---------- */
196
+ function scoreCats(t){
197
+ t=" "+(t||"").toLowerCase().replace(/\s+/g," ")+" ";
198
+ const s={malignant:0,dysplasia:0,atypical:0,benign:0,nondiag:0}; const terms=[];
199
+ const add=(k,w,lab,side)=>{s[k]+=w; terms.push({label:lab,w,side});};
200
+ // non-diagnostic / adequacy
201
+ [[/non[- ]?diagnostic/g,2,"non-diagnostic"],[/insufficient|inadequate|scant|paucicellular|acellular/g,1.5,"insufficient sample"],
202
+ [/cannot be (assessed|evaluated|interpreted)/g,1.5,"cannot be assessed"],[/no (epithelial|diagnostic) (cells|material)/g,1.5,"no diagnostic material"]]
203
+ .forEach(([re,w,lab])=>{const m=t.match(re); if(m)add("nondiag",w*m.length,lab,"nd");});
204
+ // negated malignancy / dysplasia / atypia -> benign signal, then strip
205
+ const negMal=/(no|negative for|without|absence of|free of)\s+(evidence of\s+)?((?:\w+\s+){0,2})(malignan\w*|tumou?rs?|carcinoma|dysplasi\w*|atypi\w*|neoplas\w*)/g;
206
+ const neg=t.match(negMal); if(neg){neg.forEach(x=>add("benign",3,'"'+x.trim()+'"',"ben")); t=t.replace(negMal," ");}
207
+ // benign
208
+ [[/benign/g,2.5,"benign"],[/within normal limits/g,2.5,"within normal limits"],[/unremarkable/g,1.5,"unremarkable"],
209
+ [/reactive/g,1,"reactive changes"],[/preserved (crypt )?architecture/g,1.5,"preserved architecture"]]
210
+ .forEach(([re,w,lab])=>{const m=t.match(re); if(m)add("benign",w*m.length,lab,"ben");});
211
+ // malignant
212
+ [[/adenocarcinoma/g,4,"adenocarcinoma"],[/carcinoma/g,3,"carcinoma"],[/sarcoma/g,3,"sarcoma"],[/malignan\w*/g,3,"malignant"],
213
+ [/invasiv\w*|invasion/g,2,"invasion"],[/metasta\w*/g,3,"metastasis"]]
214
+ .forEach(([re,w,lab])=>{const m=t.match(re); if(m)add("malignant",w*m.length,lab,"mal");});
215
+ // dysplasia / pre-malignant (non-negated)
216
+ [[/high[- ]grade dysplasia/g,3,"high grade dysplasia"],[/low[- ]grade dysplasia/g,2,"low grade dysplasia"],
217
+ [/dysplas\w*/g,1.5,"dysplasia"],[/intraepithelial neoplasi\w*/g,2,"intraepithelial neoplasia"],[/\bcin\b|\bvin\b/g,2,"intraepithelial neoplasia"]]
218
+ .forEach(([re,w,lab])=>{const m=t.match(re); if(m)add("dysplasia",w*m.length,lab,"warn");});
219
+ // atypical / suspicious / indeterminate
220
+ [[/atypi\w*/g,1.5,"atypia"],[/suspicious/g,2,"suspicious"],[/cannot exclude|cannot rule out/g,1.5,"cannot exclude malignancy"],
221
+ [/indeterminate/g,1.5,"indeterminate"],[/favou?r/g,0.8,"favours a diagnosis"]]
222
+ .forEach(([re,w,lab])=>{const m=t.match(re); if(m)add("atypical",w*m.length,lab,"warn");});
223
+ return {s,terms};
224
+ }
225
+ function classify(t){
226
+ const base=scoreCats(t); const s={...base.s};
227
+ const idx=(t||"").toLowerCase().search(/impression|diagnosis|conclusion/);
228
+ if(idx>=0){const si=scoreCats(t.slice(idx)).s; for(const k in s) s[k]+=2*si[k];}
229
+ const axis=["malignant","dysplasia","atypical","benign"];
230
+ const total=Object.values(s).reduce((a,b)=>a+b,0);
231
+ if(total===0) return {cat:"uncertain",conf:0.45,terms:base.terms,s};
232
+ // adequacy dominates only if it clearly outweighs findings
233
+ const axisSum=axis.reduce((a,k)=>a+s[k],0);
234
+ if(s.nondiag>0 && s.nondiag>=axisSum) return {cat:"nondiag",conf:Math.min(0.95,s.nondiag/total+0.3),terms:base.terms,s};
235
+ const sorted=axis.map(k=>[k,s[k]]).sort((a,b)=>b[1]-a[1]);
236
+ const [topK,topV]=sorted[0], secV=sorted[1][1];
237
+ if(topV===0) return {cat:"uncertain",conf:0.5,terms:base.terms,s};
238
+ const conf=Math.min(0.96,Math.max(0.55,0.55+0.41*(topV-secV)/(axisSum||1)));
239
+ return {cat:topK,conf,terms:base.terms,s};
240
+ }
241
+
242
+ function getPatho(){
243
+ const ft=$("free").value.trim();
244
+ if(ft) return {cat:classify(ft).cat, src:"your typed conclusion"};
245
+ if(selected && selected!=="unknown") return {cat:selected, src:"your selection"};
246
+ if(selected==="unknown") return {cat:"unknown", src:"not stated"};
247
+ return null;
248
+ }
249
+
250
+ /* ---------- render ---------- */
251
+ function render(a){
252
+ const conf=Math.round(a.conf*100);
253
+ const terms=(a.terms||[]).slice().sort((x,y)=>y.w-x.w);
254
+ let why = terms.length
255
+ ? `<details class="why" open><summary>What this is based on</summary>
256
+ <div class="hint" style="margin-top:6px">Pathify is reading the words in the statement here (it is not judging tissue). Terms it weighted:</div>
257
+ <div>${terms.map(t=>`<span class="term ${t.side}">${t.label} +${(+t.w).toFixed(1)}</span>`).join("")}</div></details>`
258
+ : `<div class="hint" style="margin-top:8px">No clear diagnostic terms were found in the text.</div>`;
259
+ let img="";
260
+ if(imgData&&imgData.overlayURL){
261
+ img=`<div class="stitle" style="margin-top:14px;font-size:14px">Image stain check</div>
262
+ <div class="hint">Dense nuclei area ${Math.round(imgData.frac*100)}% of tissue, suspicion ${Math.round(imgData.suspicion*100)}%.</div>
263
+ <div class="imgs"><figure><img src="${imgData.thumbURL}"><figcaption>uploaded</figcaption></figure>
264
+ <figure><img src="${imgData.overlayURL}"><figcaption>highlighted nuclei</figcaption></figure></div>`;
265
+ }
266
+ let html=`<div class="card"><div class="stitle">Pathify's independent read</div>
267
+ <div style="margin:8px 0 2px">${pill(a.cat)} <span class="muted">confidence ${conf}%</span></div>
268
+ <div class="confbar"><span id="cbar"></span></div>${why}${img}</div>`;
269
+
270
+ const patho=getPatho();
271
+ if(!patho || patho.cat==="unknown"){
272
+ html+=`<div class="verdict info"><h3>Read only</h3>
273
+ <div>Pick or type the pathologist's conclusion in step 2 to compare.</div></div>`;
274
+ } else if(a.cat==="uncertain"){
275
+ html+=`<div class="verdict info"><h3>Pathify is not sure</h3>
276
+ <div>Pathologist concluded ${pill(patho.cat)} (${patho.src}); Pathify could not read the text confidently.</div>
277
+ <div class="action">Add more of the report text, or confirm with the pathologist.</div></div>`;
278
+ } else if(a.cat==="nondiag" || patho.cat==="nondiag"){
279
+ const both=(a.cat==="nondiag"&&patho.cat==="nondiag");
280
+ html+= both
281
+ ? `<div class="verdict ok"><h3>Both call it non-diagnostic</h3><div>You and Pathify agree the sample is not adequate.</div>
282
+ <div class="action">No discrepancy. Request a repeat or better sample as usual.</div></div>`
283
+ : `<div class="verdict soft"><h3>Adequacy mismatch</h3>
284
+ <div>One side reads non-diagnostic: pathologist ${pill(patho.cat)} vs Pathify ${pill(a.cat)}.</div>
285
+ <div class="action">Confirm sample adequacy with the pathologist before relying on the read.</div></div>`;
286
+ } else {
287
+ const gap=Math.abs(CATS[a.cat].rank - CATS[patho.cat].rank);
288
+ if(gap===0){
289
+ html+=`<div class="verdict ok"><h3>Matches the pathologist</h3>
290
+ <div>Pathologist ${pill(patho.cat)} (${patho.src}) and Pathify ${pill(a.cat)}.</div>
291
+ <div class="action">No discrepancy found. Safe to proceed and file as usual.</div></div>`;
292
+ } else if(gap===1){
293
+ html+=`<div class="verdict soft"><h3>Borderline difference</h3>
294
+ <div>Pathologist ${pill(patho.cat)} (${patho.src}), Pathify ${pill(a.cat)}. These are one step apart.</div>
295
+ <div class="action">Worth a quick confirm with the pathologist before sign-out.</div></div>`;
296
+ } else {
297
+ html+=`<div class="verdict flag"><h3>Clear discrepancy, second look needed</h3>
298
+ <div>Pathologist ${pill(patho.cat)} (${patho.src}), but Pathify ${pill(a.cat)}. These are ${gap} steps apart.</div>
299
+ <div class="action">Take this case back to the pathologist for a second look before sign-out. Do not change the read yourself.</div></div>`;
300
+ }
301
+ }
302
+ $("result").innerHTML=html;
303
+ requestAnimationFrame(()=>{const c=$("cbar"); if(c) c.style.width=conf+"%";});
304
+ $("reset").style.display="";
305
+ }
306
+
307
+ $("run").onclick=()=>{
308
+ const report=$("report").value.trim();
309
+ if(!report && !imgData){ $("status").textContent="Paste the statement first, or add an image."; return; }
310
+ $("run").disabled=true; $("status").innerHTML='<span class="spinner"></span>Re-verifying...'; $("result").innerHTML="";
311
+ setTimeout(()=>{
312
+ let a;
313
+ if(report){ a=classify(report); }
314
+ else { const s=imgData.suspicion; a={cat:s>=0.5?"malignant":s>0.25?"atypical":"benign",conf:Math.max(s,1-s),terms:[]}; }
315
+ render(a); $("status").textContent=""; $("run").disabled=false;
316
+ },350);
317
+ };
318
+ $("reset").onclick=()=>{
319
+ $("report").value=""; $("imgFile").value=""; $("free").value=""; $("detected").textContent="";
320
+ imgData=null; selected=null; document.querySelectorAll("#seg button").forEach(x=>x.className="");
321
+ $("result").innerHTML=""; $("reset").style.display="none"; $("status").textContent="";
322
+ window.scrollTo({top:0,behavior:"smooth"});
323
+ };
324
+ </script>
325
+ </body>
326
+ </html>
pathqa_demo.html ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8"/>
5
+ <meta name="viewport" content="width=device-width, initial-scale=1"/>
6
+ <title>PathQA — interactive demo</title>
7
+ <style>
8
+ :root{
9
+ --bg:#0f1419; --panel:#161c24; --panel2:#1c242e; --line:#2a343f;
10
+ --text:#e6edf3; --muted:#8b98a5; --accent:#2dd4bf; --accent2:#38bdf8;
11
+ --warn:#f59e0b; --ok:#34d399;
12
+ }
13
+ *{box-sizing:border-box}
14
+ body{margin:0;background:var(--bg);color:var(--text);
15
+ font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif}
16
+ .wrap{max-width:1120px;margin:0 auto;padding:24px}
17
+ header h1{margin:0;font-size:20px}
18
+ header .sub{color:var(--muted);font-size:13px;margin-top:2px}
19
+ .banner{margin:14px 0 18px;padding:10px 14px;border:1px solid var(--line);
20
+ border-left:3px solid var(--accent);background:var(--panel);border-radius:8px;
21
+ font-size:13px;color:var(--muted)}
22
+ .banner b{color:var(--text)}
23
+ .demoflag{margin:0 0 18px;padding:8px 12px;border:1px dashed var(--warn);border-radius:8px;
24
+ font-size:12px;color:var(--warn);background:rgba(245,158,11,.06)}
25
+ .tabs{display:flex;gap:8px;margin-bottom:16px;align-items:center}
26
+ .tab{background:var(--panel);border:1px solid var(--line);color:var(--muted);
27
+ padding:8px 14px;border-radius:8px;font-size:13px;cursor:pointer}
28
+ .tab.active{color:var(--text);border-color:var(--accent);background:var(--panel2)}
29
+ .spacer{flex:1}
30
+ .cards{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:16px}
31
+ .card{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:14px}
32
+ .card .k{color:var(--muted);font-size:12px;text-transform:uppercase;letter-spacing:.4px}
33
+ .card .v{font-size:24px;font-weight:600;margin-top:6px}
34
+ .card .v small{font-size:13px;color:var(--muted);font-weight:400}
35
+ .controls{display:flex;align-items:center;gap:14px;background:var(--panel);
36
+ border:1px solid var(--line);border-radius:10px;padding:14px;margin-bottom:16px;flex-wrap:wrap}
37
+ .controls label{font-size:13px;color:var(--muted)}
38
+ input[type=range]{accent-color:var(--accent);width:210px;vertical-align:middle}
39
+ .pill{font-size:12px;padding:3px 8px;border-radius:999px;border:1px solid var(--line)}
40
+ .pill.tumor{color:#fca5a5;border-color:#5b2b2b;background:#2a1414}
41
+ .pill.normal{color:#a7f3d0;border-color:#1f4d3d;background:#0f241d}
42
+ table{width:100%;border-collapse:collapse;background:var(--panel);border:1px solid var(--line);
43
+ border-radius:10px;overflow:hidden}
44
+ th,td{padding:10px 12px;text-align:left;font-size:13px;border-bottom:1px solid var(--line)}
45
+ th{color:var(--muted);font-weight:500;text-transform:uppercase;font-size:11px;letter-spacing:.5px}
46
+ tr:last-child td{border-bottom:none}
47
+ tr.done{opacity:.5}
48
+ .mono{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px}
49
+ canvas.thumb{width:52px;height:52px;border-radius:6px;border:1px solid var(--line);
50
+ cursor:pointer;image-rendering:pixelated;display:block}
51
+ .confbar{height:6px;background:var(--panel2);border-radius:3px;overflow:hidden;width:90px}
52
+ .confbar>span{display:block;height:100%;background:linear-gradient(90deg,var(--accent),var(--accent2))}
53
+ .btn{font-size:12px;padding:6px 10px;border-radius:7px;border:1px solid var(--line);
54
+ background:var(--panel2);color:var(--text);cursor:pointer}
55
+ .btn:hover{border-color:var(--accent)}
56
+ .btn.amend{border-color:#7a4a12;color:#fcd34d}
57
+ .btn.confirm{border-color:#1f4d3d;color:#a7f3d0}
58
+ .btn.ghost{background:transparent}
59
+ .tag{font-size:11px;padding:2px 8px;border-radius:999px}
60
+ .tag.confirm{background:#0f241d;color:#a7f3d0}
61
+ .tag.amend{background:#2a1c0a;color:#fcd34d}
62
+ .empty{padding:40px;text-align:center;color:var(--muted)}
63
+ .slidegrid{display:grid;grid-template-columns:repeat(2,1fr);gap:14px}
64
+ .slidecard{background:var(--panel);border:1px solid var(--line);border-radius:12px;overflow:hidden}
65
+ .slidecard.done{opacity:.55}
66
+ .slidecard canvas.heat{width:100%;display:block;cursor:pointer;image-rendering:pixelated;border-bottom:1px solid var(--line)}
67
+ .scbody{padding:12px 14px}
68
+ .foot{color:var(--muted);font-size:12px;margin-top:22px;line-height:1.6}
69
+ .modal{position:fixed;inset:0;background:rgba(0,0,0,.6);display:flex;align-items:center;justify-content:center;z-index:20}
70
+ .modal .box{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:20px;max-width:460px;width:92%}
71
+ .modal canvas{width:180px;height:180px;image-rendering:pixelated;border-radius:8px;border:1px solid var(--line)}
72
+ .note{background:var(--panel2);border:1px solid var(--line);color:var(--text);border-radius:6px;padding:5px 7px;font-size:12px;width:120px}
73
+ </style>
74
+ </head>
75
+ <body>
76
+ <div class="wrap">
77
+ <header>
78
+ <h1>PathQA · second-reader QA</h1>
79
+ <div class="sub">An AI safety-net for the pathology sign-out — quality assurance, not diagnosis.</div>
80
+ </header>
81
+ <div class="banner"><b>Assist, not replace.</b> PathQA lists only the cases where the model confidently
82
+ disagrees with the sign-out, so a human can take a second look. You decide the outcome. No sign-out is ever changed automatically.</div>
83
+ <div class="demoflag">Interactive browser demo — synthetic H&amp;E patches and a lightweight in-page model stand in for the backend,
84
+ so you can click through the workflow with zero install. The production app runs the real trained PyTorch model locally (<span class="mono">./pathqa-app</span>).</div>
85
+
86
+ <div class="tabs">
87
+ <button class="tab active" id="tab-patch">Patch QA</button>
88
+ <button class="tab" id="tab-slide">Whole-slide QA</button>
89
+ <span class="spacer"></span>
90
+ <button class="btn ghost" id="regen">↻ Regenerate cohort</button>
91
+ </div>
92
+
93
+ <div id="view"></div>
94
+
95
+ <div class="foot">Every decision would be appended to a local audit log (<span class="mono">audit_log.jsonl</span>) in the real app.
96
+ PathQA outputs re-check recommendations only — it does not diagnose. The pathologist is in control.</div>
97
+ </div>
98
+
99
+ <div id="modalRoot"></div>
100
+
101
+ <script>
102
+ "use strict";
103
+ /* ---------- deterministic RNG ---------- */
104
+ function mulberry32(a){return function(){a|=0;a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296;};}
105
+ let SEED = 1234;
106
+ let rng = mulberry32(SEED);
107
+ const rand=(a,b)=>a+(b-a)*rng();
108
+ const clamp=(x,a,b)=>Math.max(a,Math.min(b,x));
109
+
110
+ /* ---------- state ---------- */
111
+ let view="patch";
112
+ let tauPatch=0.90, tauSlide=0.70;
113
+ let patches=[], slides=[];
114
+ let decisions={}; // id -> "confirm"|"amend"
115
+ const PATCH_N=120, SLIDE_N=8, GRID=14;
116
+
117
+ /* ---------- patch cohort ---------- */
118
+ function makePatch(i){
119
+ const truth = (rng()<0.5)?1:0; // real tissue label
120
+ const correct = rng() > 0.10; // model ~90% accurate
121
+ let prob;
122
+ if(truth===1) prob = correct ? rand(0.72,0.99) : rand(0.10,0.40);
123
+ else prob = correct ? rand(0.01,0.28) : rand(0.58,0.90);
124
+ const call = prob>=0.5?1:0;
125
+ const conf = Math.max(prob,1-prob);
126
+ const err = rng()<0.07; // pathologist mis-read
127
+ const path = err ? 1-truth : truth;
128
+ // nuclei layout (stored so patch + Grad-CAM stay consistent)
129
+ const nuclei=[]; const cluster={cx:rand(0.3,0.7),cy:rand(0.3,0.7),rad:rand(0.16,0.26)};
130
+ const scatter = truth?12:18;
131
+ for(let k=0;k<scatter;k++) nuclei.push({x:rng(),y:rng(),r:rand(0.02,0.045)});
132
+ if(truth===1){ for(let k=0;k<70;k++){const a=rng()*6.28,d=Math.sqrt(rng())*cluster.rad;
133
+ nuclei.push({x:clamp(cluster.cx+Math.cos(a)*d,0,1),y:clamp(cluster.cy+Math.sin(a)*d,0,1),r:rand(0.02,0.05),dense:true});}}
134
+ return {id:"case_"+String(i).padStart(6,"0"),truth,prob,call,conf,path,nuclei,cluster};
135
+ }
136
+ /* ---------- draw a patch ---------- */
137
+ function drawPatch(cv,p){
138
+ const S=96; cv.width=S; cv.height=S; const g=cv.getContext("2d");
139
+ g.fillStyle = p.truth? "#d7b6df" : "#ecccd6"; g.fillRect(0,0,S,S);
140
+ // speckle
141
+ const img=g.getImageData(0,0,S,S), d=img.data;
142
+ for(let j=0;j<d.length;j+=4){const n=(Math.random()-0.5)*22; d[j]+=n; d[j+1]+=n*0.6; d[j+2]+=n;}
143
+ g.putImageData(img,0,0);
144
+ // nuclei
145
+ for(const nu of p.nuclei){
146
+ g.beginPath(); g.arc(nu.x*S,nu.y*S,nu.r*S,0,6.283);
147
+ g.fillStyle = nu.dense? "rgba(84,40,110,0.85)" : "rgba(140,70,120,0.6)"; g.fill();
148
+ }
149
+ }
150
+ /* ---------- draw Grad-CAM overlay ---------- */
151
+ function drawCAM(cv,p){
152
+ drawPatch(cv,p); const S=cv.width, g=cv.getContext("2d");
153
+ const cx=(p.call?p.cluster.cx:0.5)*S, cy=(p.call?p.cluster.cy:0.5)*S;
154
+ const intensity = clamp((p.conf-0.5)*2,0,1); // stronger for confident calls
155
+ const R = (p.call? p.cluster.rad*1.9 : 0.5)*S;
156
+ const grd=g.createRadialGradient(cx,cy,2,cx,cy,R);
157
+ grd.addColorStop(0,`rgba(255,40,40,${0.65*intensity})`);
158
+ grd.addColorStop(0.5,`rgba(255,120,30,${0.35*intensity})`);
159
+ grd.addColorStop(1,"rgba(255,80,40,0)");
160
+ g.fillStyle=grd; g.fillRect(0,0,S,S);
161
+ }
162
+
163
+ /* ---------- slide cohort ---------- */
164
+ function makeSlide(i){
165
+ const truth=(i%2===0)?1:0;
166
+ const n=GRID; const grid=[]; const tumorCells=new Set();
167
+ if(truth===1){ // grow a blob
168
+ let cr=2+Math.floor(rng()*(n-4)), cc=2+Math.floor(rng()*(n-4));
169
+ const cells=[[cr,cc]]; const K=Math.floor(0.10*n*n);
170
+ while(cells.length<K){const b=cells[Math.floor(rng()*cells.length)];
171
+ const nr=clamp(b[0]+Math.floor(rand(-1,2)),0,n-1), nc=clamp(b[1]+Math.floor(rand(-1,2)),0,n-1);
172
+ cells.push([nr,nc]);}
173
+ cells.forEach(c=>tumorCells.add(c[0]+"_"+c[1]));
174
+ }
175
+ const probs=[];
176
+ for(let r=0;r<n;r++){const row=[];for(let c=0;c<n;c++){
177
+ const dist=Math.pow((r-n/2)/(n/2),2)+Math.pow((c-n/2)/(n/2),2);
178
+ if(dist>1.05){row.push(-1);continue;} // glass / background
179
+ const isT=tumorCells.has(r+"_"+c);
180
+ row.push(isT? rand(0.75,0.99) : rand(0.0,0.18));
181
+ }row.push();grid.push(row);}
182
+ const flat=grid.flat().filter(v=>v>=0).sort((a,b)=>b-a);
183
+ const K=Math.max(4,Math.floor(0.02*flat.length));
184
+ const score = flat.slice(0,K).reduce((a,b)=>a+b,0)/K;
185
+ const call=score>=0.5?1:0, conf=Math.max(score,1-score);
186
+ const tumorTiles = flat.filter(v=>v>=0.5).length, tissue=flat.length;
187
+ const err = rng()<0.25; const path = err? 1-truth : truth;
188
+ return {id:"slide_"+String(i).padStart(3,"0"),truth,grid,score,call,conf,tumorTiles,tissue,path};
189
+ }
190
+ function drawHeat(cv,s){
191
+ const n=GRID, cell=14; cv.width=n*cell; cv.height=n*cell; const g=cv.getContext("2d");
192
+ g.fillStyle="#0f1419"; g.fillRect(0,0,cv.width,cv.height);
193
+ for(let r=0;r<n;r++)for(let c=0;c<n;c++){
194
+ const p=s.grid[r][c]; if(p<0) continue;
195
+ let col;
196
+ if(p<0.5){const t=p/0.5; col=`rgb(${29+t*160|0},${158+t*40|0},${117-t*80|0})`;}
197
+ else{const t=(p-0.5)/0.5; col=`rgb(${245},${199-t*160|0},${39+t*36|0})`;}
198
+ g.fillStyle=col; g.fillRect(c*cell,r*cell,cell,cell);
199
+ }
200
+ }
201
+
202
+ /* ---------- build ---------- */
203
+ function rebuild(){
204
+ rng=mulberry32(SEED); decisions={};
205
+ patches=[]; for(let i=0;i<PATCH_N;i++) patches.push(makePatch(i));
206
+ slides=[]; for(let i=0;i<SLIDE_N;i++) slides.push(makeSlide(i));
207
+ render();
208
+ }
209
+
210
+ /* ---------- helpers ---------- */
211
+ const pill=(v)=>`<span class="pill ${v?'tumor':'normal'}">${v?'tumor':'normal'}</span>`;
212
+ const pct=(x)=>(100*x).toFixed(1)+"%";
213
+ function el(html){const d=document.createElement("div"); d.innerHTML=html.trim(); return d.firstChild;}
214
+
215
+ /* ---------- patch view ---------- */
216
+ function patchWorklist(){ // flagged = confident disagreement
217
+ return patches.map(p=>({p,flagged:(p.call!==p.path)&&p.conf>=tauPatch}))
218
+ .filter(x=>x.flagged).sort((a,b)=>b.p.conf-a.p.conf).map(x=>x.p);
219
+ }
220
+ function renderPatch(){
221
+ const disN = patches.filter(p=>p.call!==p.path).length;
222
+ const wl = patchWorklist();
223
+ const resolved = wl.filter(p=>decisions[p.id]).length;
224
+ const view=document.getElementById("view");
225
+ view.innerHTML=`
226
+ <div class="cards">
227
+ <div class="card"><div class="k">Cases reviewed</div><div class="v">${patches.length}</div></div>
228
+ <div class="card"><div class="k">Disagreements</div><div class="v">${disN} <small>· ${pct(disN/patches.length)}</small></div></div>
229
+ <div class="card"><div class="k">Flagged</div><div class="v">${wl.length} <small>· ${pct(wl.length/patches.length)}</small></div></div>
230
+ <div class="card"><div class="k">Resolved</div><div class="v">${resolved} / ${wl.length}</div></div>
231
+ </div>
232
+ <div class="controls">
233
+ <label>Flag confidence threshold (τ)</label>
234
+ <input type="range" id="tp" min="0.5" max="0.999" step="0.005" value="${tauPatch}">
235
+ <span class="mono" id="tpv">τ = ${tauPatch.toFixed(3)}</span>
236
+ <span style="color:var(--muted);font-size:12px">lower τ → catch more · higher τ → shorter queue</span>
237
+ </div>
238
+ <div id="ptable"></div>`;
239
+ const tp=document.getElementById("tp");
240
+ tp.oninput=()=>{document.getElementById("tpv").textContent="τ = "+parseFloat(tp.value).toFixed(3);};
241
+ tp.onchange=()=>{tauPatch=parseFloat(tp.value); renderPatch();};
242
+ const holder=document.getElementById("ptable");
243
+ if(wl.length===0){holder.innerHTML='<div class="empty">Nothing left to re-check at this threshold. ✅</div>'; return;}
244
+ const table=el('<table><thead><tr><th>#</th><th>Patch</th><th>Case</th><th>Sign-out</th><th>Model reads</th><th>Confidence</th><th>Re-review outcome</th></tr></thead><tbody></tbody></table>');
245
+ const tb=table.querySelector("tbody");
246
+ wl.forEach((p,idx)=>{
247
+ const done=decisions[p.id];
248
+ const tr=el(`<tr class="${done?'done':''}">
249
+ <td>${idx+1}</td><td></td><td class="mono">${p.id}</td>
250
+ <td>${pill(p.path)}</td><td>${pill(p.call)}</td>
251
+ <td><div class="confbar"><span style="width:${(100*p.conf)}%"></span></div><span class="mono" style="font-size:11px">${p.conf.toFixed(3)}</span></td>
252
+ <td></td></tr>`);
253
+ const cv=document.createElement("canvas"); cv.className="thumb"; drawPatch(cv,p);
254
+ cv.onclick=()=>openPatchModal(p); tr.children[1].appendChild(cv);
255
+ const out=tr.children[6];
256
+ if(done){ out.innerHTML=`<span class="tag ${done}">${done==='amend'?'Amended':'Sign-out confirmed'}</span>`; }
257
+ else{
258
+ const c=el('<button class="btn confirm">Confirm sign-out</button>');
259
+ const a=el('<button class="btn amend" style="margin-left:6px">Amend (model was right)</button>');
260
+ c.onclick=()=>{decisions[p.id]="confirm"; renderPatch();};
261
+ a.onclick=()=>{decisions[p.id]="amend"; renderPatch();};
262
+ out.appendChild(c); out.appendChild(a);
263
+ }
264
+ tb.appendChild(tr);
265
+ });
266
+ holder.appendChild(table);
267
+ }
268
+ function openPatchModal(p){
269
+ const root=document.getElementById("modalRoot");
270
+ root.innerHTML="";
271
+ const m=el(`<div class="modal"><div class="box">
272
+ <div style="display:flex;justify-content:space-between;margin-bottom:10px">
273
+ <span class="mono">${p.id}</span><span style="cursor:pointer;color:var(--muted)" id="x">✕</span></div>
274
+ <div style="display:flex;gap:14px;justify-content:center">
275
+ <div style="text-align:center"><canvas id="mp"></canvas><div style="font-size:11px;color:var(--muted);margin-top:4px">patch</div></div>
276
+ <div style="text-align:center"><canvas id="mc"></canvas><div style="font-size:11px;color:var(--muted);margin-top:4px">model attention (Grad-CAM)</div></div>
277
+ </div>
278
+ <p style="font-size:13px;color:var(--muted);margin-top:12px">Model reads <b>${p.call?'tumor':'normal'}</b> (confidence ${p.conf.toFixed(2)}) but sign-out is <b>${p.path?'tumor':'normal'}</b> — recommend re-review.</p>
279
+ </div></div>`);
280
+ root.appendChild(m);
281
+ drawPatch(m.querySelector("#mp"),p); drawCAM(m.querySelector("#mc"),p);
282
+ m.onclick=(e)=>{if(e.target===m||e.target.id==="x") root.innerHTML="";};
283
+ }
284
+
285
+ /* ---------- slide view ---------- */
286
+ function slideWorklist(){
287
+ return slides.map(s=>({s,flagged:(s.call!==s.path)&&s.conf>=tauSlide}))
288
+ .filter(x=>x.flagged).sort((a,b)=>b.s.conf-a.s.conf).map(x=>x.s);
289
+ }
290
+ function renderSlide(){
291
+ const wl=slideWorklist();
292
+ const resolved=wl.filter(s=>decisions[s.id]).length;
293
+ const view=document.getElementById("view");
294
+ view.innerHTML=`
295
+ <div class="cards" style="grid-template-columns:repeat(3,1fr)">
296
+ <div class="card"><div class="k">Slides reviewed</div><div class="v">${slides.length}</div></div>
297
+ <div class="card"><div class="k">Flagged for re-review</div><div class="v">${wl.length}</div></div>
298
+ <div class="card"><div class="k">Resolved</div><div class="v">${resolved} / ${wl.length}</div></div>
299
+ </div>
300
+ <div class="controls">
301
+ <label>Slide flag threshold (τ)</label>
302
+ <input type="range" id="ts" min="0.5" max="0.999" step="0.005" value="${tauSlide}">
303
+ <span class="mono" id="tsv">τ = ${tauSlide.toFixed(3)}</span>
304
+ <span style="color:var(--muted);font-size:12px">heatmap: green = normal, red = suspicious tissue</span>
305
+ </div>
306
+ <div id="sgrid"></div>`;
307
+ const ts=document.getElementById("ts");
308
+ ts.oninput=()=>{document.getElementById("tsv").textContent="τ = "+parseFloat(ts.value).toFixed(3);};
309
+ ts.onchange=()=>{tauSlide=parseFloat(ts.value); renderSlide();};
310
+ const holder=document.getElementById("sgrid");
311
+ if(wl.length===0){holder.innerHTML='<div class="empty">No slides flagged at this threshold. ✅</div>'; return;}
312
+ const grid=el('<div class="slidegrid"></div>');
313
+ wl.forEach((s,idx)=>{
314
+ const done=decisions[s.id];
315
+ const card=el(`<div class="slidecard ${done?'done':''}"></div>`);
316
+ const cv=document.createElement("canvas"); cv.className="heat"; drawHeat(cv,s); cv.onclick=()=>openSlideModal(s);
317
+ card.appendChild(cv);
318
+ const body=el(`<div class="scbody">
319
+ <div style="display:flex;justify-content:space-between;align-items:center">
320
+ <span class="mono">#${idx+1} · ${s.id}</span>
321
+ <span class="mono" style="font-size:11px;color:var(--muted)">score ${s.score.toFixed(2)}</span></div>
322
+ <div style="margin:8px 0;font-size:13px">sign-out ${pill(s.path)} &nbsp;vs&nbsp; model ${pill(s.call)}</div>
323
+ <div style="font-size:12px;color:var(--muted);margin-bottom:10px">${s.tumorTiles} suspicious / ${s.tissue} tissue tiles · conf ${s.conf.toFixed(2)}</div>
324
+ <div class="acts"></div></div>`);
325
+ const acts=body.querySelector(".acts");
326
+ if(done){acts.innerHTML=`<span class="tag ${done}">${done==='amend'?'Amended':'Sign-out confirmed'}</span>`;}
327
+ else{
328
+ const c=el('<button class="btn confirm">Confirm sign-out</button>');
329
+ const a=el('<button class="btn amend" style="margin-left:6px">Amend (model was right)</button>');
330
+ c.onclick=()=>{decisions[s.id]="confirm"; renderSlide();};
331
+ a.onclick=()=>{decisions[s.id]="amend"; renderSlide();};
332
+ acts.appendChild(c); acts.appendChild(a);
333
+ }
334
+ card.appendChild(body); grid.appendChild(card);
335
+ });
336
+ holder.appendChild(grid);
337
+ }
338
+ function openSlideModal(s){
339
+ const root=document.getElementById("modalRoot"); root.innerHTML="";
340
+ const m=el(`<div class="modal"><div class="box">
341
+ <div style="display:flex;justify-content:space-between;margin-bottom:10px">
342
+ <span class="mono">${s.id}</span><span style="cursor:pointer;color:var(--muted)" id="x">✕</span></div>
343
+ <div style="text-align:center"><canvas id="mh" style="width:280px;height:280px"></canvas></div>
344
+ <p style="font-size:13px;color:var(--muted);margin-top:12px">Model reads <b>${s.call?'tumor':'normal'}</b> (slide score ${s.score.toFixed(2)}, ${s.tumorTiles} suspicious tiles) but sign-out is <b>${s.path?'tumor':'normal'}</b> — recommend re-review.</p>
345
+ </div></div>`);
346
+ root.appendChild(m); drawHeat(m.querySelector("#mh"),s);
347
+ m.onclick=(e)=>{if(e.target===m||e.target.id==="x") root.innerHTML="";};
348
+ }
349
+
350
+ /* ---------- shell ---------- */
351
+ function render(){ view==="patch"?renderPatch():renderSlide(); }
352
+ document.getElementById("tab-patch").onclick=()=>{view="patch";
353
+ document.getElementById("tab-patch").classList.add("active");
354
+ document.getElementById("tab-slide").classList.remove("active"); render();};
355
+ document.getElementById("tab-slide").onclick=()=>{view="slide";
356
+ document.getElementById("tab-slide").classList.add("active");
357
+ document.getElementById("tab-patch").classList.remove("active"); render();};
358
+ document.getElementById("regen").onclick=()=>{SEED=(SEED*1103515245+12345)>>>0; rebuild();};
359
+ rebuild();
360
+ </script>
361
+ </body>
362
+ </html>
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ torch>=2.0
2
+ torchvision>=0.15
3
+ # No sklearn/pandas needed — AUROC, ECE and worklist export are dependency-free.
4
+ # For real PatchCamelyon download, torchvision also needs h5py:
5
+ h5py>=3.0
samples/HE_benign_low.png ADDED

Git LFS Details

  • SHA256: 8b390b0f2c84d3e74f11154dc46510bc61b098e25778d5ca13818f2a4639e186
  • Pointer size: 131 Bytes
  • Size of remote file: 126 kB
samples/HE_borderline_mid.png ADDED

Git LFS Details

  • SHA256: 229caf1e2005978868ca8aba37b9863593f178f79b876b888efcd318329e5c8f
  • Pointer size: 131 Bytes
  • Size of remote file: 128 kB
samples/HE_tumor_high.png ADDED

Git LFS Details

  • SHA256: 53298b32876e5a5e15c6b3748582f657f2f3f04a8d4cd8b1311812a22d48aecc
  • Pointer size: 131 Bytes
  • Size of remote file: 111 kB
slide_demo.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Whole-slide QA demo.
3
+
4
+ Builds a small cohort of synthetic slides (some with a tumor region, some
5
+ without), scores each slide by tiling + top-K aggregation, assigns a
6
+ pathologist sign-out with a small injected error, runs the slide-level QA
7
+ second reader, and writes a tumor heatmap per slide + a slide worklist.
8
+
9
+ python slide_demo.py --n-slides 8 --epochs 1 --tau 0.7 --outdir slide_out
10
+
11
+ For a real slide, swap SyntheticSlide for `open_slide_image(path)` (OpenSlide is
12
+ used automatically for .svs/.ndpi if installed).
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import json
18
+ import random
19
+ from pathlib import Path
20
+
21
+ import torch
22
+
23
+ from pathqa.data import get_synthetic_loaders
24
+ from pathqa.engine import fit_temperature, train_one_epoch
25
+ from pathqa.model import TemperatureScaler, build_model
26
+ from pathqa.slide import SlideScorer, render_heatmap, review_slides
27
+ from pathqa.wsi import SlideTiler, SyntheticSlide
28
+
29
+
30
+ def get_demo_model(epochs: int, device):
31
+ model = build_model("resnet18", pretrained=False).to(device)
32
+ train_dl, val_dl, _ = get_synthetic_loaders(n_train=256, n_eval=128, batch_size=32)
33
+ optim = torch.optim.Adam(model.parameters(), lr=1e-3)
34
+ for _ in range(max(1, epochs)):
35
+ train_one_epoch(model, train_dl, optim, device)
36
+ scaler = TemperatureScaler()
37
+ scaler.set_temperature(fit_temperature(model, val_dl, device))
38
+ return model, scaler
39
+
40
+
41
+ def main():
42
+ ap = argparse.ArgumentParser()
43
+ ap.add_argument("--n-slides", type=int, default=8)
44
+ ap.add_argument("--grid", type=int, default=16, help="tiles per side of the synthetic slide")
45
+ ap.add_argument("--epochs", type=int, default=1)
46
+ ap.add_argument("--tau", type=float, default=0.7)
47
+ ap.add_argument("--path-error-rate", type=float, default=0.2)
48
+ ap.add_argument("--outdir", default="slide_out")
49
+ args = ap.parse_args()
50
+
51
+ device = torch.device("cpu")
52
+ torch.manual_seed(0); random.seed(0)
53
+ print(f"[slide-QA] preparing model + {args.n_slides} synthetic slides ({args.grid}x{args.grid} tiles)")
54
+ model, scaler = get_demo_model(args.epochs, device)
55
+ scorer = SlideScorer(model, scaler, device, topk_frac=0.02, min_topk=4)
56
+
57
+ out = Path(args.outdir); out.mkdir(parents=True, exist_ok=True)
58
+ scores, labels, truth = {}, {}, {}
59
+ for i in range(args.n_slides):
60
+ has_tumor = (i % 2 == 0)
61
+ slide = SyntheticSlide(grid=args.grid, tumor=has_tumor, seed=100 + i)
62
+ sid = f"slide_{i:03d}"
63
+ tiler = SlideTiler(slide.image(), tile_size=slide.tile, model_size=96)
64
+ sc = scorer.score_slide(sid, tiler)
65
+ scores[sid] = sc
66
+ truth[sid] = int(has_tumor)
67
+ # pathologist sign-out with a small chance of error
68
+ lb = int(has_tumor)
69
+ if random.random() < args.path_error_rate:
70
+ lb = 1 - lb
71
+ labels[sid] = lb
72
+ # save heatmap over the slide thumbnail
73
+ png = render_heatmap(sc, base_image=slide.image())
74
+ (out / f"{sid}_heatmap.png").write_bytes(png)
75
+ print(f" {sid}: truth={'tumor' if has_tumor else 'normal':6s} "
76
+ f"sign-out={'tumor' if lb else 'normal':6s} "
77
+ f"model_score={sc.slide_score:.2f} call={sc.model_read:6s} "
78
+ f"tumor_tiles={sc.n_tumor_tiles}/{sc.n_tissue_tiles}")
79
+
80
+ reviews = review_slides(scores, labels, tau=args.tau)
81
+ flagged = [r for r in reviews if r.flagged]
82
+ print(f"\n[slide-QA] {len(flagged)}/{len(reviews)} slides flagged for re-review at tau={args.tau}")
83
+ for r in sorted(flagged, key=lambda r: r.confidence, reverse=True):
84
+ print(f" FLAG {r.slide_id}: sign-out={r.pathologist_read} vs model={r.model_read} "
85
+ f"(conf {r.confidence:.2f}) — {r.reason}")
86
+
87
+ caught = sum(1 for r in reviews if r.flagged and r.pathologist_label != truth[r.slide_id])
88
+ errs = sum(1 for sid in truth if labels[sid] != truth[sid])
89
+ if errs:
90
+ print(f"[slide-QA effectiveness] of {errs} simulated sign-out errors, flagged {caught}.")
91
+
92
+ report = {
93
+ "tau": args.tau,
94
+ "n_slides": len(reviews),
95
+ "n_flagged": len(flagged),
96
+ "slides": [{
97
+ "slide_id": r.slide_id, "pathologist_read": r.pathologist_read,
98
+ "model_read": r.model_read, "slide_score": round(scores[r.slide_id].slide_score, 3),
99
+ "confidence": round(r.confidence, 3), "n_tumor_tiles": r.n_tumor_tiles,
100
+ "n_tissue_tiles": scores[r.slide_id].n_tissue_tiles,
101
+ "flagged": r.flagged, "reason": r.reason,
102
+ } for r in reviews],
103
+ }
104
+ (out / "slide_report.json").write_text(json.dumps(report, indent=2))
105
+ print(f"\n[saved] {out}/slide_report.json + per-slide *_heatmap.png")
106
+ print("PathQA flags slides for human re-review only. It does not diagnose.")
107
+
108
+
109
+ if __name__ == "__main__":
110
+ main()
train_combined.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Train on PathMNIST + PatchCamelyon MIXED together (balanced, no forgetting).
3
+
4
+ Instead of training on one dataset then the other (which makes the model forget
5
+ the first), this mixes both datasets into one training set and trains a single
6
+ model on the combination. The result is genuinely strong on BOTH colorectal
7
+ (PathMNIST) and lymph-node (PatchCamelyon) tissue.
8
+
9
+ pip install medmnist datasets
10
+ python train_combined.py --epochs 2 --out model.pt
11
+ # quick test: python train_combined.py --subset 6000 --epochs 1 --out model.pt
12
+
13
+ Reuses the same loaders as train_open.py (PathMNIST) and train_pcam_hf.py (PCam).
14
+ Run on a GPU (Colab). Both are open datasets that download automatically.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+
20
+ import torch
21
+ import torch.nn.functional as F
22
+ from torch.utils.data import ConcatDataset, DataLoader, Subset
23
+
24
+ from pathqa.engine import (evaluate, expected_calibration_error, fit_temperature,
25
+ train_one_epoch)
26
+ from pathqa.model import TemperatureScaler, build_model
27
+ from train_open import BinaryPathMNIST # PathMNIST, binarised tumour vs rest
28
+ from train_pcam_hf import HFPatchCam # PatchCamelyon via Hugging Face
29
+
30
+
31
+ def _cap(ds, n):
32
+ return Subset(ds, range(min(n, len(ds)))) if n else ds
33
+
34
+
35
+ def build(subset, batch_size):
36
+ # train splits from both datasets, mixed
37
+ pm_tr, pc_tr = BinaryPathMNIST("train", True), HFPatchCam("train", True)
38
+ pm_va, pc_va = BinaryPathMNIST("val", False), HFPatchCam("validation", False)
39
+ pm_te, pc_te = BinaryPathMNIST("test", False), HFPatchCam("test", False)
40
+ if subset:
41
+ s4 = subset // 4 or 1
42
+ pm_tr, pc_tr = _cap(pm_tr, subset), _cap(pc_tr, subset)
43
+ pm_va, pc_va = _cap(pm_va, s4), _cap(pc_va, s4)
44
+ pm_te, pc_te = _cap(pm_te, s4), _cap(pc_te, s4)
45
+ train = ConcatDataset([pm_tr, pc_tr])
46
+ val = ConcatDataset([pm_va, pc_va])
47
+ dl = lambda d, sh: DataLoader(d, batch_size=batch_size, shuffle=sh, num_workers=2)
48
+ # keep the two test sets separate so we can report each tissue's score
49
+ return (dl(train, True), dl(val, False),
50
+ dl(pm_te, False), dl(pc_te, False))
51
+
52
+
53
+ @torch.no_grad()
54
+ def _probs_labels(model, loader, device, scaler):
55
+ model.eval(); ps, ys = [], []
56
+ for x, y in loader:
57
+ lo = model(x.to(device))
58
+ if scaler is not None:
59
+ lo = scaler(lo)
60
+ ps.append(F.softmax(lo, 1)[:, 1].cpu()); ys.append(y)
61
+ return torch.cat(ps), torch.cat(ys)
62
+
63
+
64
+ def main():
65
+ ap = argparse.ArgumentParser()
66
+ ap.add_argument("--epochs", type=int, default=2)
67
+ ap.add_argument("--lr", type=float, default=1e-4)
68
+ ap.add_argument("--batch-size", type=int, default=256)
69
+ ap.add_argument("--subset", type=int, default=None, help="cap samples per dataset (quick test)")
70
+ ap.add_argument("--base", default=None, help="optional checkpoint to start from")
71
+ ap.add_argument("--out", default="model.pt")
72
+ args = ap.parse_args()
73
+
74
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
75
+ print(f"[train_combined] device={device} datasets=PathMNIST + PatchCamelyon (mixed)")
76
+ train_dl, val_dl, pm_test_dl, pc_test_dl = build(args.subset, args.batch_size)
77
+ print(f"[train_combined] mixed train batches={len(train_dl)} val batches={len(val_dl)}")
78
+
79
+ model = build_model("resnet18", pretrained=True).to(device)
80
+ if args.base:
81
+ ck = torch.load(args.base, map_location=device)
82
+ model.load_state_dict(ck["state_dict"] if "state_dict" in ck else ck)
83
+ print(f"[train_combined] starting from {args.base}")
84
+ optim = torch.optim.Adam(model.parameters(), lr=args.lr)
85
+
86
+ best, best_state = -1.0, None
87
+ for ep in range(args.epochs):
88
+ loss = train_one_epoch(model, train_dl, optim, device)
89
+ res = evaluate(model, val_dl, device)
90
+ print(f"[epoch {ep+1}/{args.epochs}] loss={loss:.3f} mixed_val_acc={res.accuracy:.3f} mixed_val_auroc={res.auroc:.3f}")
91
+ if res.auroc >= best:
92
+ best, best_state = res.auroc, {k: v.cpu().clone() for k, v in model.state_dict().items()}
93
+ if best_state:
94
+ model.load_state_dict(best_state)
95
+
96
+ T = fit_temperature(model, val_dl, device)
97
+ scaler = TemperatureScaler(); scaler.set_temperature(T)
98
+ pm = evaluate(model, pm_test_dl, device, scaler=scaler)
99
+ pc = evaluate(model, pc_test_dl, device, scaler=scaler)
100
+ p, y = _probs_labels(model, pc_test_dl, device, scaler)
101
+ ece = expected_calibration_error(p, y)
102
+ print("\n=== Held-out test (each tissue) ===")
103
+ print(f" PathMNIST (colorectal): acc {pm.accuracy:.3f} | AUROC {pm.auroc:.3f}")
104
+ print(f" PatchCamelyon (lymph) : acc {pc.accuracy:.3f} | AUROC {pc.auroc:.3f}")
105
+ print(f" temperature T={T:.3f} (PCam ECE {ece:.3f})")
106
+
107
+ torch.save({"state_dict": model.state_dict(), "backbone": "resnet18", "temperature": T,
108
+ "labels": {0: "normal", 1: "tumor"},
109
+ "metrics": {"pathmnist_auroc": pm.auroc, "pcam_auroc": pc.auroc,
110
+ "test_auroc": min(pm.auroc, pc.auroc)},
111
+ "note": "Pathify model trained on PathMNIST + PatchCamelyon (mixed)."}, args.out)
112
+ print(f"[saved] {args.out}")
113
+
114
+
115
+ if __name__ == "__main__":
116
+ main()
train_on_your_data.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Train-on-your-data entry point.
3
+
4
+ This is the version a lab actually runs. Point it at a local folder of the
5
+ lab's OWN labeled patches and it fine-tunes the classifier on that lab's stain,
6
+ scanner and tissue mix — which is what closes the domain-shift gap that makes
7
+ off-the-shelf models fail. Data never leaves the machine.
8
+
9
+ Expected layout:
10
+ my_lab_data/
11
+ train/normal/*.png train/tumor/*.png
12
+ val/normal/*.png val/tumor/*.png
13
+
14
+ Usage:
15
+ python train_on_your_data.py --data my_lab_data --epochs 5 --out model.pt
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ from pathlib import Path
21
+
22
+ import torch
23
+
24
+ from pathqa.data import get_folder_loaders
25
+ from pathqa.engine import evaluate, fit_temperature, train_one_epoch
26
+ from pathqa.model import build_model
27
+
28
+
29
+ def main() -> None:
30
+ ap = argparse.ArgumentParser()
31
+ ap.add_argument("--data", required=True, help="root folder with train/ and val/")
32
+ ap.add_argument("--epochs", type=int, default=5)
33
+ ap.add_argument("--lr", type=float, default=1e-4)
34
+ ap.add_argument("--batch-size", type=int, default=128)
35
+ ap.add_argument("--backbone", default="resnet18")
36
+ ap.add_argument("--out", default="model.pt")
37
+ args = ap.parse_args()
38
+
39
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
40
+ train_dl, val_dl = get_folder_loaders(args.data, batch_size=args.batch_size, num_workers=4)
41
+
42
+ model = build_model(args.backbone, pretrained=True).to(device)
43
+ optim = torch.optim.Adam(model.parameters(), lr=args.lr)
44
+
45
+ best_auroc = -1.0
46
+ for ep in range(args.epochs):
47
+ loss = train_one_epoch(model, train_dl, optim, device)
48
+ res = evaluate(model, val_dl, device)
49
+ print(f"epoch {ep+1}/{args.epochs} loss={loss:.3f} "
50
+ f"val_acc={res.accuracy:.3f} val_auroc={res.auroc:.3f}")
51
+ if res.auroc > best_auroc:
52
+ best_auroc = res.auroc
53
+ _save(model, args, device, val_dl)
54
+ print(f"Best val AUROC {best_auroc:.3f}. Saved -> {args.out}")
55
+
56
+
57
+ def _save(model, args, device, val_dl) -> None:
58
+ T = fit_temperature(model, val_dl, device)
59
+ torch.save({
60
+ "state_dict": model.state_dict(),
61
+ "backbone": args.backbone,
62
+ "temperature": T,
63
+ "labels": {0: "normal", 1: "tumor"},
64
+ "note": "PathQA QA second-reader model. Outputs re-check flags, not diagnoses.",
65
+ }, args.out)
66
+
67
+
68
+ if __name__ == "__main__":
69
+ main()
train_open.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Train on a real, openly-available histopathology dataset (no manual download).
3
+
4
+ Uses MedMNIST's PathMNIST (100k+ real colorectal H&E image tiles, 9 tissue
5
+ classes, auto-downloaded from Zenodo). We binarise it to the task the app uses:
6
+
7
+ tumour = colorectal adenocarcinoma epithelium (class 8)
8
+ normal = everything else
9
+
10
+ It trains a ResNet18, reports honest held-out AUROC + calibration (ECE), and
11
+ saves a checkpoint the app loads directly:
12
+
13
+ PATHQA_MODEL=model.pt ./pathqa-app (or set it in your host)
14
+
15
+ Run on a GPU (Colab is free). CPU works but is slow.
16
+
17
+ pip install medmnist
18
+ python train_open.py --epochs 3 --out model.pt
19
+ # quick test: python train_open.py --epochs 1 --subset 4000 --out model.pt
20
+
21
+ For the closer-to-real PatchCamelyon set instead, use train_pcam.py.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import argparse
26
+
27
+ import torch
28
+ import torch.nn.functional as F
29
+ from torch.utils.data import DataLoader, Dataset, Subset
30
+ from torchvision import transforms
31
+
32
+ from pathqa.data import IMAGENET_MEAN, IMAGENET_STD
33
+ from pathqa.engine import (evaluate, expected_calibration_error, fit_temperature,
34
+ train_one_epoch)
35
+ from pathqa.model import TemperatureScaler, build_model
36
+
37
+ TUMOUR_CLASS = 8 # PathMNIST: colorectal adenocarcinoma epithelium (TUM)
38
+
39
+
40
+ class BinaryPathMNIST(Dataset):
41
+ """PathMNIST wrapped as binary tumour(=1)/normal(=0), resized to 96px."""
42
+
43
+ def __init__(self, split: str, train: bool):
44
+ from medmnist import PathMNIST
45
+ aug = [transforms.RandomHorizontalFlip(), transforms.RandomVerticalFlip()] if train else []
46
+ self.tf = transforms.Compose([transforms.Resize(96), *aug,
47
+ transforms.ToTensor(),
48
+ transforms.Normalize(IMAGENET_MEAN, IMAGENET_STD)])
49
+ self.ds = PathMNIST(split=split, download=True, as_rgb=True, size=28)
50
+
51
+ def __len__(self):
52
+ return len(self.ds)
53
+
54
+ def __getitem__(self, i):
55
+ img, y = self.ds[i] # PIL image, label array shape (1,)
56
+ label = 1 if int(y[0]) == TUMOUR_CLASS else 0
57
+ return self.tf(img), label
58
+
59
+
60
+ def loaders(batch_size, subset):
61
+ tr, va, te = (BinaryPathMNIST("train", True), BinaryPathMNIST("val", False),
62
+ BinaryPathMNIST("test", False))
63
+ if subset:
64
+ tr = Subset(tr, range(min(subset, len(tr))))
65
+ va = Subset(va, range(min(subset // 4 or 1, len(va))))
66
+ te = Subset(te, range(min(subset // 4 or 1, len(te))))
67
+ return (DataLoader(tr, batch_size, shuffle=True, num_workers=2),
68
+ DataLoader(va, batch_size, num_workers=2),
69
+ DataLoader(te, batch_size, num_workers=2))
70
+
71
+
72
+ @torch.no_grad()
73
+ def _probs_labels(model, loader, device, scaler=None):
74
+ model.eval(); ps, ys = [], []
75
+ for x, y in loader:
76
+ lo = model(x.to(device))
77
+ if scaler is not None:
78
+ lo = scaler(lo)
79
+ ps.append(F.softmax(lo, 1)[:, 1].cpu()); ys.append(y)
80
+ return torch.cat(ps), torch.cat(ys)
81
+
82
+
83
+ def main():
84
+ ap = argparse.ArgumentParser()
85
+ ap.add_argument("--epochs", type=int, default=3)
86
+ ap.add_argument("--lr", type=float, default=1e-4)
87
+ ap.add_argument("--batch-size", type=int, default=128)
88
+ ap.add_argument("--subset", type=int, default=None, help="cap samples per split for a quick run")
89
+ ap.add_argument("--out", default="model.pt")
90
+ args = ap.parse_args()
91
+
92
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
93
+ print(f"[train_open] device={device} dataset=PathMNIST (binarised tumour vs rest)")
94
+ train_dl, val_dl, test_dl = loaders(args.batch_size, args.subset)
95
+
96
+ model = build_model("resnet18", pretrained=True).to(device)
97
+ optim = torch.optim.Adam(model.parameters(), lr=args.lr)
98
+ best, best_state = -1.0, None
99
+ for ep in range(args.epochs):
100
+ loss = train_one_epoch(model, train_dl, optim, device)
101
+ res = evaluate(model, val_dl, device)
102
+ print(f"[epoch {ep+1}/{args.epochs}] loss={loss:.3f} val_acc={res.accuracy:.3f} val_auroc={res.auroc:.3f}")
103
+ if res.auroc >= best:
104
+ best, best_state = res.auroc, {k: v.cpu().clone() for k, v in model.state_dict().items()}
105
+ if best_state:
106
+ model.load_state_dict(best_state)
107
+
108
+ T = fit_temperature(model, val_dl, device)
109
+ scaler = TemperatureScaler(); scaler.set_temperature(T)
110
+ p, y = _probs_labels(model, test_dl, device, scaler)
111
+ test = evaluate(model, test_dl, device, scaler=scaler)
112
+ ece = expected_calibration_error(p, y)
113
+ print("\n=== Held-out test metrics (real data) ===")
114
+ print(f" accuracy {test.accuracy:.3f} | AUROC {test.auroc:.3f} | ECE {ece:.3f} | T {T:.3f} | n {test.n}")
115
+
116
+ torch.save({"state_dict": model.state_dict(), "backbone": "resnet18", "temperature": T,
117
+ "labels": {0: "normal", 1: "tumor"},
118
+ "metrics": {"test_auroc": test.auroc, "test_acc": test.accuracy, "ece": ece},
119
+ "note": "Pathify model trained on PathMNIST (open data). QA aid, not a diagnosis."},
120
+ args.out)
121
+ print(f"[saved] {args.out} -> run with PATHQA_MODEL={args.out}")
122
+
123
+
124
+ if __name__ == "__main__":
125
+ main()
train_pcam.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Train the patch classifier on real PatchCamelyon and report genuine metrics.
3
+
4
+ Produces a calibrated, app-ready checkpoint plus real AUROC and Expected
5
+ Calibration Error (ECE) on the held-out PCam test split.
6
+
7
+ PCam is ~7 GB and training wants a GPU, so run this on your machine or Colab:
8
+
9
+ # full run (GPU)
10
+ python train_pcam.py --epochs 5 --batch-size 256 --out pcam_model.pt
11
+
12
+ # quick CPU sanity run on a subset
13
+ python train_pcam.py --subset 8000 --epochs 1 --batch-size 64 --out pcam_model.pt
14
+
15
+ # verify the pipeline with no download (synthetic stand-in)
16
+ python train_pcam.py --synthetic --epochs 1 --out demo_model.pt
17
+
18
+ The checkpoint (state_dict + backbone + fitted temperature + labels) drops
19
+ straight into the app: PATHQA_MODEL=pcam_model.pt python backend/server.py
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import time
25
+
26
+ import torch
27
+
28
+ from pathqa.data import get_pcam_loaders, get_synthetic_loaders
29
+ from pathqa.engine import (EvalResult, evaluate, expected_calibration_error,
30
+ fit_temperature, train_one_epoch)
31
+ from pathqa.model import TemperatureScaler, build_model
32
+
33
+
34
+ @torch.no_grad()
35
+ def _probs_labels(model, loader, device, scaler=None, max_batches=None):
36
+ import torch.nn.functional as F
37
+ model.eval(); ps, ys = [], []
38
+ for i, (x, y) in enumerate(loader):
39
+ if max_batches is not None and i >= max_batches:
40
+ break
41
+ logits = model(x.to(device))
42
+ if scaler is not None:
43
+ logits = scaler(logits)
44
+ ps.append(F.softmax(logits, 1)[:, 1].cpu()); ys.append(y)
45
+ return torch.cat(ps), torch.cat(ys)
46
+
47
+
48
+ def main():
49
+ ap = argparse.ArgumentParser()
50
+ src = ap.add_mutually_exclusive_group()
51
+ src.add_argument("--synthetic", action="store_true", help="no-download pipeline check")
52
+ ap.add_argument("--data-root", default="./data")
53
+ ap.add_argument("--subset", type=int, default=None, help="samples per split (CPU-friendly)")
54
+ ap.add_argument("--epochs", type=int, default=5)
55
+ ap.add_argument("--lr", type=float, default=1e-4)
56
+ ap.add_argument("--batch-size", type=int, default=256)
57
+ ap.add_argument("--backbone", default="resnet18")
58
+ ap.add_argument("--out", default="pcam_model.pt")
59
+ ap.add_argument("--base", default=None, help="start from an existing checkpoint (continue training / 'merge')")
60
+ ap.add_argument("--no-pretrained", action="store_true", help="skip ImageNet weights (offline)")
61
+ ap.add_argument("--max-batches", type=int, default=None, help="cap batches/epoch (debug)")
62
+ args = ap.parse_args()
63
+
64
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
65
+ print(f"[train_pcam] device={device} source={'synthetic' if args.synthetic else 'PatchCamelyon'}")
66
+
67
+ if args.synthetic:
68
+ train_dl, val_dl, test_dl = get_synthetic_loaders(n_train=512, n_eval=256, batch_size=args.batch_size)
69
+ else:
70
+ train_dl, val_dl, test_dl = get_pcam_loaders(
71
+ root=args.data_root, batch_size=args.batch_size, num_workers=4, subset=args.subset)
72
+
73
+ model = build_model(args.backbone, pretrained=not args.no_pretrained).to(device)
74
+ if args.base:
75
+ ck = torch.load(args.base, map_location=device)
76
+ model.load_state_dict(ck["state_dict"] if "state_dict" in ck else ck)
77
+ print(f"[train_pcam] continuing from {args.base} (keeps its prior learning)")
78
+ optim = torch.optim.Adam(model.parameters(), lr=args.lr)
79
+
80
+ best_auroc, best_state = -1.0, None
81
+ for ep in range(args.epochs):
82
+ t0 = time.time()
83
+ loss = train_one_epoch(model, train_dl, optim, device, max_batches=args.max_batches)
84
+ res = evaluate(model, val_dl, device, max_batches=args.max_batches)
85
+ print(f"[epoch {ep+1}/{args.epochs}] loss={loss:.3f} val_acc={res.accuracy:.3f} "
86
+ f"val_auroc={res.auroc:.3f} ({time.time()-t0:.0f}s)")
87
+ if res.auroc > best_auroc:
88
+ best_auroc, best_state = res.auroc, {k: v.cpu().clone() for k, v in model.state_dict().items()}
89
+
90
+ if best_state is not None:
91
+ model.load_state_dict(best_state)
92
+
93
+ # Calibrate on val, then report honest test-set metrics.
94
+ T = fit_temperature(model, val_dl, device, max_batches=args.max_batches)
95
+ scaler = TemperatureScaler(); scaler.set_temperature(T)
96
+
97
+ p_raw, y = _probs_labels(model, test_dl, device, scaler=None, max_batches=args.max_batches)
98
+ p_cal, _ = _probs_labels(model, test_dl, device, scaler=scaler, max_batches=args.max_batches)
99
+ test = evaluate(model, test_dl, device, scaler=scaler, max_batches=args.max_batches)
100
+ ece_raw = expected_calibration_error(p_raw, y)
101
+ ece_cal = expected_calibration_error(p_cal, y)
102
+
103
+ print("\n=== PatchCamelyon test metrics ===")
104
+ print(f" accuracy : {test.accuracy:.3f}")
105
+ print(f" AUROC : {test.auroc:.3f}")
106
+ print(f" ECE : {ece_raw:.3f} (raw) -> {ece_cal:.3f} (calibrated), T={T:.3f}")
107
+ print(f" n(test) : {test.n}")
108
+
109
+ torch.save({
110
+ "state_dict": model.state_dict(), "backbone": args.backbone,
111
+ "temperature": T, "labels": {0: "normal", 1: "tumor"},
112
+ "metrics": {"test_auroc": test.auroc, "test_acc": test.accuracy,
113
+ "ece_calibrated": ece_cal},
114
+ "note": "PathQA QA second-reader model. Outputs re-check flags, not diagnoses.",
115
+ }, args.out)
116
+ print(f"[saved] {args.out} → run: PATHQA_MODEL={args.out} python backend/server.py")
117
+
118
+
119
+ if __name__ == "__main__":
120
+ main()
train_pcam_hf.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Train on PatchCamelyon via the Hugging Face mirror (reliable download).
3
+
4
+ Uses `zacharielegault/PatchCamelyon` (327k 96px lymph-node tiles, binary
5
+ tumour/normal), which downloads through the Hugging Face datasets library, no
6
+ Google-Drive quota problems like torchvision's built-in PCam.
7
+
8
+ Continue-training your existing model (the 'merge'):
9
+
10
+ pip install datasets
11
+ python train_pcam_hf.py --base model.pt --epochs 2 --out model.pt
12
+ # quick test: python train_pcam_hf.py --base model.pt --subset 8000 --epochs 1 --out model.pt
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+
18
+ import torch
19
+ import torch.nn.functional as F
20
+ from torch.utils.data import DataLoader, Dataset, Subset
21
+ from torchvision import transforms
22
+
23
+ from pathqa.data import IMAGENET_MEAN, IMAGENET_STD
24
+ from pathqa.engine import (evaluate, expected_calibration_error, fit_temperature,
25
+ train_one_epoch)
26
+ from pathqa.model import TemperatureScaler, build_model
27
+
28
+ HF_ID = "zacharielegault/PatchCamelyon" # image (96px) + label (0 normal / 1 tumour)
29
+
30
+
31
+ class HFPatchCam(Dataset):
32
+ def __init__(self, split: str, train: bool):
33
+ from datasets import load_dataset
34
+ self.ds = load_dataset(HF_ID, split=split)
35
+ aug = [transforms.RandomHorizontalFlip(), transforms.RandomVerticalFlip()] if train else []
36
+ self.tf = transforms.Compose([transforms.Resize(96), *aug,
37
+ transforms.ToTensor(),
38
+ transforms.Normalize(IMAGENET_MEAN, IMAGENET_STD)])
39
+
40
+ def __len__(self):
41
+ return len(self.ds)
42
+
43
+ def __getitem__(self, i):
44
+ r = self.ds[i]
45
+ return self.tf(r["image"].convert("RGB")), int(r["label"])
46
+
47
+
48
+ def loaders(batch_size, subset):
49
+ tr, va, te = (HFPatchCam("train", True), HFPatchCam("validation", False), HFPatchCam("test", False))
50
+ if subset:
51
+ tr = Subset(tr, range(min(subset, len(tr))))
52
+ va = Subset(va, range(min(subset // 4 or 1, len(va))))
53
+ te = Subset(te, range(min(subset // 4 or 1, len(te))))
54
+ return (DataLoader(tr, batch_size, shuffle=True, num_workers=2),
55
+ DataLoader(va, batch_size, num_workers=2),
56
+ DataLoader(te, batch_size, num_workers=2))
57
+
58
+
59
+ @torch.no_grad()
60
+ def _probs_labels(model, loader, device, scaler=None):
61
+ model.eval(); ps, ys = [], []
62
+ for x, y in loader:
63
+ lo = model(x.to(device))
64
+ if scaler is not None:
65
+ lo = scaler(lo)
66
+ ps.append(F.softmax(lo, 1)[:, 1].cpu()); ys.append(y)
67
+ return torch.cat(ps), torch.cat(ys)
68
+
69
+
70
+ def main():
71
+ ap = argparse.ArgumentParser()
72
+ ap.add_argument("--epochs", type=int, default=2)
73
+ ap.add_argument("--lr", type=float, default=1e-4)
74
+ ap.add_argument("--batch-size", type=int, default=256)
75
+ ap.add_argument("--subset", type=int, default=None)
76
+ ap.add_argument("--base", default=None, help="checkpoint to continue from")
77
+ ap.add_argument("--out", default="model.pt")
78
+ args = ap.parse_args()
79
+
80
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
81
+ print(f"[train_pcam_hf] device={device} dataset={HF_ID}")
82
+ train_dl, val_dl, test_dl = loaders(args.batch_size, args.subset)
83
+
84
+ model = build_model("resnet18", pretrained=True).to(device)
85
+ if args.base:
86
+ ck = torch.load(args.base, map_location=device)
87
+ model.load_state_dict(ck["state_dict"] if "state_dict" in ck else ck)
88
+ print(f"[train_pcam_hf] continuing from {args.base}")
89
+ optim = torch.optim.Adam(model.parameters(), lr=args.lr)
90
+
91
+ best, best_state = -1.0, None
92
+ for ep in range(args.epochs):
93
+ loss = train_one_epoch(model, train_dl, optim, device)
94
+ res = evaluate(model, val_dl, device)
95
+ print(f"[epoch {ep+1}/{args.epochs}] loss={loss:.3f} val_acc={res.accuracy:.3f} val_auroc={res.auroc:.3f}")
96
+ if res.auroc >= best:
97
+ best, best_state = res.auroc, {k: v.cpu().clone() for k, v in model.state_dict().items()}
98
+ if best_state:
99
+ model.load_state_dict(best_state)
100
+
101
+ T = fit_temperature(model, val_dl, device)
102
+ scaler = TemperatureScaler(); scaler.set_temperature(T)
103
+ p, y = _probs_labels(model, test_dl, device, scaler)
104
+ test = evaluate(model, test_dl, device, scaler=scaler)
105
+ ece = expected_calibration_error(p, y)
106
+ print(f"\n=== PatchCamelyon test === accuracy {test.accuracy:.3f} | AUROC {test.auroc:.3f} | ECE {ece:.3f} | T {T:.3f}")
107
+
108
+ torch.save({"state_dict": model.state_dict(), "backbone": "resnet18", "temperature": T,
109
+ "labels": {0: "normal", 1: "tumor"},
110
+ "metrics": {"test_auroc": test.auroc, "test_acc": test.accuracy, "ece": ece},
111
+ "note": "Pathify model, trained/continued on PatchCamelyon (HF mirror)."}, args.out)
112
+ print(f"[saved] {args.out}")
113
+
114
+
115
+ if __name__ == "__main__":
116
+ main()
zigWmHRR ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:05d41f8f566d4424e08af2cd80d05b2f007b66ba635770391e74148a630ffca6
3
+ size 621516