Spaces:
Running
π 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, rainfallinclude_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
Install dependencies:
pip install -r requirements.txtRun the API:
python app.pyor
uvicorn app:app --host 0.0.0.0 --port 7860Access the API:
- API: http://localhost:7860
- Documentation: http://localhost:7860/docs
- Alternative docs: http://localhost:7860/redoc
π€ Hugging Face Spaces Deployment
Method 1: Web Interface
Create a new Space:
- Go to https://huggingface.co/spaces
- Click "Create new Space"
- Choose "Docker" as the SDK
- Set visibility as desired
Upload files:
- Upload all project files through the web interface
- Ensure
Dockerfileis in the root directory
Build and deploy:
- The Space will automatically build using the Dockerfile
- Check logs for any build issues
Method 2: Git Repository
Initialize git and add Hugging Face remote:
git init git remote add origin https://huggingface.co/spaces/YOUR_USERNAME/YOUR_SPACE_NAMECommit and push:
git add . git commit -m "Initial FastAPI deployment" git push origin mainMonitor 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 filesPYTHONUNBUFFERED: Ensures proper logging
Model Configuration
The API automatically loads the latest model:
models/crop_disease_v3_model.pth(preferred)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
Model not loading:
- Check if model files exist in
models/directory - Verify model file is not corrupted
- Check console logs for detailed error messages
- Check if model files exist in
CUDA/GPU issues:
- API automatically falls back to CPU if CUDA unavailable
- For GPU deployment, ensure CUDA-compatible PyTorch version
Memory issues:
- Increase container memory limits if needed
- Monitor memory usage during inference
Port conflicts:
- Ensure port 7860 is available
- Modify port in Dockerfile and uvicorn command if needed
Debugging
- Check FastAPI logs in the console
- Use
/healthendpoint to verify model status - Access
/docsfor 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
/healthendpoint 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
- Replace model file in
models/directory - Update DEFAULT_CLASSES if class changes occurred
- Restart the API to load new model
Code Updates
- Update application code
- Test locally before deployment
- 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.