Metadata-Version: 2.4
Name: ugvnet
Version: 0.1.2
Summary: UGVNet: Universal Gradient Vision Network for Skin Disease Classification
Author: Mizanur Rahman Sajid
License-Expression: MIT
Project-URL: Homepage, https://github.com/mizanur-sajid/UGVNet
Project-URL: Repository, https://github.com/mizanur-sajid/UGVNet
Project-URL: Issues, https://github.com/mizanur-sajid/UGVNet/issues
Project-URL: Documentation, https://github.com/mizanur-sajid/UGVNet#readme
Keywords: deep-learning,skin-disease,dermatology,image-classification,convolutional-neural-network,pytorch,medical-imaging,computer-vision
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Healthcare Industry
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Scientific/Engineering :: Image Recognition
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
Classifier: Typing :: Typed
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: torch>=2.0
Requires-Dist: torchvision>=0.15
Requires-Dist: numpy>=1.24
Requires-Dist: Pillow>=10.0
Requires-Dist: tqdm>=4.65
Requires-Dist: scikit-learn>=1.3
Requires-Dist: matplotlib>=3.7
Requires-Dist: seaborn>=0.12
Provides-Extra: full
Requires-Dist: pandas>=2.0; extra == "full"
Requires-Dist: pyyaml>=6.0; extra == "full"
Requires-Dist: onnx>=1.14; extra == "full"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: ruff>=0.4; extra == "dev"
Requires-Dist: build>=1.0; extra == "dev"
Requires-Dist: twine>=5.0; extra == "dev"
Dynamic: license-file

<p align="center">
  <h1 align="center">UGVNet — Universal Gradient Vision Network</h1>
  <p align="center">
    A lightweight CNN architecture for dermatological image classification
  </p>
</p>

<p align="center">
  <a href="https://pypi.org/project/ugvnet/"><img src="https://img.shields.io/pypi/v/ugvnet?style=for-the-badge&logo=pypi&logoColor=white&color=3775A9" alt="PyPI"></a>
  <a href="https://www.python.org/downloads/"><img src="https://img.shields.io/badge/python-3.12+-3776AB?style=for-the-badge&logo=python&logoColor=white" alt="Python 3.12+"></a>
  <a href="https://pytorch.org/"><img src="https://img.shields.io/badge/PyTorch-2.x-EE4C2C?style=for-the-badge&logo=pytorch&logoColor=white" alt="PyTorch"></a>
  <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-22C55E?style=for-the-badge" alt="MIT License"></a>
</p>

---

**UGVNet** (Universal Gradient Vision Network) is a custom, lightweight convolutional neural network engineered for automated classification of common inflammatory and infectious skin diseases. The architecture combines depthwise separable convolutions, squeeze‑and‑excitation channel attention, and multi‑scale feature refinement to achieve efficient lesion‑level feature extraction from dermatoscopic images.

> **Status:** This project is under active research. Model performance is being iteratively improved through architecture refinements and training strategy optimization.

---

## Table of Contents

- [Key Features](#key-features)
- [Architecture](#architecture)
- [Installation](#installation)
- [Quick Start](#quick-start)
  - [Google Colab](#google-colab)
  - [Kaggle](#kaggle)
  - [Local](#local)
- [API Reference](#api-reference)
- [Dataset](#dataset)
- [Project Structure](#project-structure)
- [Results](#results)
- [Future Work](#future-work)
- [Citation](#citation)
- [Author](#author)
- [License](#license)

---

## Key Features

| Feature | Description |
|---|---|
| 🧠 **Custom Architecture** | Purpose‑built for dermatological image classification — not a fine‑tuned transfer‑learning model |
| ⚡ **Lightweight** | ~2.17 M trainable parameters; designed with edge‑deployment in mind |
| 🔬 **Depthwise Separable Convolutions** | Reduces computational cost while preserving representational capacity |
| 🎯 **Squeeze‑and‑Excitation Attention** | Adaptive channel recalibration to emphasize clinically relevant features |
| 🔀 **Multi‑Scale Feature Refinement** | Parallel 3×3, 5×5, and 7×7 branches capture textures, patterns, and broader context |
| 📦 **End‑to‑End Pipeline** | Config → data loading → training → evaluation → visualization in a single `pip install` |
| 🌐 **Environment‑Aware** | Auto‑detects Google Colab, Kaggle, and local environments; works seamlessly on any platform |
| 📊 **Built‑in Explainability** | Grad‑CAM heatmap generation for visual interpretation of model predictions |

---

## Architecture

UGVNet follows a sequential, five‑stage topology:

```
Input (3 × 224 × 224)
        │
   ┌────┴────┐
   │  Stem   │   2× ConvBNAct → 32 → 64 channels
   └────┬────┘
        │
   ┌────┴────┐
   │ Stage 1 │   2× UGVBlock (64 → 96), stride‑2 downsampling
   └────┬────┘
        │
   ┌────┴────┐
   │ Stage 2 │   2× UGVBlock (96 → 160), stride‑2 downsampling
   └────┬────┘
        │
   ┌────┴────┐
   │ Stage 3 │   2× UGVBlock (160 → 256), stride‑2 downsampling
   └────┬────┘
        │
   ┌────┴────────────┐
   │  Refinement     │   MultiScaleBlock + SE Attention + Residual
   └────┬────────────┘
        │
   Global Avg Pool → Dropout → Linear (256 → num_classes)
```

### Core Building Blocks

| Component | Description |
|---|---|
| **ConvBNAct** | Conv2D → BatchNorm → GELU activation |
| **DepthwiseSeparableConv** | Depthwise conv + pointwise conv for efficiency |
| **SqueezeExcitation** | Channel attention via global pooling → FC → Sigmoid gating |
| **UGVBlock** | DepthwiseSeparableConv → SE Attention → Residual addition → GELU |
| **MultiScaleBlock** | Parallel 3×3 / 5×5 / 7×7 branches → concatenation → 1×1 fusion |
| **FeatureRefinementBlock** | MultiScaleBlock → SE Attention → Residual addition → GELU |

All weights are initialized using Kaiming Normal (Conv2d), constant (BatchNorm), and Normal (Linear).

---

## Installation

> **Prerequisites:** Python 3.12+, pip, and (optionally) a CUDA‑capable GPU.

### From PyPI (recommended)

```bash
pip install ugvnet
```

### From Source (development)

```bash
git clone https://github.com/mizanur-sajid/UGVNet.git
cd UGVNet

python -m venv .venv
# Windows
.venv\Scripts\activate
# macOS / Linux
source .venv/bin/activate

pip install -e ".[dev,full]"
```

---

## Quick Start

UGVNet provides a complete pipeline that works out of the box on **Google Colab**, **Kaggle**, and **local machines**. Just point it to your dataset directory.

### Expected Dataset Structure

Your dataset should follow the standard ImageFolder layout:

```
your_dataset/
├── train/
│   ├── ClassA/
│   ├── ClassB/
│   └── ...
├── validation/          (also supports: val/, valid/)
│   └── ...
└── test/
    └── ...
```

### Google Colab

```python
# Install
!pip install ugvnet

# Mount Google Drive
from google.colab import drive
drive.mount('/content/drive')

# Train
from ugvnet import UGVNet, UGVNetConfig, Trainer, create_dataloaders

config = UGVNetConfig(
    data_dir="/content/drive/MyDrive/your-dataset/Preprocessed_Split",
    output_dir="/content/output",
    num_epochs=50,
    batch_size=32,
)
print(config)

model = UGVNet(num_classes=config.num_classes)
dataloaders = create_dataloaders(config)
trainer = Trainer(model, dataloaders, config)
history = trainer.fit()

# Visualize training curves
from ugvnet.visualization import plot_training_curves
plot_training_curves(history)

# Evaluate on test set
from ugvnet.evaluation import Evaluator
evaluator = Evaluator(model, dataloaders["test"], config)
results = evaluator.evaluate()
evaluator.save_report()
```

### Kaggle

```python
!pip install ugvnet

from ugvnet import UGVNet, UGVNetConfig, Trainer, create_dataloaders

config = UGVNetConfig(
    data_dir="/kaggle/input/your-dataset/Preprocessed_Split",
    output_dir="/kaggle/working/output",
    num_epochs=50,
)

model = UGVNet(num_classes=config.num_classes)
dataloaders = create_dataloaders(config)
trainer = Trainer(model, dataloaders, config)
history = trainer.fit()
```

### Local

```python
from ugvnet import UGVNet, UGVNetConfig, Trainer, create_dataloaders

config = UGVNetConfig(
    data_dir="./path/to/your/dataset",
    output_dir="./output",
)

model = UGVNet(num_classes=config.num_classes)
dataloaders = create_dataloaders(config)
trainer = Trainer(model, dataloaders, config)
history = trainer.fit()
```

---

## API Reference

### Configuration

```python
from ugvnet.config import UGVNetConfig

config = UGVNetConfig(
    # ── Paths ──
    data_dir="...",            # Root of your dataset (required)
    output_dir="./output",     # Where to save checkpoints, logs, reports

    # ── Model ──
    num_classes=6,             # Auto-detected from dataset folders
    dropout=0.3,

    # ── Data ──
    image_size=224,
    batch_size=32,
    num_workers=2,

    # ── Training ──
    num_epochs=50,
    learning_rate=1e-3,
    weight_decay=1e-4,
    label_smoothing=0.1,
    patience=10,               # Early stopping patience
    scheduler="cosine",        # "cosine" or "step"

    # ── Augmentation ──
    use_augmentation=True,     # Advanced augmentation for training

    # ── Reproducibility ──
    seed=42,

    # ── Resume ──
    resume_from=None,          # Path to checkpoint to resume training
)
```

### Model

```python
from ugvnet import UGVNet
from ugvnet.utils import count_parameters

model = UGVNet(num_classes=6, dropout=0.3)
info = count_parameters(model)
print(f"Parameters: {info['total']:,}")  # 2,166,328
```

### Training

```python
from ugvnet import Trainer

trainer = Trainer(model, dataloaders, config)
history = trainer.fit()
# Returns: {"train_loss": [...], "train_acc": [...], "val_loss": [...], "val_acc": [...], "lr": [...]}
```

### Evaluation

```python
from ugvnet.evaluation import Evaluator

evaluator = Evaluator(model, dataloaders["test"], config)
results = evaluator.evaluate()
evaluator.save_report()  # Saves classification_report.txt + confusion_matrix.csv
```

### Visualization

```python
from ugvnet.visualization import plot_training_curves, plot_confusion_matrix, plot_roc_curves

plot_training_curves(history, save_path="./output/curves.png")
plot_confusion_matrix(results["confusion_matrix"], class_names=[...])
plot_roc_curves(results["y_true"], results["y_proba"], class_names=[...])
```

### Explainability (Grad‑CAM)

```python
from ugvnet.evaluation import GradCAM

gradcam = GradCAM(model, target_layer=model.refinement)
heatmap = gradcam.generate(image_tensor, class_idx=2)
overlay = gradcam.overlay(heatmap, original_pil_image)
overlay.show()
```

### Utilities

```python
from ugvnet.utils import set_seed, get_device, setup_logger

set_seed(42)
device = get_device()           # Auto-detects CUDA / MPS / CPU
logger = setup_logger("my_run", log_dir="./logs")
```

---

## Dataset

Coming Soon!

---

## Project Structure

```
UGVNet/
├── ugvnet/                         # Source package (pip install ugvnet)
│   ├── models/
│   │   ├── layers.py               # ConvBNAct, DepthwiseSeparableConv, SqueezeExcitation
│   │   ├── blocks.py               # UGVBlock, MultiScaleBlock, FeatureRefinementBlock
│   │   └── ugvnet.py               # Main UGVNet model class
│   ├── training/
│   │   ├── trainer.py              # Training loop with validation & early stopping
│   │   ├── losses.py               # Loss functions (CrossEntropy + label smoothing)
│   │   └── scheduler.py            # LR scheduling (Cosine, StepLR)
│   ├── evaluation/
│   │   ├── evaluator.py            # Model evaluation pipeline
│   │   ├── metrics.py              # Accuracy, Precision, Recall, F1, ROC‑AUC
│   │   └── explainability.py       # Grad‑CAM visualization
│   ├── visualization/
│   │   └── plots.py                # Training curves, confusion matrix, ROC curves
│   ├── utils/
│   │   ├── helpers.py              # Device detection, checkpointing
│   │   ├── logger.py               # Console + file logging
│   │   └── seed.py                 # Reproducibility seed management
│   ├── augmentation.py             # Advanced data augmentation strategies
│   ├── preprocessing.py            # Image preprocessing pipeline
│   ├── dataset.py                  # Dataset loading & DataLoader creation
│   └── config.py                   # Central configuration management
│
├── pyproject.toml                  # Build configuration (PEP 621)
├── MANIFEST.in                     # Source distribution manifest
├── .gitignore
├── LICENSE                         # MIT License
└── README.md
```

---

## Results

Coming Soon!

---

## Future Work

- **Architecture refinement** — iterative improvements to UGVBlock design and training strategies to boost accuracy.
- **Dataset expansion** — incorporate rare dermatological conditions and larger public datasets.
- **Advanced augmentation** — explore CutMix, MixUp, and domain‑specific augmentation techniques.
- **Edge deployment** — optimize inference for mobile and embedded devices via quantization and pruning.
- **Explainability** — extend Grad‑CAM support with SHAP and other XAI techniques for clinical interpretability.

---

## Citation

If you use UGVNet in your research, please cite:

```bibtex
@software{sajid2026ugvnet,
  author       = {Mizanur Rahman Sajid},
  title        = {UGVNet: Universal Gradient Vision Network for Skin Disease Classification},
  year         = {2026},
  url          = {https://github.com/mizanur-sajid/UGVNet}
}
```

---

## Author

<table>
  <tr>
    <td align="center">
      <strong>Mizanur Rahman Sajid</strong>
      <br><br>
      <a href="https://github.com/mizanur-sajid"><img src="https://img.shields.io/badge/GitHub-181717?style=for-the-badge&logo=github&logoColor=white" alt="GitHub"></a>
      <a href="https://linkedin.com/in/mizanursajid"><img src="https://img.shields.io/badge/LinkedIn-0A66C2?style=for-the-badge&logo=linkedin&logoColor=white" alt="LinkedIn"></a>
    </td>
  </tr>
</table>

---

## License

This project is licensed under the [MIT License](LICENSE).
