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:
SVM Classifier (Classical ML)
- Hand-crafted features: LBP (Local Binary Patterns) + HOG (Histogram of Oriented Gradients)
- Preprocessing: CLAHE enhancement β Feature extraction
- Fast inference (~50ms)
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:
- Local: http://localhost:8000
- Network: http://your-ip-address:8000
π API Documentation
Once running, access interactive API documentation:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
π 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:
- CORS Configuration: Replace
allow_origins=["*"]with specific allowed domains - HTTPS: Use SSL/TLS certificates
- Rate Limiting: Add request rate limiting
- Authentication: Implement API key or OAuth authentication
- Input Validation: Additional validation for file size/format
π Troubleshooting
Models Not Loading
Problem: FileNotFoundError: SVM model not found
Solution:
- Verify model files exist in
models/directory - Check file names match exactly:
svm_model.pklandbest_densenet121.pth - 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
- Dataset: Chest X-Ray Images (Pneumonia) from Kaggle
- DenseNet121 architecture: CheXNet
π§ 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