crop / DEPLOYMENT_GUIDE.md
vivek12coder's picture
Initial commit - uploaded project
36dd4e6

πŸš€ FastAPI Crop Disease Detection - Deployment Guide

Overview

This project has been converted from Streamlit to FastAPI to provide a RESTful API for crop disease detection. The API includes all original features:

  • Health Check - API and model status
  • Disease Prediction - Image upload and AI inference
  • Grad-CAM Visualization - Heat map generation
  • Progress Tracking - Real-time processing status
  • Disease Information - Knowledge base integration

πŸ“‹ API Endpoints

1. Health Check

GET /health

Returns API status and model information.

2. Disease Prediction

POST /predict

Upload an image file for disease prediction.

Parameters:

  • file (required): Image file (JPG, PNG, BMP)
  • weather_data (optional): JSON string with humidity, temperature, rainfall
  • include_gradcam (optional): Generate Grad-CAM heatmap (default: true)
  • include_disease_info (optional): Include disease information (default: true)

Response:

{
  "success": true,
  "predicted_class": "Tomato_Late_blight",
  "crop": "Tomato",
  "disease": "Late_blight", 
  "confidence": 0.95,
  "all_probabilities": {...},
  "risk_level": "High",
  "processing_time": 2.3,
  "task_id": "uuid-string"
}

3. Grad-CAM Visualization

GET /gradcam/{task_id}

Get the Grad-CAM heatmap for a prediction task.

4. Processing Status

GET /status/{task_id}

Check the processing status of a task.

5. Disease Information

GET /disease-info?crop=Tomato&disease=Late_blight

Get detailed information about a specific disease.

πŸƒβ€β™‚οΈ Local Development

Prerequisites

  • Python 3.9+
  • PyTorch
  • FastAPI
  • Uvicorn

Setup

  1. Install dependencies:

    pip install -r requirements.txt
    
  2. Run the API:

    python app.py
    

    or

    uvicorn app:app --host 0.0.0.0 --port 7860
    
  3. Access the API:

πŸ€— Hugging Face Spaces Deployment

Method 1: Web Interface

  1. Create a new Space:

  2. Upload files:

    • Upload all project files through the web interface
    • Ensure Dockerfile is in the root directory
  3. Build and deploy:

    • The Space will automatically build using the Dockerfile
    • Check logs for any build issues

Method 2: Git Repository

  1. Initialize git and add Hugging Face remote:

    git init
    git remote add origin https://huggingface.co/spaces/YOUR_USERNAME/YOUR_SPACE_NAME
    
  2. Commit and push:

    git add .
    git commit -m "Initial FastAPI deployment"
    git push origin main
    
  3. Monitor deployment:

    • Check the Space's build logs
    • Verify the API is running at your Space URL

πŸ“ Project Structure

diseases_aicrop/
β”œβ”€β”€ app.py                  # FastAPI application
β”œβ”€β”€ requirements.txt        # Python dependencies  
β”œβ”€β”€ Dockerfile             # Container configuration
β”œβ”€β”€ DEPLOYMENT_GUIDE.md    # This guide
β”œβ”€β”€ README.md              # Project documentation
β”œβ”€β”€ src/                   # Source code modules
β”‚   β”œβ”€β”€ model.py          # ResNet50 model definition
β”‚   β”œβ”€β”€ explain.py        # Grad-CAM explainer
β”‚   β”œβ”€β”€ risk_level.py     # Risk assessment
β”‚   └── ...
β”œβ”€β”€ models/               # Trained models
β”‚   └── crop_disease_v3_model.pth  # Latest model (V3)
β”œβ”€β”€ knowledge_base/       # Disease information
β”‚   └── disease_info.json
└── data/                # Training data (preserved)

πŸ”§ Configuration

Environment Variables

  • PYTHONPATH: Set to /app (handled by Dockerfile)
  • PYTHONDONTWRITEBYTECODE: Prevents .pyc files
  • PYTHONUNBUFFERED: Ensures proper logging

Model Configuration

The API automatically loads the latest model:

  1. models/crop_disease_v3_model.pth (preferred)
  2. models/crop_disease_v2_model.pth (fallback)

πŸ§ͺ Testing the API

Using curl

# Health check
curl -X GET "http://localhost:7860/health"

# Predict disease
curl -X POST "http://localhost:7860/predict" \
  -H "accept: application/json" \
  -H "Content-Type: multipart/form-data" \
  -F "file=@test_leaf_sample.jpg"

Using Python requests

import requests

# Health check
response = requests.get("http://localhost:7860/health")
print(response.json())

# Predict disease
with open("test_leaf_sample.jpg", "rb") as f:
    files = {"file": f}
    response = requests.post("http://localhost:7860/predict", files=files)
    print(response.json())

πŸ› Troubleshooting

Common Issues

  1. Model not loading:

    • Check if model files exist in models/ directory
    • Verify model file is not corrupted
    • Check console logs for detailed error messages
  2. CUDA/GPU issues:

    • API automatically falls back to CPU if CUDA unavailable
    • For GPU deployment, ensure CUDA-compatible PyTorch version
  3. Memory issues:

    • Increase container memory limits if needed
    • Monitor memory usage during inference
  4. Port conflicts:

    • Ensure port 7860 is available
    • Modify port in Dockerfile and uvicorn command if needed

Debugging

  • Check FastAPI logs in the console
  • Use /health endpoint to verify model status
  • Access /docs for interactive API testing

πŸš€ Performance Optimization

Production Recommendations

  • Use GPU-enabled containers for faster inference
  • Implement caching for repeated requests
  • Add rate limiting for production use
  • Monitor API performance and add logging

Scaling

  • Deploy multiple instances behind a load balancer
  • Use Redis for shared processing status storage
  • Implement background task queues for heavy operations

πŸ“Š Monitoring

Health Monitoring

  • The /health endpoint provides model status
  • Docker health check verifies API availability
  • Monitor response times and error rates

Logging

  • All processing steps are logged to console
  • Error messages include detailed stack traces
  • Task IDs help track individual requests

πŸ”„ Updates and Maintenance

Model Updates

  1. Replace model file in models/ directory
  2. Update DEFAULT_CLASSES if class changes occurred
  3. Restart the API to load new model

Code Updates

  1. Update application code
  2. Test locally before deployment
  3. Push changes to trigger automatic rebuild

πŸ“ž Support

For issues and questions:

  • Check this deployment guide
  • Review the API documentation at /docs
  • Examine console logs for error details
  • Test endpoints individually to isolate problems

🌱 Happy deploying! Your FastAPI-based crop disease detection system is ready for production use.