A full-stack web application demonstrating ML model deployment and inference with built-in explainability using Grad-CAM visualization.
- Image Classification: Upload images and get AI-powered object classification using MobileNetV2 (ImageNet)
- Model Explainability: Built-in Grad-CAM (Gradient-weighted Class Activation Mapping) visualization showing which parts of the image influenced the model's decision
- Modern UI: Responsive React frontend with drag-and-drop image upload
- Production-Ready: FastAPI backend optimized for performance
- Cloud Deployment: One-command deployment to Google Cloud Run
- Docker Support: Containerized application for easy local development and deployment
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β React Frontend β
β - Image Upload UI (Drag & Drop) β
β - Results Display β
β - Grad-CAM Visualization Toggle β
βββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββ
β HTTP/REST API
βββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββ
β FastAPI Backend β
β - /predict endpoint β
β - Image preprocessing β
β - Model inference β
β - Grad-CAM generation β
βββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββ
β TensorFlow/Keras β
β - MobileNetV2 (ImageNet pretrained) β
β - 1000 object classes β
β - Gradient computation for Grad-CAM β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- Python 3.10+
- Node.js 18+
- Docker (optional, for containerized deployment)
- Google Cloud SDK (optional, for Cloud Run deployment)
# Navigate to backend directory
cd backend
# Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt
# Start the FastAPI server
python main.pyThe backend will be available at http://localhost:8000
API Documentation: http://localhost:8000/docs
# In a new terminal, navigate to frontend directory
cd frontend
# Install dependencies
npm install
# Start the development server
npm run devThe frontend will be available at http://localhost:3000
# Start both backend and frontend with one command
docker-compose up
# Or run in detached mode
docker-compose up -d- Frontend:
http://localhost:3000 - Backend API:
http://localhost:8080 - API Docs:
http://localhost:8080/docs
AI-Image-Classifier-App/
βββ backend/
β βββ main.py # FastAPI application
β βββ model_handler.py # Model loading and inference
β βββ gradcam.py # Grad-CAM implementation
β βββ requirements.txt # Python dependencies
βββ frontend/
β βββ src/
β β βββ components/
β β β βββ ImageUploader.jsx
β β β βββ ResultsDisplay.jsx
β β β βββ *.css
β β βββ App.jsx
β β βββ main.jsx
β β βββ index.css
β βββ package.json
β βββ vite.config.js
βββ models/ # Directory for custom models
βββ Dockerfile # Production Docker image
βββ docker-compose.yml # Local development setup
βββ deploy.sh # Cloud Run deployment script
βββ README.md
Health check endpoint
{
"status": "healthy",
"service": "ML Image Classifier",
"version": "1.0.0"
}Detailed health check with model status
{
"status": "healthy",
"model_loaded": true,
"model_info": {...}
}Classify an uploaded image
Request: multipart/form-data with image file
Response:
{
"success": true,
"predictions": [
{
"class_idx": 123,
"class_name": "golden_retriever",
"confidence": 0.89,
"confidence_percent": "89.00%"
},
...
],
"original_image": "data:image/png;base64,...",
"gradcam_image": "data:image/png;base64,...",
"top_prediction": {...}
}Get list of all available classification classes
Grad-CAM (Gradient-weighted Class Activation Mapping) is a technique for making visual explanations from CNN-based models. It highlights the regions in the image that were most important for the model's prediction.
How it works:
- Computes the gradient of the predicted class score with respect to the final convolutional layer
- Pools the gradients to get feature importance weights
- Creates a heatmap by weighting the feature maps
- Overlays the heatmap on the original image
Interpretation:
- Red/Yellow regions: High importance (model focused here)
- Blue/Purple regions: Low importance
- Green regions: Medium importance
- Install Google Cloud SDK
- Authenticate:
gcloud auth login - Set your project:
gcloud config set project YOUR_PROJECT_ID
# Set environment variables
export GCP_PROJECT_ID="your-project-id"
export GCP_REGION="us-central1" # Optional, defaults to us-central1
# Run deployment script
./deploy.shThe script will:
- Build the Docker image
- Push to Google Container Registry
- Deploy to Cloud Run
- Output the public URL
# Build and tag image
docker build -t gcr.io/YOUR_PROJECT_ID/ml-image-classifier .
# Push to GCR
docker push gcr.io/YOUR_PROJECT_ID/ml-image-classifier
# Deploy to Cloud Run
gcloud run deploy ml-image-classifier \
--image gcr.io/YOUR_PROJECT_ID/ml-image-classifier \
--platform managed \
--region us-central1 \
--allow-unauthenticated \
--memory 2Gi \
--cpu 2# Health check
curl http://localhost:8000/health
# Predict with image
curl -X POST \
http://localhost:8000/predict \
-H 'Content-Type: multipart/form-data' \
-F 'file=@/path/to/your/image.jpg'import requests
# Upload and classify image
with open('image.jpg', 'rb') as f:
files = {'file': f}
response = requests.post('http://localhost:8000/predict', files=files)
result = response.json()
print(f"Top prediction: {result['top_prediction']['class_name']}")
print(f"Confidence: {result['top_prediction']['confidence_percent']}")- Save your Keras/TensorFlow model to the
models/directory - Update
model_handler.py:
def __init__(self, model_path: str = "models/your_model.h5"):
self.model_path = model_path
# ... rest of the code- Update class labels if needed:
self.classes = ["class1", "class2", "class3", ...]In gradcam.py, modify the generate() method:
# Change overlay transparency (0.0 - 1.0)
def generate(self, image: Image.Image, class_idx: int, alpha: float = 0.4):
# Lower alpha = more transparent heatmap
# Higher alpha = more opaque heatmapModel loading errors:
# Check TensorFlow installation
python -c "import tensorflow as tf; print(tf.__version__)"
# Re-install TensorFlow
pip uninstall tensorflow
pip install tensorflow==2.15.0Port already in use:
# Kill process on port 8000
lsof -ti:8000 | xargs kill -9
# Or use a different port
uvicorn backend.main:app --port 8001Build errors:
# Clear node_modules and reinstall
rm -rf node_modules package-lock.json
npm installAPI connection issues:
- Check CORS settings in
backend/main.py - Verify
VITE_API_URLin.envorvite.config.js
- Model: MobileNetV2 is optimized for inference speed (~30-50ms per image)
- Memory: ~500MB for model + gradients
- Scaling: Cloud Run auto-scales based on traffic
- Optimization: Consider TensorFlow Lite for edge deployment
Contributions are welcome! Please follow these steps:
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Commit your changes:
git commit -m 'Add amazing feature' - Push to the branch:
git push origin feature/amazing-feature - Open a Pull Request
This project is licensed under the MIT License.
- MobileNetV2: Pre-trained model from TensorFlow/Keras
- Grad-CAM: Original paper by Selvaraju et al. (2017)
- FastAPI: Modern, fast web framework for building APIs
- React: UI library for building interactive interfaces
For issues, questions, or suggestions, please open an issue on GitHub.
Built with β€οΈ using FastAPI, TensorFlow, and React