Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

OPMD Triage System — v3

Decision-support for oral potentially-malignant disorder (OPMD) screening. A midwife photographs the oral cavity, an EfficientNet-B4 + ResNet50 ensemble classifies it, Grad-CAM++ highlights the region that drove the decision, and a surgeon triages the case.

No Docker. Backend is FastAPI on SQLite; training runs on a free Kaggle GPU.


Read this first

This project is built around a handful of facts about the dataset. They constrain everything else, and any number quoted without them is misleading.

Fact Consequence
1,964 images from 510 patients (1,953 after dedup), classes 718 / 1110 / 125 A constant "opmd" predictor scores 56.8% accuracy. Accuracy is not the metric — balanced accuracy and macro-F1 are.
Labels live in Imagewise_Data.csv, not in the filename The v2 pipeline read the class from the filename prefix. Under this dataset that is wrong: the 253-image C cohort is healthy controls, which the old map would call cancer. See opmd/labels.py.
Benign has 748 CSV rows and 2 image files The class is dropped, not merged. The model has never seen coated tongue, candidiasis, VBD or mucocele, and will force each into one of the three trained classes. This is the largest gap between the metrics and clinical reality.
1,034 of 3,000 CSV rows have no image file 746 Benign, 284 OPMD, 4 OCA. The manifest records the gap rather than papering over it.
1,239 usable hand-painted lesion masks, spanning every trainable class Localization is measured for the first time, and the models are trained with a lesion-guided objective rather than class labels alone.
13.8% of images sit at a resolution used by exactly one class Down from 95% on the v2 dataset. Still measured every run by scripts/shortcut_baseline.py, never assumed.
cancer is the rarest class: 125 images from 58 patients Its recall is the noisiest number in any report and must not be quoted alone.

The unit of evidence is the patient, not the image. One patient contributes up to 11 correlated photographs, so every confidence interval bootstraps the 510 patients, never the 1,953 images.

The deliverable is a reproducible pipeline and an honest number, not a high one. See docs/HONEST_LIMITATIONS.md.

What changed from v2

v2 shipped on 130 images from 51 patients with no annotations at all. Three things follow from the new data, and they are the whole reason for v3:

  1. Labels moved to the CSV. Filename-prefix labelling is now an inverted mapping for a quarter of the corpus, so it is gone, and labels.json records that the prefix is a cohort id.
  2. Localization is measured. v2 documented "localization accuracy is unmeasured" as a permanent limitation. opmd/localization.py now scores Grad-CAM++ out-of-fold against the painted masks — pointing-game hit rate, lesion coverage and IoU, each against its own chance level.
  3. Training is lesion-guided. A 1×1 segmentation head on the final feature map is trained against the masks alongside the classifier, so class evidence is pushed onto mucosa instead of onto the examiner's fingers. At serving time its (coarse) map damps CAM attention it does not support; it can never invent attention the CAM did not have.

Checkpoints from v2 are not loadable and their labels are wrong for the C cohort. opmd.models.load_for_inference refuses them explicitly rather than loading them partially.


Documentation

Document Contents
docs/CODEBASE.md Every file, what it does, and how it changed across v1 → v2 → v3
docs/PIPELINE.md End-to-end pipeline: data → training → calibration → localization → serving, with every hyperparameter and the reason for it
docs/CALCULATIONS.md The arithmetic: TTA averaging, temperature scaling, the ensemble blend, Grad-CAM++, the losses and every metric — each formula with a worked example carried through it
docs/RUNBOOK.md Copy-paste commands for the Kaggle retrain and local setup
docs/KAGGLE.md The Kaggle route in full: dataset folder structure, what to upload and why it is split into three datasets, every command and flag, and the gotchas
docs/ARCHITECTURE.md Module layout, import boundaries, request flow, data model
docs/POSTMAN.md API test guide — every endpoint, its body type, expected status codes and the role/auth negative tests. Importable collection: docs/opmd-postman-collection.json
docs/V1_VS_V2.md Every v1 defect, where it was, and how it was addressed
docs/HONEST_LIMITATIONS.md What this system cannot do and what its numbers do not mean
dataset/prepare_report.md Generated — every data decision prepare_dataset.py made
artifacts/metrics_report.md Generated by scripts/evaluate.py — the actual measured performance
artifacts/subtype_report.md Generated by scripts/fit_subtype.py — the OPMD subtype probe's out-of-fold score and ship verdict
artifacts/domain_report.md Generated by scripts/fit_domain_gate.py — the out-of-domain gate's false-rejection and detection rates

Retraining on new data

The full loop, in order. Steps 1–2 run locally on CPU in about half an hour; step 4 runs on a free Kaggle T4 in roughly 4–5 GPU-hours.

# 1. Build the training corpus: oral-region crops + masks in matching
#    coordinates, with every crop checked against the painted lesion.
python scripts/prepare_dataset.py --raw "G:\OPMD-triage-system-main\Updated Train data sets"

# 2. Join the label CSV, dedup, assign patient-grouped folds, assert composition.
python scripts/build_manifest.py
python scripts/shortcut_baseline.py       # the metadata floor, on full-res metadata

# 3. Upload images + masks + manifest + code (downscaled to 1024 px long side).
python scripts/kaggle_run.py setup --token C:\path\to\kaggle.json   # once
python scripts/kaggle_run.py push-data

# 4. Train on a GPU, poll, and pull the artifacts back.
python scripts/kaggle_run.py push-kernel --fresh
python scripts/kaggle_run.py status --watch
python scripts/kaggle_run.py fetch

# 5. Optional: re-fit the OPMD subtype probe against the new weights (local CPU).
#    Does not retrain anything; read artifacts/subtype_report.md and honour it.
python scripts/fit_subtype.py

# 6. Optional: re-calibrate the gate that rejects non-oral uploads (local CPU).
python scripts/fit_domain_gate.py --ood-dir "C:/Windows/Web/Wallpaper"

The manifest is deliberately built locally, on the full-resolution crops: its width/height/filesize columns are what the metadata-shortcut baseline measures the leak from, and rebuilding it on the resized upload would measure the resizer instead of the cameras.

build_manifest.py asserts the dataset composition (labels.EXPECTED_*) and fails loudly if it changed. That is the point — a swapped or half-copied dataset must not silently retrain and invalidate recorded metrics. If the data legitimately changed, update opmd/labels.py and re-run every experiment.


Quick start

Running a copy someone sent you

The batch files set the machine up themselves — nothing has to be installed by hand, and a package built by PACKAGE.bat needs no internet connection.

  1. Right-click the zip → Properties → tick Unblock → OK. Windows marks files that arrived from the internet, and that mark makes SmartScreen block the .bat files.
  2. Right-click the zip → Extract All…, into a folder you own. Do not run the files from inside the zip — Windows opens those from a temporary folder that it later deletes.
  3. Double-click SETUP.bat once. It finds or installs Python 3.11 and Node.js, builds .venv, installs every package from the bundled vendor/ folder, writes a .env with a fresh random JWT_SECRET, and creates the two demo accounts. Safe to run again at any time — it repairs whatever is missing and skips whatever is not.
  4. Double-click START_APP.bat. It waits for /api/health to answer before opening the browser, so a slow machine is fine.

Sign in with testm / pW123456 (midwife) or tests / pW123456 (surgeon). Change those before any real use.

File What it does
SETUP.bat One-time (repeatable) setup. Every launcher calls it automatically if something is missing.
START_APP.bat Starts backend + frontend and opens the browser.
start_backend.bat / start_frontend.bat Either half on its own.
ANNOTATE.bat The lesion-painting tool, on dataset/images.
PACKAGE.bat Developer only — builds the shareable folder + zip.

Sharing it with someone else

PACKAGE.bat

Copies every folder the app needs into ..\OPMD-v2-share\OPMD-v2, adds the pip wheels, node_modules and the Python/Node installers under vendor/, then zips it. Excluded from the copy: .venv, node_modules, __pycache__, uploads/, runs/, and — deliberately — your .env and *.db, so no signing key and no patient case records leave this machine. Downloads are cached in .package_cache/, so a second run is quick.

It refuses to build if artifacts/*.pt are missing or stub-sized, since a package without weights cannot predict anything.

Run locally

SETUP.bat then START_APP.bat does all of the below. By hand:

# Requires Python 3.11 (64-bit)
py -3.11 -m venv .venv
.venv\Scripts\activate
pip install -r requirements.txt

copy .env.example .env      # then edit JWT_SECRET

cd backend
python create_user.py --username dr_smith --role surgeon   # first surgeon only
uvicorn app:app --port 8000

In a second terminal:

cd frontend
npm install
npm run dev

Open http://localhost:5173.

Staff sign themselves up at /register and choose their role there — midwife or surgeon — so a self-registered account can be either. A surgeon account reads every patient case, so on any network wider than the clinic LAN set ALLOW_SELF_REGISTRATION=false in .env and provision accounts from a signed-in surgeon under Users instead.

Verify

python scripts/check_cam.py                       # localization sanity + overlay inspection
python scripts/check_roi_masks.py --sheet         # mucosa_mask() vs the painted masks
python scripts/smoke_test.py --username dr_smith --password ... --image "...\R-01-01.jpg"

Layout

OPMD-v2/
├── opmd/           shared package — imported by BOTH training and the backend
├── scripts/        prepare, manifest, shortcut baseline, training, evaluation, checks
├── kaggle/         the GPU kernel entry point
├── dataset/        prepared corpus: images/, masks/, the label CSVs, prepare_report.md
├── artifacts/      trained weights + labels + calibration + metrics report
├── backend/        FastAPI on SQLite
├── frontend/       React + Vite SPA
└── docs/           the documentation table above

opmd/ is split by dependency so the 3.9 GB inference machine never has to install pandas, scikit-learn or albumentations:

  • inference-safe: labels, preprocess, models, cam, localization, predict, subtype, domain
  • training-only: data, transforms, engine, metrics, calibrate

Hardware

Training Serving
Where Kaggle free T4 (16 GB), 30 GPU-h/week This machine
CPU/GPU T4 Intel i3-6100, 2 cores, no CUDA
RAM ~13 GB 3.9 GB
Full run ~4–5 GPU-hours —
Per-image inference — ~34 s measured (2 cores, 1800×4000 image)

Measured breakdown on the serving box: classification with 6 TTA views × 2 models 8.5 s, six Grad-CAM++ passes 20.8 s, fusion + boxes + full-resolution render 4.4 s. The lesion prior is read out of the Grad-CAM++ forward pass that already runs, so it costs no additional inference time.


Scope

This is triage decision-support. It does not diagnose. The highlighted regions are classifier attention narrowed by a learned lesion prior — measured against hand-painted masks, but still attention rather than a segmented boundary. The model knows three classes; benign oral pathology is absent from its training data entirely and will be forced into one of them.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages