Metadata-Version: 2.4
Name: prost-softnet
Version: 1.2.2
Summary: Reproducible cascade-CNN software for prostate MRI zonal segmentation (whole gland / central gland / peripheral zone)
Author: Saqib Iqbal, Ghzanfar Farooq Saddiqui, Muhammad Tausif, Muhammad Zafar Iqbal
License: MIT License
        
        Copyright (c) 2026 Saqib Iqbal and Muhammad Tausif
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://github.com/ProST-SoftNet/ProST-SoftNet-v2
Project-URL: Documentation, https://github.com/ProST-SoftNet/ProST-SoftNet-v2#readme
Project-URL: Repository, https://github.com/ProST-SoftNet/ProST-SoftNet-v2
Project-URL: Issues, https://github.com/ProST-SoftNet/ProST-SoftNet-v2/issues
Project-URL: Demo, https://huggingface.co/spaces/ProST-SoftNet/ProST-SoftNet
Keywords: prostate cancer,MRI,deep learning,vision transformer,medical imaging
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Healthcare Industry
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: torch>=2.2.0
Requires-Dist: torchvision>=0.17.0
Requires-Dist: timm>=0.9.12
Requires-Dist: einops>=0.7.0
Requires-Dist: numpy>=1.26.0
Requires-Dist: pandas>=2.2.0
Requires-Dist: scikit-learn>=1.4.0
Requires-Dist: scikit-image>=0.22.0
Requires-Dist: albumentations>=1.4.0
Requires-Dist: SimpleITK>=2.3.1
Requires-Dist: nibabel>=5.2.0
Requires-Dist: pydicom>=2.4.4
Requires-Dist: Pillow>=10.2.0
Requires-Dist: opencv-python-headless>=4.9.0
Requires-Dist: tqdm>=4.66.0
Requires-Dist: pyyaml>=6.0.1
Requires-Dist: omegaconf>=2.3.0
Requires-Dist: matplotlib>=3.8.0
Requires-Dist: seaborn>=0.13.0
Requires-Dist: scipy>=1.12.0
Requires-Dist: grad-cam>=1.4.8
Requires-Dist: onnx>=1.16.0
Requires-Dist: onnxruntime>=1.17.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: pytest-cov>=5.0.0; extra == "dev"
Requires-Dist: black>=24.0.0; extra == "dev"
Requires-Dist: ruff>=0.3.0; extra == "dev"
Requires-Dist: fastapi>=0.111.0; extra == "dev"
Requires-Dist: httpx>=0.27.0; extra == "dev"
Requires-Dist: uvicorn[standard]>=0.29.0; extra == "dev"
Requires-Dist: python-multipart>=0.0.9; extra == "dev"
Provides-Extra: train
Requires-Dist: wandb>=0.16.0; extra == "train"
Requires-Dist: tensorboard>=2.16.0; extra == "train"
Requires-Dist: lightning>=2.2.0; extra == "train"
Provides-Extra: notebook
Requires-Dist: jupyter>=1.0.0; extra == "notebook"
Requires-Dist: ipywidgets>=8.0.0; extra == "notebook"
Dynamic: license-file

# ProST-SoftNet

**Reproducible cascade-CNN software for prostate MRI zonal segmentation (whole gland / central gland / peripheral zone)**

[![CI](https://github.com/ProST-SoftNet/ProST-SoftNet-v2/actions/workflows/ci.yml/badge.svg)](https://github.com/ProST-SoftNet/ProST-SoftNet-v2/actions)
[![PyPI](https://img.shields.io/pypi/v/prost-softnet.svg)](https://pypi.org/project/prost-softnet/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)

*Zenodo DOI is not minted yet — see [Status](#status) below before citing this work.*

Install the classification package with `pip install prost-softnet`.

---

ProST-SoftNet segments the prostate into **whole gland (WG)**, **central gland (CG)**, and **peripheral zone (PZ)** from multi-parametric MRI, using a cascade 3-D CNN pipeline built around [Prostate158](https://github.com/kbressem/prostate158) — the public benchmark of 158 prostate MRI exams with expert zonal and lesion annotations ([Zenodo archive, DOI 10.5281/zenodo.6481141](https://zenodo.org/record/6481141)).

On the held-out 19-case test split, the pipeline reaches a **peripheral-zone Dice of 0.7513 — above the 0.7473 human inter-reader agreement measured on the same data.** The peripheral zone is the hardest of the three to segment and the region where most clinically significant prostate cancers arise, so it is reported separately rather than averaged away. Full results are in [Zone-Segmentation Results](#zone-segmentation-results).

Every trained checkpoint, per-iteration ablation log, and per-case metric CSV is committed to this repository rather than described from the outside, so the numbers here can be recomputed and checked directly rather than taken on faith. An interactive dashboard ([`demo/`](demo/)) lets you browse the results or upload a new patient's MRI and run the pipeline yourself.

The repository also ships `prostsoftnet`, a pip-installable hybrid **CNN-ViT** classifier for benign/malignant prediction with Grad-CAM/Attention-Rollout explainability and ONNX export. It is complete and unit-tested, but **has not been trained to completion on Prostate158 and carries no benchmark results** — it is included as reusable, extensible architecture, not as a validated classifier. See [Status](#status).

## What's in this repo

| Area | Where | What it is |
|---|---|---|
| **Zone-segmentation pipeline** *(the primary contribution)* | [`checkpoints/prost_fusenet_optimal/`](checkpoints/prost_fusenet_optimal/) | Cascade 3-D CNN (frozen whole-gland localizer → cropped zone refinement), multiple training iterations with committed results and per-case metrics, tracked via Git LFS |
| Classification package *(not benchmarked)* | [`prostsoftnet/`](prostsoftnet/) | Hybrid CNN-ViT (EfficientNetV2-S + ViT + cross-attention) for benign/malignant classification — data loading, training, metrics, explainability, ONNX export. Complete and unit-tested; **no trained checkpoint or benchmark results** |
| Interactive dashboard | [`demo/`](demo/) | FastAPI server + static frontend: pre-generated segmentation results, ROC/PR/training curves, and a live tab to upload a new patient's MRI and run the pipeline |
| Full-stack web app | [`web-app/`](web-app/), [`php-api/`](php-api/), [`ml-api/`](ml-api/) | React + PHP/MySQL + FastAPI application wrapping the classification model for doctor-facing use |
| HuggingFace Spaces demo | [`hf_spaces/`](hf_spaces/) | Gradio app for the zonal-segmentation pipeline, built and locally verified — pending PRO-tier compute to deploy live, see [Status](#status). A static landing page is live at [huggingface.co/spaces/MuhammadTausif/prost-softnet-v2-demo](https://huggingface.co/spaces/MuhammadTausif/prost-softnet-v2-demo) in the meantime. |
| Illustrative notebooks | [`notebooks/`](notebooks/) | Data preparation, training/evaluation, and inference/explainability — executed end to end on every CI run, not just committed as static files |

---

## Status

Being upfront about what's real right now, rather than what the badges of a finished project usually imply:

- **Working and benchmarked**: the zone-segmentation pipeline — its checkpoints and reported metrics (recomputed from the committed per-case CSVs, not hand-typed), the dashboard, and the 106-test suite covering both the segmentation pipeline and the classification package.
- **Complete but not benchmarked**: the `prostsoftnet` classification package. Its training, evaluation, and explainability code is finished and unit-tested, but it **has never been run to completion on the full Prostate158 dataset**, so no trained checkpoint and no accuracy numbers exist. It is shipped as reusable architecture, and this README does not report classification results because there are none to report.
- **Not yet done**: no Zenodo DOI has been minted for this repository; the interactive HuggingFace Spaces demo (live per-patient inference) is built and passes an end-to-end smoke test locally, but is not yet deployed live — HuggingFace's free tier stopped hosting Gradio/Docker Spaces on CPU compute, which now requires a PRO subscription. A static landing page (results table + links, no live inference) is deployed at [huggingface.co/spaces/MuhammadTausif/prost-softnet-v2-demo](https://huggingface.co/spaces/MuhammadTausif/prost-softnet-v2-demo) in the meantime. The package **is** published to PyPI (`pip install prost-softnet`) as of v1.2.1.
- **Repository visibility**: this repository is currently private to the ProST-SoftNet organization while the above items are finished. It will be made public before submission, per the venue's requirement that the code be openly accessible.

---

## Zone-Segmentation Results

Held-out test split of Prostate158 (19 cases). The pipeline runs in two stages: a frozen Stage-A localizer finds the gland bounding box, then a Stage-B 3-D U-Net segments WG and CG at native crop resolution; PZ is derived as `WG AND NOT CG`.

| Model | WG Dice | CG Dice | PZ Dice | Zone-mean Dice |
|---|---|---|---|---|
| Direct 3-class cascade | 0.8941 | 0.8642 | 0.7308 | 0.7975 |
| **Single-model, PZ-derived cascade — current best** | **0.8926** | **0.8676** | **0.7483** | **0.8079** |
| Confidence-weighted fusion of the PZ-derived cascade and a second refinement model, no extra training | 0.8910 | 0.8619 | 0.7513 | 0.8066 |
| Human inter-reader agreement (reference ceiling) | — | 0.8726 | 0.7473 | — |

The single-model, PZ-derived cascade is the checkpoint the dashboard's live "Zonal Analysis" tab runs. The peripheral zone is the hardest of the three by a wide margin — it's small, has a less distinct boundary on T2W, and is exactly where most clinically significant cancers arise, so tracking it separately from whole-gland Dice matters more than a single averaged number would suggest. Full iteration-by-iteration history, what changed between each one, and why some approaches didn't help are documented in [`checkpoints/prost_fusenet_optimal/README.md`](checkpoints/prost_fusenet_optimal/README.md).

### A note on the classification package

The `prostsoftnet` classifier is **deliberately not benchmarked here.** Its training, evaluation, and explainability code is complete and unit-tested, but it has never been run to completion on the full Prostate158 dataset — so no trained checkpoint exists and there are no accuracy numbers to report. Rather than publish a hastily-trained figure, this repository reports only what it can substantiate: the zone-segmentation results above.

The package remains fully usable for anyone who wants to train it themselves — see [`docs/classification-package.md`](docs/classification-package.md) — and `prost-evaluate` will produce the standard clinical metrics (AUROC, sensitivity, specificity, PPV, NPV with bootstrap confidence intervals) once a checkpoint exists.

---

## Try the dashboard

No GPU needed to browse the pre-generated results; the live "Zonal Analysis" tab needs the trained checkpoints already present in `checkpoints/prost_fusenet_optimal/`.

```bash
cd demo
pip install -r requirements.txt
python server.py
# open http://localhost:8000
```

The dashboard opens on the zone-segmentation model comparison and statistics tabs. A third tab accepts a new patient's T2W/DWI/ADC MRI — NIfTI or a DICOM series as a ZIP — runs the cascade pipeline on it, and returns WG/CG/PZ volumes, overlay figures, and a plain-language, explicitly non-diagnostic description grounded in a small retrieval-augmented knowledge base (PI-RADS anatomy references, not a diagnosis).

### Zone-Segmentation Models

Side-by-side test-set metrics for each trained checkpoint, per-zone ASD/HD95 distance metrics, and pre-generated ground-truth-vs-prediction overlays for individual test cases.

![Zone-Segmentation Models tab: metrics comparison table, distance metrics, and a ground-truth vs prediction overlay for one test case](https://raw.githubusercontent.com/ProST-SoftNet/ProST-SoftNet-v2/master/docs/images/dashboard-zone-models.png)

### Zone Statistics

Whole-gland segmentation compared against ground truth on real T2W and DWI slices (red = ground truth, yellow = prediction, green = overlap), per-model Dice/IoU/precision/recall, voxel-level ROC and precision-recall curves computed from raw per-voxel probabilities across all 19 test cases, and training history.

![Zone Statistics tab: T2W and DWI overlays comparing ground truth against both models, per-model gland metrics, ROC and precision-recall curves, and training loss and validation Dice curves](https://raw.githubusercontent.com/ProST-SoftNet/ProST-SoftNet-v2/master/docs/images/dashboard-zone-statistics.png)

---

## Installation

The `prostsoftnet` classification package is on PyPI:

```bash
pip install prost-softnet
```

To work with the full repository — the zone-segmentation checkpoints, dashboard, tests, and notebooks — install from source instead:

```bash
git clone https://github.com/ProST-SoftNet/ProST-SoftNet-v2.git
cd ProST-SoftNet-v2
pip install -e ".[dev,train,notebook]"
```

**Requirements**: Python 3.10 or newer, PyTorch 2.2+, CUDA 11.8+ recommended for training (CPU works for inference and for browsing the dashboard).

---

## The `prostsoftnet` classification package

Alongside the segmentation pipeline, this repository ships a pip-installable hybrid **CNN-ViT** classifier (EfficientNetV2-S + 6-layer ViT + cross-attention fusion) for benign/malignant prediction, with Grad-CAM and Attention-Rollout explainability, ONNX export, and a CLI (`prost-train`, `prost-evaluate`, `prost-predict`, `prost-export`).

As noted in [Status](#status), it has **not been trained to completion and carries no benchmark results** — it is included as reusable, extensible architecture rather than as a validated classifier.

**Full architecture description, quick start, training/evaluation/inference commands, and explainability API: [`docs/classification-package.md`](docs/classification-package.md).**

---

## Tests and illustrative examples

```bash
pytest tests/
```

106 tests pass in a clean environment, covering each part of the software in turn:

| Area | Tests | What they check |
|---|---|---|
| Zone-segmentation pipeline | 29 | Model architectures, confidence-weighted fusion, and an end-to-end run of the full pipeline against the real trained checkpoints |
| Dashboard HTTP API | 22 | Every route group, query-parameter validation, and that malformed uploads are refused rather than reaching inference |
| Command-line interface | 22 | All four `prost-*` entry points — argument handling, and that the installed console scripts resolve |
| Classification package | 33 | Forward pass, metrics, preprocessing, Grad-CAM, and that the default (pretrained) backbone loads correctly |

CI runs the suite on Python 3.10 and 3.11 on every push, and lints the whole repository with `ruff check .`.

The tests that need the trained checkpoints skip cleanly rather than fail when those Git LFS files aren't present, so a fresh clone without `git lfs pull` still passes.

The three notebooks in [`notebooks/`](notebooks/) are executed end to end by a separate CI job (`nbconvert --execute`) rather than just sitting in the repo unverified — each one falls back to a tiny synthetic dataset (`scripts/make_synthetic_prostate158.py`) and one or two training epochs under a `PROST_SMOKE_TEST` environment variable, so they run in seconds on a CPU-only runner without needing the real ~2 GB dataset:

1. [`01_data_preparation.ipynb`](notebooks/01_data_preparation.ipynb) — loading, preprocessing, and augmenting Prostate158
2. [`02_training_and_evaluation.ipynb`](notebooks/02_training_and_evaluation.ipynb) — training the classifier and computing clinical metrics with bootstrap confidence intervals
3. [`03_inference_and_explainability.ipynb`](notebooks/03_inference_and_explainability.ipynb) — running inference and generating Grad-CAM / Attention Rollout visualizations

---

## Project structure

```
ProST-SoftNet-v2/
├── checkpoints/prost_fusenet_optimal/  # zone-segmentation checkpoints + per-case metrics, Git LFS
├── demo/                               # zone-segmentation dashboard (FastAPI + static frontend)
│   ├── server.py
│   ├── wgcgpz_inference.py             # live WG/CG/PZ cascade inference
│   ├── zone_pipeline/                  # segmentation model definitions (self-contained)
│   ├── rag_report.py                   # retrieval-augmented report generation
│   └── static/index.html
├── hf_spaces/                          # Gradio demo of the segmentation pipeline (not yet deployed)
├── prostsoftnet/                       # classification package (pip installable, not benchmarked)
│   ├── data/                           # Prostate158 dataset, DICOM/NIfTI loading, augmentation
│   ├── models/                         # hybrid CNN-ViT architecture, losses
│   ├── training/                       # training loop, evaluation, ONNX export
│   ├── utils/                          # Grad-CAM, Attention Rollout, metrics, visualization
│   └── cli.py                          # prost-train / prost-evaluate / prost-predict / prost-export
├── web-app/                            # React frontend for the classification web app
├── php-api/                            # PHP REST API (auth, predict proxy, history, admin)
├── ml-api/                             # FastAPI ONNX inference server for the web app
├── notebooks/                          # 3 illustrative notebooks, executed in CI
├── tests/                              # pytest suite (106 tests)
├── docs/                               # architecture, classification package, API reference,
│                                       #   setup, deployment, user/admin manuals
├── .github/workflows/                  # CI and release automation
├── CITATION.cff, codemeta.json         # machine-readable citation and software metadata
└── pyproject.toml                      # package configuration
```

---

## Code metadata

| # | Field | Value |
|---|---|---|
| C1 | Current code version | 1.2.1 |
| C2 | Permanent link to code/repository used for this version | https://github.com/ProST-SoftNet/ProST-SoftNet-v2 (currently private — see [Status](#status)) |
| C3 | Permanent link to reproducible capsule | Not yet available |
| C4 | Legal code license | MIT |
| C5 | Code versioning system used | git, with Git LFS for model checkpoints |
| C6 | Software code languages, tools, and services used | Python, PyTorch, FastAPI, TypeScript/React, PHP |
| C7 | Compilation requirements, operating environments, dependencies | Python ≥ 3.10, PyTorch ≥ 2.2 (CUDA 11.8+ optional); full list in [`pyproject.toml`](pyproject.toml) |
| C8 | If available, link to developer documentation/manual | [`docs/`](docs/) (architecture, classification package, API reference, setup, deployment, user/admin manuals) |
| C9 | Support email for questions | saqibiqbal@cs.qau.edu.pk |

---

## Citation

No DOI has been minted for this software yet — a Zenodo release is planned, at which point this section and `CITATION.cff` will be updated with the real DOI. Until then, cite the repository directly, or `prost-softnet` on PyPI if referring specifically to the classification package:

```bibtex
@software{iqbal_prostsoftnet,
  title  = {ProST-SoftNet: Reproducible Cascade-CNN Software for Prostate MRI Zonal Segmentation},
  author = {Iqbal, Saqib and Saddiqui, Ghzanfar Farooq and Tausif, Muhammad and Iqbal, Muhammad Zafar},
  url    = {https://github.com/ProST-SoftNet/ProST-SoftNet-v2},
  note   = {Classification package also available via PyPI: pip install prost-softnet}
}
```

If you use the Prostate158 dataset itself, please also cite the [original dataset paper and repository](https://github.com/kbressem/prostate158).

---

## Authors

- **Saqib Iqbal** — Quaid-i-Azam University — model design, zone-segmentation methodology, training and evaluation
- **Muhammad Tausif** — software architecture and implementation: the classification package, the dashboard, the full-stack web application, and CI/testing infrastructure

---

## License

MIT — see [LICENSE](LICENSE).
