Metadata-Version: 2.4
Name: wsi-toolbox
Version: 0.3.0
Summary: A comprehensive toolkit for Whole Slide Image processing, feature extraction, and clustering analysis
Project-URL: Homepage, https://github.com/technoplasm/wsi-toolbox
Project-URL: Repository, https://github.com/technoplasm/wsi-toolbox
Project-URL: Documentation, https://github.com/technoplasm/wsi-toolbox/blob/master/README.md
Author-email: Ken Enda <ken@endaaman.com>
License: MIT License
        
        Copyright (c) 2025 Ken Enda
        
        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.
License-File: LICENSE
Keywords: clustering,deep-learning,histopathology,pathology,wsi
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3.11
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
Requires-Python: >=3.11
Requires-Dist: h5py>=3.13.0
Requires-Dist: hdbscan>=0.8.40
Requires-Dist: imagecodecs>=2024.12.30
Requires-Dist: joblib>=1.4.2
Requires-Dist: leidenalg>=0.10.2
Requires-Dist: matplotlib>=3.9.4
Requires-Dist: networkx>=3.3
Requires-Dist: numpy<2
Requires-Dist: opencv-python-headless>=4.11.0.86
Requires-Dist: openpyxl>=3.1.5
Requires-Dist: openslide-python>=1.4.1
Requires-Dist: pandas>=2.2.3
Requires-Dist: pillow>=11.0.0
Requires-Dist: pydantic-autocli>=0.2.0
Requires-Dist: pyqt6>=6.8.1
Requires-Dist: python-igraph>=0.11.8
Requires-Dist: rich>=14.0.0
Requires-Dist: scikit-learn>=1.6.1
Requires-Dist: seaborn>=0.13.2
Requires-Dist: streamlit-aggrid>=0.3.4.post3
Requires-Dist: streamlit-antd-components>=0.3.2
Requires-Dist: streamlit>=1.43.2
Requires-Dist: taskipy>=1.14.1
Requires-Dist: tifffile>=2025.2.18
Requires-Dist: timm>=0.9.16
Requires-Dist: torch>=2.5.1
Requires-Dist: torchvision>=0.20.1
Requires-Dist: umap-learn>=0.5.7
Requires-Dist: zarr>=3
Provides-Extra: build
Requires-Dist: packaging; extra == 'build'
Requires-Dist: setuptools; extra == 'build'
Requires-Dist: torch; extra == 'build'
Requires-Dist: wheel; extra == 'build'
Provides-Extra: compile
Requires-Dist: flash-attn; extra == 'compile'
Description-Content-Type: text/markdown

# WSI Toolbox

> **Note**: This package is currently unstable. API may change without notice.

A comprehensive toolkit for Whole Slide Image (WSI) processing, feature extraction, and clustering analysis.

## Installation

```bash
# From PyPI
pip install wsi-toolbox

# From GitHub (latest)
pip install git+https://github.com/technoplasm/wsi-toolbox.git
```

## Quick Start

### As a Python Library

```python
import wsi_toolbox as wt

wt.set_default_model_preset('uni')
cmd = wt.Wsi2HDF5Command(patch_size=256)
result = cmd('input.ndpi', 'output.h5')
```

See [README_API.md](README_API.md) for API documentation.

### As a CLI Tool

After `pip install wsi-toolbox`, the CLI is available as `wsi-toolbox` or `wt`.
For development, use `uv run wt`.

```bash
# Extract tile patches from WSI into HDF5
wt wsi2h5 -i input.ndpi -o output.h5

# Extract features using foundation model
wt extract -i output.h5

# Run Leiden clustering on embeddings
wt cluster -i output.h5

# Compute UMAP projection
wt umap -i output.h5

# Compute PCA projection
wt pca -i output.h5

# Generate cluster overlay preview image
wt preview -i output.h5

# Generate PCA score heatmap preview
wt preview-score -i output.h5 -n pca1

# Show HDF5 file structure
wt show -i output.h5

# Export WSI to Deep Zoom Image format
wt dzi -i input.ndpi -o ./output

# Generate thumbnail from WSI
wt thumb -i input.ndpi
```

Each subcommand has detailed help: `wt <subcommand> --help`

### Streamlit Web Application

```bash
uv run task app
```

## HDF5 File Structure

WSI-toolbox stores all data in a single HDF5 file.

### Core Data

```
patches                    # Patch images: [N, H, W, 3]
coordinates                # Patch pixel coordinates: [N, 2]
```

### Metadata

Metadata is stored in **file attrs** (recommended):

```python
with h5py.File('output.h5', 'r') as f:
    mpp = f.attrs['mpp']
    patch_size = f.attrs['patch_size']
    patch_count = f.attrs['patch_count']
    # ...
```

Available attrs: `original_mpp`, `original_width`, `original_height`, `image_level`, `mpp`, `scale`, `patch_size`, `patch_count`, `cols`, `rows`

> Legacy `metadata/*` datasets are kept for backward compatibility but attrs are preferred.

### Model Features

```
{model}/features           # Patch features: [N, D]
                           #   uni: [N, 1024]
                           #   gigapath: [N, 1536]
                           #   virchow2: [N, 2560]
{model}/latent_features    # Latent features (optional): [N, L, D]
```

### Clustering & Analysis (Hierarchical)

Results are stored in a hierarchical namespace structure:

```
{model}/{namespace}/clusters     # Cluster labels: [N]
{model}/{namespace}/umap         # UMAP coordinates: [N, 2]
{model}/{namespace}/pca1         # PCA scores: [N] or [N, k]
```

**Namespace**:
- Single file: `default`
- Multiple files: `file1+file2+...` (auto-generated from filenames)

**Filter hierarchy**: Sub-clustering creates nested paths:

```
# Base clustering
uni/default/clusters

# Sub-cluster patches in clusters 1, 2, 3
uni/default/filter/1+2+3/clusters

# Further sub-cluster within that
uni/default/filter/1+2+3/filter/0+1/clusters
```

Each level stores its own clusters, umap, pca results independently.

### Dataset Writing Status

Large datasets (`patches`, `features`, `latent_features`) have a `writing` attribute to indicate write status (`True` during write, `False` when complete). Incomplete datasets are automatically deleted on error.

```python
ds = f['patches']  # or f['uni/features']
if ds.attrs.get('writing', False):
    raise RuntimeError('Dataset is incomplete')
```

## Features

- WSI processing (.ndpi, .svs, .tiff → HDF5)
- Feature extraction (UNI, Gigapath, Virchow2)
- Leiden clustering with UMAP visualization
- Preview generation (cluster overlays, PCA heatmaps)
- Type-safe command pattern with Pydantic results
- CLI, Python API, and Streamlit GUI

## Documentation

- [API Guide](README_API.md) - Python API documentation

## Development

```bash
# Clone and install
git clone https://github.com/technoplasm/wsi-toolbox.git
cd wsi-toolbox
uv sync

# Run CLI
uv run wt --help

# Run Streamlit app
uv run task app
```

### Optional: Gigapath support

```bash
uv sync --group gigapath
```

## License

MIT
