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45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
# ๐ŸŒฑ Crop Disease Detection AI

[![Python](https://img.shields.io/badge/Python-3.8%2B-blue.svg)](https://python.org)
[![PyTorch](https://img.shields.io/badge/PyTorch-2.1.0-red.svg)](https://pytorch.org)
[![Streamlit](https://img.shields.io/badge/Streamlit-1.28.0-red.svg)](https://streamlit.io)
[![Hugging Face Spaces](https://img.shields.io/badge/๐Ÿค—%20Hugging%20Face-Spaces-blue)](https://huggingface.co/spaces)
[![License](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)

An AI-powered crop disease detection system using deep learning to identify diseases in pepper, potato, and tomato crops from leaf images. The system provides accurate disease classification, risk assessment, visual explanations, and treatment recommendations.

> **๐Ÿš€ Now Ready for Deployment**: This project is optimized for Hugging Face Spaces deployment with Streamlit and Docker. All components have been tested and verified for production use.

## ๐ŸŽฏ Project Overview

This project implements 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
- **Supports multiple interfaces**: Streamlit web app, CLI tool, and training notebooks
- **๐Ÿš€ Deployment Ready**: Optimized for Hugging Face Spaces with Docker support

### ๐Ÿ† Key Features

- **๐Ÿค– AI Model**: ResNet50-based transfer learning with 26.1M parameters
- **๐Ÿ“Š Disease Classes**: 17 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
- **๐ŸŒ Web App**: Streamlit interface optimized for Hugging Face Spaces
- **๐Ÿ–ฅ๏ธ CLI Tool**: Command-line interface for batch processing
- **๏ฟฝ Training Pipeline**: Complete model training and evaluation system

## ๐Ÿ“ Project Structure

```
AiCropDiseasesDetection/
โ”œโ”€โ”€ ๐Ÿ“‚ api/                     # FastAPI backend
โ”‚   โ”œโ”€โ”€ main.py                 # API server with endpoints
โ”‚   โ”œโ”€โ”€ requirements.txt        # API dependencies
โ”‚   โ””โ”€โ”€ __init__.py             # Package marker
โ”œโ”€โ”€ ๐Ÿ“‚ data/                    # Dataset (train/val/test splits)
โ”‚   โ”œโ”€โ”€ train/                 # Training images
โ”‚   โ”œโ”€โ”€ val/                   # Validation images
โ”‚   โ””โ”€โ”€ test/                  # Test images
โ”œโ”€โ”€ ๐Ÿ“‚ knowledge_base/          # Disease information
โ”‚   โ””โ”€โ”€ disease_info.json      # Symptoms, treatments, prevention
โ”œโ”€โ”€ ๐Ÿ“‚ models/                  # Trained model weights
โ”‚   โ”œโ”€โ”€ crop_disease_v3_model.pth      # Latest V3 model (recommended)
โ”‚   โ””โ”€โ”€ README.txt              # Model information
โ”œโ”€โ”€ ๐Ÿ“‚ 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__}')"
```

## ๐Ÿ“– Usage Guide

### ๐ŸŒ Streamlit Web App (Recommended)

The easiest way to use the system:

```powershell
streamlit run app.py
```

**Features:**
- ๏ฟฝ **Image Upload**: Drag & drop or browse for crop leaf images
- ๐Ÿ” **AI Analysis**: One-click disease detection with confidence scores
- ๐Ÿ“Š **Visual Explanations**: Grad-CAM heatmaps showing AI focus areas
- ๐Ÿ“š **Disease Information**: Detailed symptoms, treatments, and prevention
- ๐ŸŽฏ **Risk Assessment**: Environmental risk level calculation
- โš™๏ธ **Settings**: Customizable analysis options

**Supported Image Formats**: JPG, JPEG, PNG, BMP

### ๐Ÿ“Š Model Training & Evaluation

Train and evaluate your own model with custom data:

```powershell
# Evaluate existing model
python -m src.evaluate

# Train new model
python -m src.train

# Generate visual explanations
python -m src.explain
```

### ๐Ÿ” CLI Prediction Tool

Quick single-image prediction via command line:

```powershell
# Predict disease for a single image
python -m src.predict_cli -i test_leaf_sample.jpg -m models\crop_disease_v3_model.pth

# With custom class names file
python -m src.predict_cli -i your_image.jpg --classes custom_classes.json
```

### ๐Ÿ”ฌ Jupyter Notebooks

Explore the training process interactively:

```powershell
jupyter notebook notebooks/train_resnet50.ipynb
```

## ๐Ÿ’ก Usage Examples

### Python Usage Example

```python
# For programmatic use
import sys
sys.path.append('src')

from src.model import CropDiseaseResNet50
from src.dataset import preprocess_image
import torch
from PIL import Image

# Load model
model = CropDiseaseResNet50(num_classes=15)
checkpoint = torch.load('models/crop_disease_v3_model.pth', map_location='cpu')
model.load_state_dict(checkpoint)
model.eval()

# Make prediction
image = Image.open('your_leaf_image.jpg')
input_tensor = preprocess_image(image)
with torch.no_grad():
    prediction = model(input_tensor)
    confidence = torch.softmax(prediction, dim=1).max().item()
    
print(f"Prediction confidence: {confidence:.2%}")
```

### Command Line Usage

```powershell
# Evaluate model performance
python -m src.evaluate

# Single image CLI prediction
python -m src.predict_cli -i test_leaf_sample.jpg -m models\crop_disease_v3_model.pth
```

### GUI Application Workflow

1. **Launch Application**: `python crop_disease_gui.py`
2. **Upload Image**: Click "๐Ÿ“ Select Image" button
3. **Analyze**: Click "๐Ÿ” Analyze Disease" button
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!**