--- 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 ```bash cd pneumonia-detection-backend ``` ### 3. Create Virtual Environment (Recommended) ```bash # 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 ```bash 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](https://pytorch.org/get-started/locally/). ### 5. Add Model Files Place your trained model files in the `models/` directory: ```bash 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 ```bash 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 ```bash 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 ```bash GET / GET /health ``` **Response:** ```json { "status": "healthy", "models_loaded": true, "version": "1.0.0" } ``` ### Predict Pneumonia ```bash POST /predict Content-Type: multipart/form-data ``` **Request:** - Upload image file (JPG, JPEG, PNG) **Example using cURL:** ```bash curl -X POST "http://localhost:8000/predict" \ -H "accept: application/json" \ -H "Content-Type: multipart/form-data" \ -F "file=@chest_xray.jpg" ``` **Example Response:** ```json { "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 ```python 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) ```javascript 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 - Dataset: [Chest X-Ray Images (Pneumonia)](https://www.kaggle.com/datasets/paultimothymooney/chest-xray-pneumonia) from Kaggle - DenseNet121 architecture: [CheXNet](https://arxiv.org/abs/1711.05225) ## ๐Ÿ“ง 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