Spaces:
Running
Running
| title: Crop Disease Detection API | |
| emoji: ๐ฑ | |
| colorFrom: green | |
| colorTo: blue | |
| sdk: docker | |
| app_port: 7860 | |
| pinned: false | |
| license: mit | |
| tags: | |
| - computer-vision | |
| - agriculture | |
| - disease-detection | |
| - fastapi | |
| - pytorch | |
| - resnet50 | |
| - grad-cam | |
| - crop-monitoring | |
| short_description: AI-powered crop disease detection for plants | |
| # ๐ฑ Crop Disease Detection API | |
| [](https://python.org) | |
| [](https://pytorch.org) | |
| [](https://fastapi.tiangolo.com) | |
| [](https://huggingface.co/spaces) | |
| [](LICENSE) | |
| A RESTful API for AI-powered crop disease detection using deep learning to identify diseases in pepper, potato, and tomato crops from leaf images. The API provides accurate disease classification, risk assessment, Grad-CAM visualizations, and treatment recommendations. | |
| > **๐ Production Ready**: FastAPI-based REST API optimized for Hugging Face Spaces deployment with Docker. All features preserved from the original Streamlit implementation. | |
| ## ๐ฏ API Overview | |
| This FastAPI service provides a comprehensive crop disease detection pipeline that: | |
| - **Detects 15 different diseases** across pepper, potato, and tomato crops | |
| - **Provides visual explanations** using Grad-CAM heatmaps | |
| - **Offers treatment recommendations** from an integrated knowledge base | |
| - **Calculates risk levels** based on confidence and environmental factors | |
| - **RESTful endpoints** for health checks, predictions, visualizations, and status tracking | |
| - **๐ Deployment Ready**: Optimized for Hugging Face Spaces with Docker support | |
| ### ๐ Key Features | |
| - **๐ค AI Model**: ResNet50-based transfer learning with 26.1M parameters (V3) | |
| - **๐ Disease Classes**: 15 classes including healthy variants for each crop | |
| - **๐จ Visual Explanations**: Grad-CAM heatmaps highlighting infected regions | |
| - **๐ Knowledge Base**: Comprehensive disease information with symptoms and treatments | |
| - **โก Real-time Processing**: Fast inference with GPU/CPU support and progress tracking | |
| - **๐ REST API**: FastAPI with automatic OpenAPI documentation | |
| - **๐ฅ๏ธ CLI Tool**: Command-line interface for batch processing (preserved) | |
| - **๐ Training Pipeline**: Complete model training and evaluation system (preserved) | |
| ## ๐ Project Structure | |
| ``` | |
| diseases_aicrop/ | |
| โโโ ๏ฟฝ app.py # FastAPI application (main API server) | |
| โโโ ๐ requirements.txt # Python dependencies (FastAPI + ML) | |
| โโโ ๐ Dockerfile # Docker container configuration | |
| โโโ ๐ DEPLOYMENT_GUIDE.md # Detailed deployment instructions | |
| โโโ ๐ README.md # This file | |
| โโโ ๐ src/ # Core modules | |
| โ โโโ model.py # ResNet50 model definition | |
| โ โโโ explain.py # Grad-CAM explainer | |
| โ โโโ risk_level.py # Risk assessment calculator | |
| โ โโโ predict_cli.py # CLI tool (preserved) | |
| โ โโโ train.py # Model training (preserved) | |
| โ โโโ evaluate.py # Model evaluation (preserved) | |
| โโโ ๐ models/ # Trained model weights | |
| โ โโโ crop_disease_v3_model.pth # Latest V3 model (preferred) | |
| โ โโโ crop_disease_v2_model.pth # V2 model (fallback) | |
| โโโ ๐ knowledge_base/ # Disease information database | |
| โ โโโ disease_info.json # Symptoms, treatments, prevention | |
| โโโ ๐ notebooks/ # Training and analysis (preserved) | |
| โ โโโ train_resnet50.ipynb # Model training notebook | |
| โโโ ๐ data/ # Dataset (preserved for retraining) | |
| โ โโโ raw/ # Original dataset | |
| โโโ ๐ outputs/ # Evaluation results (preserved) | |
| โโโ ๐ notebooks/ # Jupyter notebooks | |
| โ โโโ train_resnet50.ipynb # Training notebook | |
| โโโ ๐ outputs/ # Results and visualizations | |
| โ โโโ heatmaps/ # Grad-CAM visualizations | |
| โ โโโ *.json # Evaluation results | |
| โโโ ๐ src/ # Core source code | |
| โ โโโ dataset.py # Data loading and preprocessing | |
| โ โโโ model.py # ResNet50 architecture | |
| โ โโโ train.py # Training pipeline | |
| โ โโโ evaluate.py # Model evaluation | |
| โ โโโ explain.py # Grad-CAM explanations | |
| โ โโโ risk_level.py # Risk assessment logic | |
| โ โโโ predict_cli.py # CLI predictor | |
| โโโ ๐ tests/ # Unit tests | |
| โโโ crop_disease_gui.py # Tkinter GUI application | |
| โโโ requirements.txt # Main dependencies | |
| โโโ TRAINING_REPORT.md # Performance analysis | |
| ``` | |
| ## ๐ ๏ธ Technology Stack | |
| ### Core Technologies | |
| - **Deep Learning**: PyTorch 2.1.0, torchvision 0.16.0 | |
| - **Model Architecture**: ResNet50 with transfer learning | |
| - **Web Framework**: Streamlit 1.28.0+ | |
| - **Computer Vision**: OpenCV, PIL/Pillow | |
| - **Visualization**: Grad-CAM, matplotlib | |
| ### Dependencies | |
| - **Core ML**: PyTorch, torchvision, numpy | |
| - **Image Processing**: OpenCV-Python, Pillow | |
| - **Web Interface**: Streamlit | |
| - **Visualization**: matplotlib, grad-cam | |
| - **Utilities**: requests, tqdm, pydantic | |
| ### Development Tools | |
| - **Environment**: Python 3.9+ (Docker: python:3.9-slim) | |
| - **Notebooks**: Jupyter/Google Colab support | |
| - **Deployment**: Docker + Hugging Face Spaces | |
| - **Version Control**: Git | |
| - **Local Development**: Optimized for Windows PowerShell | |
| ## ๐ Installation & Setup | |
| ### Prerequisites | |
| - Python 3.8 or higher | |
| - pip package manager | |
| - (Optional) CUDA-compatible GPU for faster training | |
| ### 1. Clone Repository | |
| ```bash | |
| git clone https://github.com/vivek12coder/AiCropDiseasesDetection.git | |
| cd AiCropDiseasesDetection | |
| ``` | |
| ### 2. Create Virtual Environment | |
| ```powershell | |
| # Windows PowerShell (recommended) | |
| python -m venv .venv | |
| .\.venv\Scripts\Activate.ps1 | |
| # Alternative for Command Prompt | |
| python -m venv .venv | |
| .venv\Scripts\activate.bat | |
| # macOS/Linux | |
| python -m venv .venv | |
| source .venv/bin/activate | |
| ``` | |
| ### 3. Install Dependencies | |
| ```powershell | |
| # Install main dependencies | |
| pip install -r requirements.txt | |
| # For API development (optional) | |
| pip install -r api/requirements.txt | |
| ``` | |
| ### 4. Pre-trained Model | |
| The repository includes the latest pre-trained model: | |
| - `models/crop_disease_v3_model.pth` - Latest V3 model (recommended) | |
| > **Note**: Older model versions have been removed to keep the project clean. Only the latest, best-performing model is included. | |
| ### 5. Verify Installation | |
| ```bash | |
| python -c "import torch; print(f'PyTorch: {torch.__version__}')" | |
| python -c "import torchvision; print(f'TorchVision: {torchvision.__version__}')" | |
| ``` | |
| ## ๐ API Usage Guide | |
| ### ๐ Quick Start | |
| Start the FastAPI server locally: | |
| ```powershell | |
| # Run the FastAPI application | |
| python app.py | |
| ``` | |
| The API will be available at: | |
| - **API Base URL**: http://localhost:7860 | |
| - **Interactive Docs**: http://localhost:7860/docs | |
| - **Alternative Docs**: http://localhost:7860/redoc | |
| ### ๐ API Endpoints | |
| #### 1. Health Check | |
| Check API and model status: | |
| ```bash | |
| curl -X GET "http://localhost:7860/health" | |
| ``` | |
| **Response:** | |
| ```json | |
| { | |
| "status": "healthy", | |
| "model_loaded": true, | |
| "model_version": "crop_disease_v3_model.pth", | |
| "available_endpoints": ["/health", "/predict", "/gradcam/{task_id}", "/status/{task_id}"], | |
| "timestamp": "2024-01-01T12:00:00", | |
| "device": "cuda:0" | |
| } | |
| ``` | |
| #### 2. Disease Prediction | |
| Upload an image for disease detection: | |
| ```bash | |
| curl -X POST "http://localhost:7860/predict" \ | |
| -H "Content-Type: multipart/form-data" \ | |
| -F "file=@test_leaf_sample.jpg" \ | |
| -F "include_gradcam=true" | |
| ``` | |
| **Response:** | |
| ```json | |
| { | |
| "success": true, | |
| "predicted_class": "Tomato_Late_blight", | |
| "crop": "Tomato", | |
| "disease": "Late_blight", | |
| "confidence": 0.95, | |
| "all_probabilities": { | |
| "Tomato_Late_blight": 0.95, | |
| "Tomato_Early_blight": 0.03, | |
| "Tomato_healthy": 0.02 | |
| }, | |
| "risk_level": "High", | |
| "processing_time": 2.3, | |
| "task_id": "550e8400-e29b-41d4-a716-446655440000" | |
| } | |
| ``` | |
| #### 3. Grad-CAM Visualization | |
| Get the heatmap for a prediction: | |
| ```bash | |
| curl -X GET "http://localhost:7860/gradcam/550e8400-e29b-41d4-a716-446655440000" | |
| ``` | |
| **Response:** | |
| ```json | |
| { | |
| "success": true, | |
| "heatmap_base64": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...", | |
| "explanation": "Grad-CAM heatmap showing areas the AI model focused on for prediction", | |
| "task_id": "550e8400-e29b-41d4-a716-446655440000", | |
| "processing_time": 1.2 | |
| } | |
| ``` | |
| #### 4. Processing Status | |
| Track processing progress: | |
| ```bash | |
| curl -X GET "http://localhost:7860/status/550e8400-e29b-41d4-a716-446655440000" | |
| ``` | |
| **Response:** | |
| ```json | |
| { | |
| "task_id": "550e8400-e29b-41d4-a716-446655440000", | |
| "status": "completed", | |
| "progress": 100, | |
| "message": "Analysis completed successfully", | |
| "timestamp": "2024-01-01T12:00:30" | |
| } | |
| ``` | |
| #### 5. Disease Information | |
| Get detailed disease information: | |
| ```bash | |
| curl -X GET "http://localhost:7860/disease-info?crop=Tomato&disease=Late_blight" | |
| ``` | |
| ### ๏ฟฝ Python Client Example | |
| ```python | |
| import requests | |
| import json | |
| from PIL import Image | |
| import base64 | |
| import io | |
| # API base URL | |
| API_BASE = "http://localhost:7860" | |
| # 1. Health check | |
| response = requests.get(f"{API_BASE}/health") | |
| print("Health Check:", response.json()) | |
| # 2. Predict disease | |
| with open("test_leaf_sample.jpg", "rb") as f: | |
| files = {"file": f} | |
| data = { | |
| "weather_data": json.dumps({ | |
| "humidity": 70.0, | |
| "temperature": 22.0, | |
| "rainfall": 5.0 | |
| }), | |
| "include_gradcam": True | |
| } | |
| response = requests.post(f"{API_BASE}/predict", files=files, data=data) | |
| prediction = response.json() | |
| print("Prediction:", prediction) | |
| task_id = prediction["task_id"] | |
| # 3. Get Grad-CAM visualization | |
| import time | |
| time.sleep(2) # Wait for background processing | |
| response = requests.get(f"{API_BASE}/gradcam/{task_id}") | |
| if response.status_code == 200: | |
| gradcam = response.json() | |
| # Decode and display heatmap | |
| heatmap_data = base64.b64decode(gradcam["heatmap_base64"].split(",")[1]) | |
| heatmap_image = Image.open(io.BytesIO(heatmap_data)) | |
| heatmap_image.show() | |
| # 4. Get disease information | |
| crop = prediction["crop"] | |
| disease = prediction["disease"] | |
| response = requests.get(f"{API_BASE}/disease-info", params={"crop": crop, "disease": disease}) | |
| disease_info = response.json() | |
| print("Disease Info:", disease_info) | |
| ``` | |
| ### ๐ฅ๏ธ CLI Tool (Preserved) | |
| For batch processing or scripting: | |
| ```powershell | |
| # Single image prediction | |
| python -m src.predict_cli -i test_leaf_sample.jpg -m models\crop_disease_v3_model.pth | |
| # With custom settings | |
| python -m src.predict_cli -i your_image.jpg --output-dir results/ | |
| ``` | |
| ### ๐ Model Training & Evaluation (Preserved) | |
| Original training and evaluation capabilities remain intact: | |
| ```powershell | |
| # Evaluate existing model | |
| python -m src.evaluate | |
| # Train new model | |
| python -m src.train | |
| # Generate visual explanations | |
| python -m src.explain | |
| ``` | |
| ### ๏ฟฝ Jupyter Notebooks (Preserved) | |
| Explore the training process interactively: | |
| ```powershell | |
| jupyter notebook notebooks/train_resnet50.ipynb | |
| ``` | |
| 4. **View Results**: See detailed analysis in results panel | |
| ## ๐ฏ Model Performance | |
| ### Current Performance (V3 Model) | |
| - **Model Architecture**: ResNet50 with custom classifier layers | |
| - **Parameters**: 26.1M total parameters | |
| - **Input Size**: 224x224 RGB images | |
| - **Classes**: 15 disease classes across 3 crops | |
| - **Inference Speed**: ~0.1 seconds per image on CPU | |
| ### Supported Disease Classes | |
| **Pepper Diseases:** | |
| - Bell Pepper Bacterial Spot | |
| - Bell Pepper Healthy | |
| **Potato Diseases:** | |
| - Early Blight | |
| - Late Blight | |
| - Healthy | |
| **Tomato Diseases:** | |
| - Target Spot | |
| - Tomato Mosaic Virus | |
| - Tomato Yellow Leaf Curl Virus | |
| - Bacterial Spot | |
| - Early Blight | |
| - Late Blight | |
| - Leaf Mold | |
| - Septoria Leaf Spot | |
| - Spider Mites (Two-spotted) | |
| - Healthy | |
| > **Note**: The model has been trained on limited data. For production use, consider collecting more training samples per class. | |
| ## ๐ง Configuration | |
| ### Environment Variables | |
| ```powershell | |
| # Optional: Set device preference | |
| $env:TORCH_DEVICE="cuda" # or 'cpu' | |
| # Optional: Set model path | |
| $env:MODEL_PATH="models/crop_disease_v3_model.pth" | |
| ``` | |
| ### API Configuration | |
| Edit `api/main.py` for production settings: | |
| - CORS origins | |
| - Authentication | |
| - Rate limiting | |
| - Logging levels | |
| ## ๐ Deployment | |
| ### ๐ค Hugging Face Spaces (Recommended) | |
| The project is ready for one-click deployment on Hugging Face Spaces: | |
| 1. **Fork/Clone** this repository | |
| 2. **Create a new Space** on [Hugging Face Spaces](https://huggingface.co/spaces) | |
| 3. **Select "Docker" SDK** when creating the Space | |
| 4. **Upload the project files** or connect your Git repository | |
| 5. **Wait for build** (5-10 minutes) and your app will be live! | |
| **๐ Detailed Instructions**: See [DEPLOY_INSTRUCTIONS.md](DEPLOY_INSTRUCTIONS.md) | |
| ### ๐ฅ๏ธ Local Streamlit App | |
| ```powershell | |
| # Install dependencies | |
| pip install -r requirements.txt | |
| # Run Streamlit app | |
| streamlit run app.py | |
| # Open browser to: http://localhost:8501 | |
| ``` | |
| ### ๐ณ Docker Deployment | |
| ```powershell | |
| # Build image | |
| docker build -t crop-disease-ai . | |
| # Run container | |
| docker run -p 7860:7860 crop-disease-ai | |
| # Open browser to: http://localhost:7860 | |
| ``` | |
| ### Local Development | |
| ```powershell | |
| # GUI Application | |
| python crop_disease_gui.py | |
| # API Server | |
| python -m api.main | |
| # CLI Prediction | |
| python -m src.predict_cli -i test_leaf_sample.jpg | |
| ``` | |
| ### Local (Non-Docker) Quick Start | |
| Use these steps on Windows PowerShell to run locally without Docker: | |
| ```powershell | |
| python -m venv .venv | |
| .\.venv\Scripts\Activate.ps1 | |
| pip install -r requirements.txt | |
| # Optional: API extras | |
| pip install -r api/requirements.txt | |
| # Evaluate model | |
| python -m src.evaluate | |
| # Run API | |
| python -m api.main | |
| # Single-image CLI prediction | |
| python -m src.predict_cli -i test_leaf_sample.jpg -m models\crop_disease_v3_model.pth | |
| ``` | |
| ### Cloud Deployment | |
| The API is ready for deployment on: | |
| - **AWS**: EC2, Lambda, ECS | |
| - **Google Cloud**: Cloud Run, Compute Engine | |
| - **Azure**: Container Instances, App Service | |
| - **Heroku**: Container deployment | |
| ## ๐ค Contributing | |
| ### Development Setup | |
| 1. Fork the repository | |
| 2. Create feature branch: `git checkout -b feature/new-feature` | |
| 3. Make changes and test thoroughly | |
| 4. Submit pull request with detailed description | |
| ### Contribution Guidelines | |
| - Follow PEP 8 style guidelines | |
| - Add unit tests for new features | |
| - Update documentation for API changes | |
| - Ensure backward compatibility | |
| ### Areas for Contribution | |
| - **Data Collection**: Expand disease image dataset | |
| - **Model Improvements**: Experiment with new architectures | |
| - **Feature Enhancement**: Add new crops/diseases | |
| - **Performance Optimization**: Speed and accuracy improvements | |
| - **Documentation**: Tutorials and examples | |
| ## ๐ License | |
| This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. | |
| ## ๐ฅ Authors & Acknowledgments | |
| **Project Team:** | |
| - **Lead Developer**: [Your Name] | |
| - **AI/ML Engineer**: [Team Member] | |
| - **Data Scientist**: [Team Member] | |
| **Acknowledgments:** | |
| - PlantVillage dataset for training data | |
| - PyTorch team for deep learning framework | |
| - FastAPI team for web framework | |
| - Open source community for various tools | |
| ## ๐ Support & Contact | |
| ### Getting Help | |
| - **Documentation**: Check this README and code comments | |
| - **Issues**: Create GitHub issue for bugs/feature requests | |
| - **Discussions**: Use GitHub discussions for questions | |
| ### Contact Information | |
| - **GitHub Repository**: https://github.com/vivek12coder/AiCropDiseasesDetection | |
| - **Issues**: Create GitHub issue for bugs/feature requests | |
| - **Project Owner**: @vivek12coder | |
| ## ๐ฎ Future Roadmap | |
| ### Phase 1: Data Enhancement (Weeks 1-2) | |
| - [ ] Collect 1000+ images per disease class | |
| - [ ] Implement advanced data augmentation | |
| - [ ] Create balanced train/val/test splits | |
| ### Phase 2: Model Optimization (Weeks 3-4) | |
| - [ ] Experiment with EfficientNet, MobileNet | |
| - [ ] Implement ensemble methods | |
| - [ ] Add uncertainty estimation | |
| ### Phase 3: Feature Expansion (Weeks 5-6) | |
| - [ ] Add more crop types (rice, wheat, etc.) | |
| - [ ] Implement real-time video processing | |
| - [ ] Mobile app development | |
| ### Phase 4: Production Enhancement (Weeks 7-8) | |
| - [ ] Cloud deployment with auto-scaling | |
| - [ ] Monitoring and logging system | |
| - [ ] User analytics and feedback system | |
| --- | |
| ## ๐ Quick Start Checklist | |
| - [ ] Install Python 3.8+ | |
| - [ ] Clone repository | |
| - [ ] Install dependencies: `pip install -r requirements.txt` | |
| - [ ] Test GUI: `python crop_disease_gui.py` | |
| - [ ] Test API: `python -m api.main` | |
| - [ ] Test CLI: `python -m src.predict_cli -i test_leaf_sample.jpg` | |
| - [ ] Upload test image and verify results | |
| - [ ] Explore API documentation at http://127.0.0.1:8000/docs | |
| **๐ Ready to detect crop diseases with AI!** | |