A-Laabid's picture
Update README.md
57e0956 verified
|
Raw
History Blame Contribute Delete
7.16 kB
metadata
title: Pneumonia Detection API Backend
emoji: 🫁
colorFrom: blue
colorTo: indigo
sdk: docker
app_file: app.py
pinned: false

Pneumonia Detection API Backend

Production-ready FastAPI backend for dual-model pneumonia classification from chest X-ray images.

πŸ—οΈ Architecture

This API uses two independent models working in parallel:

  1. SVM Classifier (Classical ML)

    • Hand-crafted features: LBP (Local Binary Patterns) + HOG (Histogram of Oriented Gradients)
    • Preprocessing: CLAHE enhancement β†’ Feature extraction
    • Fast inference (~50ms)
  2. DenseNet121 (Deep Learning)

    • Transfer learning from ImageNet
    • Fine-tuned on pneumonia dataset
    • Preprocessing: ImageNet normalization
    • Moderate inference (~200ms on CPU)

πŸ“ Project Structure

pneumonia-detection-backend/
β”‚
β”œβ”€β”€ app.py                     # Main FastAPI application
β”œβ”€β”€ requirements.txt           # Python dependencies
β”œβ”€β”€ README.md                  # This file
β”‚
β”œβ”€β”€ models/                    # Model files (add your trained models here)
β”‚   β”œβ”€β”€ svm_model.pkl         # Trained SVM model
β”‚   └── best_densenet121.pth  # Trained DenseNet121 weights
β”‚
β”œβ”€β”€ utils/                     # Preprocessing & utilities
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ preprocess_svm.py     # SVM preprocessing pipeline
β”‚   β”œβ”€β”€ preprocess_cnn.py     # CNN preprocessing pipeline
β”‚   └── model_loader.py       # Model loading utilities
β”‚
└── tests/                     # Test scripts (optional)
    └── test_api.py

πŸš€ Setup Instructions

1. Prerequisites

  • Python 3.8 or higher
  • pip (Python package manager)

2. Clone/Download Repository

cd pneumonia-detection-backend

3. Create Virtual Environment (Recommended)

# Create virtual environment
python -m venv venv

# Activate virtual environment
# On Linux/Mac:
source venv/bin/activate
# On Windows:
venv\Scripts\activate

4. Install Dependencies

pip install -r requirements.txt

Note: Installing PyTorch may take several minutes. The requirements include CPU-only PyTorch. For GPU support, see PyTorch Installation Guide.

5. Add Model Files

Place your trained model files in the models/ directory:

models/
β”œβ”€β”€ svm_model.pkl              # Your trained SVM model
└── best_densenet121.pth       # Your trained DenseNet121 weights

Important: Model files are NOT included in this repository. You must train them using the provided Jupyter notebooks or use your own trained models.

6. Verify Model Files

python -m utils.model_loader

Expected output: ``` Model File Verification:

svm_exists: True svm_path: .../models/svm_model.pkl cnn_exists: True cnn_path: .../models/best_densenet121.pth


## ▢️ Running the API

### Development Mode (with auto-reload)

```bash
python app.py

Production Mode

uvicorn app:app --host 0.0.0.0 --port 8000 --workers 4

The API will be available at:

πŸ“– API Documentation

Once running, access interactive API documentation:

πŸ”Œ API Endpoints

Health Check

GET /
GET /health

Response:

{
  "status": "healthy",
  "models_loaded": true,
  "version": "1.0.0"
}

Predict Pneumonia

POST /predict
Content-Type: multipart/form-data

Request:

  • Upload image file (JPG, JPEG, PNG)

Example using cURL:

curl -X POST "http://localhost:8000/predict" \
  -H "accept: application/json" \
  -H "Content-Type: multipart/form-data" \
  -F "file=@chest_xray.jpg"

Example Response:

{
  "success": true,
  "predictions": {
    "svm": {
      "class": "PNEUMONIA",
      "class_id": 1,
      "probabilities": {
        "NORMAL": 0.12,
        "PNEUMONIA": 0.88
      },
      "confidence": 0.88,
      "inference_time_ms": 45.23
    },
    "cnn": {
      "class": "PNEUMONIA",
      "class_id": 1,
      "probabilities": {
        "NORMAL": 0.08,
        "PNEUMONIA": 0.92
      },
      "confidence": 0.92,
      "inference_time_ms": 187.45
    }
  },
  "consensus": {
    "agreement": true,
    "predicted_class": "PNEUMONIA"
  },
  "total_time_ms": 232.68,
  "image_info": {
    "filename": "chest_xray.jpg",
    "original_size": [1024, 1024],
    "format": "JPEG"
  }
}

πŸ§ͺ Testing the API

Using Python Requests

import requests

url = "http://localhost:8000/predict"
files = {"file": open("test_image.jpg", "rb")}

response = requests.post(url, files=files)
print(response.json())

Using JavaScript (Frontend)

const formData = new FormData();
formData.append('file', fileInput.files[0]);

fetch('http://localhost:8000/predict', {
  method: 'POST',
  body: formData
})
.then(response => response.json())
.then(data => console.log(data));

πŸ”’ Security Considerations

For Production Deployment:

  1. CORS Configuration: Replace allow_origins=["*"] with specific allowed domains
  2. HTTPS: Use SSL/TLS certificates
  3. Rate Limiting: Add request rate limiting
  4. Authentication: Implement API key or OAuth authentication
  5. Input Validation: Additional validation for file size/format

πŸ› Troubleshooting

Models Not Loading

Problem: FileNotFoundError: SVM model not found

Solution:

  1. Verify model files exist in models/ directory
  2. Check file names match exactly: svm_model.pkl and best_densenet121.pth
  3. Run verification: python -m utils.model_loader

CUDA Out of Memory

Problem: GPU runs out of memory

Solution:

  • Use CPU inference (automatic fallback)
  • Reduce batch size if processing multiple images
  • Close other GPU-intensive applications

Slow Inference on CPU

Expected Behavior:

  • SVM: ~50-100ms
  • CNN: ~200-500ms (CPU)
  • CNN: ~50-100ms (GPU)

Optimization:

  • Use GPU if available
  • Consider model quantization for production

πŸ“Š Performance Benchmarks

Tested on: Intel i7-10700K, 32GB RAM, RTX 3070

Model Device Avg Inference Time
SVM CPU 48 ms
DenseNet121 CPU 210 ms
DenseNet121 GPU 65 ms
Total (both) CPU ~260 ms
Total (both) GPU ~115 ms

πŸ“ License

This project is provided as-is for educational and research purposes.

πŸ™ Acknowledgments

πŸ“§ Support

For issues or questions, please open an issue on the repository or contact the development team.


Version: 1.0.0
Last Updated: January 2026