Spaces:
Running
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, rainfall | |
| - `include_gradcam` (optional): Generate Grad-CAM heatmap (default: true) | |
| - `include_disease_info` (optional): Include disease information (default: true) | |
| **Response:** | |
| ```json | |
| { | |
| "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:** | |
| ```bash | |
| pip install -r requirements.txt | |
| ``` | |
| 2. **Run the API:** | |
| ```bash | |
| python app.py | |
| ``` | |
| or | |
| ```bash | |
| uvicorn app:app --host 0.0.0.0 --port 7860 | |
| ``` | |
| 3. **Access 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 | |
| 1. **Create a new Space:** | |
| - Go to https://huggingface.co/spaces | |
| - Click "Create new Space" | |
| - Choose "Docker" as the SDK | |
| - Set visibility as desired | |
| 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:** | |
| ```bash | |
| git init | |
| git remote add origin https://huggingface.co/spaces/YOUR_USERNAME/YOUR_SPACE_NAME | |
| ``` | |
| 2. **Commit and push:** | |
| ```bash | |
| 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 | |
| ```bash | |
| # 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 | |
| ```python | |
| 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. |