Metadata-Version: 2.5
Name: nishan
Version: 0.1.0
Summary: Air-gapped biomedical, neuroimaging, microscopy, and EEG triage workstation powered by local Gemma models
Project-URL: Homepage, https://github.com/aslansd/nishan
Project-URL: Repository, https://github.com/aslansd/nishan
Project-URL: Issues, https://github.com/aslansd/nishan/issues
Author-email: Aslan Satary Dizaji <aslansatary@gmail.com>
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: air-gapped,differential-privacy,eeg,embeddinggemma,functiongemma,gemma,medgemma,microscopy,neuroimaging,vaultgemma
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Healthcare Industry
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
Requires-Python: >=3.11
Requires-Dist: daftar>=1.3.1
Requires-Dist: numpy>=1.26
Requires-Dist: pillow>=10.4
Requires-Dist: pydantic>=2.7
Requires-Dist: rich>=13.7
Requires-Dist: typer>=0.12
Provides-Extra: all
Requires-Dist: fastapi>=0.115; extra == 'all'
Requires-Dist: huggingface-hub>=0.25; extra == 'all'
Requires-Dist: lancedb>=0.15; extra == 'all'
Requires-Dist: matplotlib>=3.9; extra == 'all'
Requires-Dist: mne>=1.7; extra == 'all'
Requires-Dist: nibabel>=5.2; extra == 'all'
Requires-Dist: ollama>=0.4.7; extra == 'all'
Requires-Dist: pyarrow>=17.0; extra == 'all'
Requires-Dist: pydicom>=2.4; extra == 'all'
Requires-Dist: sentence-transformers[image]>=6.1.0; extra == 'all'
Requires-Dist: tifffile>=2024.7; extra == 'all'
Requires-Dist: torch>=2.4; extra == 'all'
Requires-Dist: transformers>=4.57; extra == 'all'
Requires-Dist: uvicorn>=0.32; extra == 'all'
Provides-Extra: api
Requires-Dist: fastapi>=0.115; extra == 'api'
Requires-Dist: uvicorn>=0.32; extra == 'api'
Provides-Extra: dev
Requires-Dist: httpx>=0.27; extra == 'dev'
Requires-Dist: pytest>=8.2; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Provides-Extra: eeg
Requires-Dist: matplotlib>=3.9; extra == 'eeg'
Requires-Dist: mne>=1.7; extra == 'eeg'
Provides-Extra: embed
Requires-Dist: huggingface-hub>=0.25; extra == 'embed'
Requires-Dist: sentence-transformers[image]>=6.1.0; extra == 'embed'
Requires-Dist: torch>=2.4; extra == 'embed'
Requires-Dist: transformers>=4.57; extra == 'embed'
Provides-Extra: microscopy
Requires-Dist: tifffile>=2024.7; extra == 'microscopy'
Provides-Extra: neuro
Requires-Dist: nibabel>=5.2; extra == 'neuro'
Requires-Dist: pydicom>=2.4; extra == 'neuro'
Provides-Extra: search
Requires-Dist: lancedb>=0.15; extra == 'search'
Requires-Dist: pyarrow>=17.0; extra == 'search'
Provides-Extra: triage
Requires-Dist: ollama>=0.4.7; extra == 'triage'
Description-Content-Type: text/markdown

# nishan (نشان / nişan)

**An air-gapped, local-first biomedical, neuroimaging, microscopy, and EEG triage workstation powered by specialized Gemma models.**

> **Etymology:** *Nishan* (**نشان** in Persian; **nişan** in Azerbaijani and Turkish) means *sign, mark, indicator, or biomarker*.

---

## Why `nishan`?

Hospital imaging archives, patient EEG/fMRI recordings, and pre-publication microscopy datasets cannot legally or ethically be uploaded to third-party cloud APIs. `nishan` runs **100% offline on local hardware** with a verifiable socket-level air-gap lock, deterministic PHI/metadata scrubbing, a zero-CDN local browser workstation, and full experimental provenance via `daftar`.

Instead of relying on a single general-purpose model, `nishan` composes specialized on-device Gemma models:

| Role | Model | Local Responsibility |
| :--- | :--- | :--- |
| **Multimodal Indexing** | **EmbeddingGemma 2** | Indexes 3D brain slices, confocal/WSI microscopy tiles, EEG diagnostic figures, and lab protocols into one shared local LanceDB vector space |
| **Visual & Clinical Triage** | **MedGemma 1.5 4B** | Performs structured multi-slice triage, abstention checks, citation grounding, and longitudinal comparison via loopback Ollama |
| **Tool Routing** | **FunctionGemma (270M)** | Maps natural-language workstation commands to strictly validated local Python tools |
| **Privacy-Safe Sharing** | **VaultGemma 1B** *(Optional)* | Differentially private base checkpoint ($\epsilon \le 2.0$) for Poisson-subsampled DP-SGD LoRA cohort adaptation with exact RDP certification |
| **Provenance** | **`daftar`** | Records immutable SHA-256 hashes, slice/tile coordinates, windowing specs, indexing runs, triage prompts, eval scorecards, and DP certificates |

---

## Supported Modalities

All modalities normalize automatically via `nishan ingest` into a single `CaseBundle` of $896 \times 896$ RGB `VisualUnit`s and de-identified `TextArtifact`s:

1. **3D Neuroimaging & Radiology (`Neuro3DAdapter`):** NIfTI (`.nii`, `.nii.gz`) and DICOM (`.dcm` file or series folder) with allowlist-only PHI scrubbing, MedGemma 1.5 3-channel Hounsfield Unit (HU) RGB windowing for CT, and $1\%\text{--}99.9\%$ percentile contrast normalization for MRI.
2. **Histopathology & Confocal Microscopy (`MicroscopyAdapter`):** Multi-channel confocal Z-stacks (`.ome.tif`, `.tif`) with per-channel $1\%\text{--}99.9\%$ normalization plus Max-Intensity Projection (MIP) and Z-planes, as well as large 2D brightfield/histopathology slides automatically tiled into informative $896 \times 896$ foreground patches with blank-glass rejection.
3. **Multimodal EEG + Reports (`EEGReportAdapter`):** `.edf` and `.fif` recordings (standalone or paired with `.txt`/`.md` clinical/lab notes) with subject-header and regex text PHI scrubbing, automatic PhysioNet EEGBCI channel standardization and 10–05 scalp montage fallback, quantitative canonical band-power summaries, and four headless $896 \times 896$ diagnostic figures (PSD, $2 \times 2$ scalp topomap / channel-band heatmap, highest-variance $10\text{ s}$ traces, and hotspot channel STFT spectrogram).

---

## Installation

### From PyPI

Install the full workstation stack (all three modalities, LanceDB, EmbeddingGemma 2, Ollama client, and FastAPI UI):

```bash
pip install "nishan[all]"
```

Or install only the extras you need:

```bash
pip install "nishan[neuro,search,triage,api]"
```

Available extras: `neuro`, `microscopy`, `eeg`, `search`, `embed`, `triage`, `api`, `all`, `dev`.

### From Source (with `uv`)

```bash
git clone https://github.com/aslansd/nishan.git
cd nishan
uv sync --extra all --extra dev
uv run --no-sync ruff check src tests
uv run --no-sync pytest -v
uv run --no-sync nishan verify-airgap
```

### Air-Gapped Docker Compose

Build and run `nishan` alongside a local Ollama container on an internal bridge network (`internal: true`, zero internet gateway) exposing the UI strictly on `127.0.0.1:8000`:

```bash
docker compose up --build
```

---

## Quickstart

### 1. One-Time Online Model Provisioning

Download the specialized Gemma models once while online, then disable network access:

```bash
# 1. EmbeddingGemma 2 (~1.53 GB, Apache 2.0)
nishan fetch-embed-model

# 2. MedGemma 1.5 4B (Q4_K_M ~3.3 GB) & FunctionGemma (270M ~301 MB) via Ollama
ollama pull medgemma1.5:4b
ollama pull functiongemma

# 3. Optional: VaultGemma 1B for differentially private cohort LoRA adaptation
nishan fetch-vault-model
```

### 2. Ingest & Index Cases Across All Three Modalities

Generate offline synthetic phantoms (or fetch the real public cohort below) and index them into local LanceDB:

```bash
# Synthetic quickstart across all three modalities
nishan synth-nifti --out sample_data/phantom_t0.nii.gz --lesion-radius 3.0
nishan synth-nifti --out sample_data/phantom_t1.nii.gz --lesion-radius 7.0
nishan synth-microscopy
nishan synth-eeg

nishan ingest sample_data/phantom_t0.nii.gz --case-id phantom-t0 --max-units 8
nishan ingest sample_data/phantom_t1.nii.gz --case-id phantom-t1 --max-units 8
nishan ingest sample_data/phantom_confocal.ome.tif --case-id confocal-01 --max-units 6
nishan ingest sample_data/phantom_eeg_case --case-id eeg-01 --max-units 4

# Index all cases into local LanceDB with EmbeddingGemma 2 (256-d MRL)
nishan index --backend embeddinggemma2 --dim 256
```

### 3. Launch the Air-Gapped Split-Pane Workstation UI

```bash
nishan serve \
  --embed-backend embeddinggemma2 \
  --vlm-backend medgemma \
  --router-backend functiongemma \
  --port 8000
```

Open **`http://127.0.0.1:8000`** in any browser (zero external CDN calls; works with Wi-Fi disabled):

* **Left Pane:** Modality filter, case browser, interactive $896 \times 896$ slice/tile/EEG scrubber, thumbnail strip, and one-click **"Find Similar"** image-to-image search.
* **Center Pane:** **FunctionGemma** natural-language command bar, **MedGemma 1.5** structured triage cards with clickable `unit_id` chips that jump the viewer directly to cited slices, longitudinal prior-vs-current diff panel, and scrubbed text artifacts.
* **Right Pane:** **EmbeddingGemma 2** cross-modal search bar (filtered by modality and item kind) and live **`daftar`** provenance ledger.

### 4. CLI Workflows, Offline Evaluation & DP-LoRA Cohort Sharing

```bash
# Cross-modal search, triage, longitudinal diff, and FunctionGemma routing via CLI
nishan search --query "occipital alpha rhythm and frontal theta burst" --backend embeddinggemma2
nishan triage eeg-01 --vlm-backend medgemma --embed-backend embeddinggemma2
nishan compare phantom-t0 phantom-t1 --vlm-backend medgemma
nishan ask "Compare prior phantom-t0 against follow-up phantom-t1" \
  --router-backend functiongemma --vlm-backend medgemma --embed-backend embeddinggemma2

# Offline multi-modality evaluation suite (saves JSON + Markdown scorecards in nishan_workspace/evals/)
nishan eval --embed-backend mock --vlm-backend mock
nishan eval --embed-backend embeddinggemma2 --vlm-backend medgemma

# Differentially private cohort corpus + DP-SGD LoRA adapter export + privacy certificate
nishan dp-cohort --train --mode smoke --steps 6 --noise-multiplier 2.0
nishan dp-cohort --train --mode vaultgemma --steps 10 --noise-multiplier 1.5

# Inspect immutable daftar provenance history
daftar list
```

---

## Real Public Cohort Validation

`scripts/fetch_public_cohort.py` downloads a compact (~20 MB, no login) open-access multi-modality benchmark cohort for realistic offline testing:

```bash
uv pip install nilearn
uv run --no-sync python scripts/fetch_public_cohort.py
```

| Case ID | Public Dataset & Modality | Visual Units | Indexed Vectors | Observed Local MedGemma 1.5 4B Behavior |
| :--- | :--- | ---: | ---: | :--- |
| `mni152-baseline` / `mni152-followup` | 1 mm MNI152 T1w human brain MRI + controlled focal white-matter lesion (`neuro_3d`) | $10$ each | $22$ | Valid structured longitudinal diff; cautiously labeled `indeterminate` (demonstrating need for clinical windowing/calibration and domain fine-tuning) |
| `allen-cells3d` | Allen Institute for Cell Science 3D confocal Z-stack (`60 x 2 x 256 x 256`, `microscopy`) | $8$ (MIP + $7$ Z) | $9$ | Accurately described round/oval cellular morphology, green intracellular fluorescence, and red membrane/boundary staining with 4 grounded findings and 4 unassessable aspects |
| `eeg-eyes-open` / `eeg-eyes-closed` | PhysioNet EEGMMIDB Subject 001, Runs 01 & 02 (`64`-ch 10–10 EDF, `eeg_multimodal`) | $4$ each | $12$ | Auto-standardized EEGBCI channels into $2 \times 2$ scalp topomaps; structured diff identified alpha ($8\text{--}13\text{ Hz}$) and beta ($13\text{--}30\text{ Hz}$) shifts across PSD and topomaps while conservatively returning `indeterminate` |

---

## Baseline Offline Evaluation Results

Observed local benchmark results (`nishan eval`) across the deterministic 6-case multi-modality test harness (3D neuroimaging, confocal microscopy, EEG + PHI notes, blank-slice abstention, and longitudinal pairs):

| Metric | Mock Baseline | Local Gemma Stack (`embeddinggemma-2` + `medgemma1.5:4b`) |
| :--- | ---: | ---: |
| PHI Scrubbing Pass Rate | 100.0% | 100.0% |
| Structured JSON Validity Rate | 100.0% | 100.0% |
| Blank-Slice Abstention Rate | 100.0% | 100.0% |
| Citation Grounding Pass Rate | 100.0% | 100.0% |
| Cross-Modal Text Recall@3 | 100.0% | 100.0% |
| Image Self-Retrieval@1 | 100.0% | 100.0% |
| Longitudinal Direction Accuracy *(synthetic phantoms)* | 100.0% | 0.0%* |
| Mean Triage Latency (4 units/case) | 511.5 ms | 52,016.2 ms |

*\*Note on longitudinal direction accuracy:* On both geometric phantoms and uncalibrated synthetic-lesion MNI152 pairs, `medgemma1.5:4b` (Q4_K_M) tends to select `overall_change = "indeterminate"` even when its rationale describes visual differences. Evaluating on registered clinical radiology pairs and/or task-specific QLoRA adaptation is recommended before relying on automated longitudinal labels.

---

## Repository Structure

```text
nishan/
├── pyproject.toml
├── LICENSE                     # Apache-2.0
├── Dockerfile                  # Air-gapped container image
├── docker-compose.yml          # Isolated internal-network compose stack (nishan + ollama)
├── README.md
├── docs/
│   └── ARCHITECTURE.md         # Engineering contracts, RDP math, and module specs
├── scripts/
│   └── fetch_public_cohort.py  # One-time fetcher for MNI152, Allen cells3d, PhysioNet EEG
├── src/
│   └── nishan/
│       ├── __init__.py
│       ├── airgap.py           # Offline env flags + loopback-only socket guard
│       ├── schema.py           # Unified CaseBundle, VisualUnit, TextArtifact models
│       ├── embeddings.py       # EmbeddingGemma 2 (440M text+vision) + deterministic mock
│       ├── store.py            # Local LanceDB multimodal vector store (lazy optional import)
│       ├── triage.py           # MedGemma 1.5 4B triage, longitudinal diff, guardrails
│       ├── router.py           # FunctionGemma (270M) local dispatcher + Pydantic validation
│       ├── evals.py            # Multi-modality offline evaluation harness & scorecards
│       ├── privacy.py          # Scrubbed DP cohort corpus, RDP accountant & DP-SGD LoRA
│       ├── api.py              # Air-gapped FastAPI server (127.0.0.1) + daftar ledger API
│       ├── cli.py              # Typer CLI for ingest, index, search, triage, eval, dp-cohort, serve
│       ├── ui/
│       │   └── index.html      # Zero-CDN split-pane workstation SPA
│       └── adapters/
│           ├── __init__.py
│           ├── base.py         # ModalityAdapter abstract base class
│           ├── utils.py        # Hashing, letterboxing, contrast norm, text PHI scrubbing
│           ├── neuro3d.py      # NIfTI + DICOM series ingestion adapter
│           ├── microscopy.py   # Confocal OME-TIFF Z-stack + 2D WSI tiling adapter
│           ├── eeg.py          # MNE EDF/FIF EEG + auto-montage + scrubbed report adapter
│           └── registry.py     # Automatic ModalityAdapter resolution
└── tests/
    ├── test_step1_ingest.py
    ├── test_step2_index_search.py
    ├── test_step3_triage_router.py
    ├── test_step4_microscopy_eeg.py
    └── test_step5_workstation_eval_dp.py
```

---

## Safety & Research Disclaimer

`nishan` is a **research triage, labeling, and quality-assurance workstation**. It is **not** a medical device and is **not** intended for clinical diagnosis, treatment, or patient management. All model outputs require review by qualified domain experts, in accordance with Google's Health AI Developer Foundations terms of use.