File size: 6,921 Bytes
36dd4e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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
# πŸš€ 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.