File size: 6,151 Bytes
bbd5f9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
# 🌾 Crop Yield Prediction API Documentation

## Overview
FastAPI-based REST API for crop yield prediction using Random Forest model.

## πŸš€ Quick Start

### Local Development
```bash
# Install dependencies
pip install fastapi uvicorn

# Run the API
uvicorn app:app --host 0.0.0.0 --port 8000

# API will be available at: http://localhost:8000
```

### Docker Deployment
```bash
# Build the container
docker build -t crop-yield-api .

# Run the container
docker run -p 8000:8000 crop-yield-api

# Or use docker-compose
docker-compose up -d
```

## πŸ“‹ API Endpoints

### Base URL
```
http://localhost:8000
```

---

## 🎯 Main Prediction Endpoint

### POST `/predict`
Predict crop yield based on agricultural parameters.

**Input Format (JSON):**
```json
{
  "year": 2024,
  "state": "Punjab",
  "crop": "Rice",
  "season": "Kharif",
  "area": 10.0,
  "production": 25.0,
  "rainfall": 1200,
  "fertilizer": 75,
  "pesticide": 8
}
```

**Fields:**
- `year` (required): Crop year (integer, e.g., 2024)
- `state` (required): State name (string, e.g., "Punjab")
- `crop` (required): Crop name (string, e.g., "Rice")
- `season` (required): Season (string, e.g., "Kharif", "Rabi", "Summer")
- `area` (required): Area in hectares (float)
- `production` (required): Production in tons (float)
- `rainfall` (optional): Annual rainfall in mm (float, default: 1000)
- `fertilizer` (optional): Fertilizer usage in kg (float, default: 50)
- `pesticide` (optional): Pesticide usage in kg (float, default: 5)

**Response Format:**
```json
{
  "model": "Random Forest",
  "predicted_yield": "2017.7 kg/hectare",
  "total_expected_production": "20.18 tons",
  "assessment": "Good yield expected"
}
```

**Example cURL Request:**
```bash
curl -X POST "http://localhost:8000/predict" \
-H "Content-Type: application/json" \
-d '{
  "year": 2024,
  "state": "Punjab",
  "crop": "Rice",
  "season": "Kharif",
  "area": 10.0,
  "production": 25.0,
  "rainfall": 1200,
  "fertilizer": 75,
  "pesticide": 8
}'
```

**Example Python Request:**
```python
import requests
import json

url = "http://localhost:8000/predict"
data = {
    "year": 2024,
    "state": "Punjab",
    "crop": "Rice",
    "season": "Kharif",
    "area": 10.0,
    "production": 25.0,
    "rainfall": 1200,
    "fertilizer": 75,
    "pesticide": 8
}

response = requests.post(url, json=data)
result = response.json()
print(json.dumps(result, indent=2))
```

---

## πŸ“Š Other Endpoints

### GET `/`
Root endpoint with API information.

**Response:**
```json
{
  "message": "Crop Yield Prediction API. Use /docs for interactive API documentation.",
  "version": "1.0.0",
  "endpoints": {
    "predict": "/predict",
    "health": "/health",
    "docs": "/docs",
    "available_options": "/available-options"
  }
}
```

### GET `/health`
Health check endpoint.

**Response:**
```json
{
  "status": "healthy",
  "timestamp": "2024-09-11T08:00:00.000000",
  "model_loaded": true
}
```

### GET `/available-options`
Get available states, crops, and seasons.

**Response:**
```json
{
  "states": ["Punjab", "Haryana", "Uttar Pradesh", "..."],
  "crops": ["Rice", "Wheat", "Maize", "..."],
  "seasons": ["Kharif", "Rabi", "Summer", "Whole Year", "Autumn", "Winter", "Total"],
  "note": "This shows first 10 states and crops. All are supported in predictions."
}
```

### GET `/docs`
Interactive API documentation (Swagger UI).

### GET `/redoc`
Alternative API documentation (ReDoc).

---

## 🎯 Assessment Levels

The API returns assessment based on predicted yield:

| Yield Range | Assessment |
|-------------|------------|
| > 3000 kg/hectare | "Excellent yield expected" |
| 2000-3000 kg/hectare | "Good yield expected" |
| 1000-2000 kg/hectare | "Moderate yield expected" |
| < 1000 kg/hectare | "Low yield expected" |

---

## ⚠️ Error Responses

### 400 Bad Request
```json
{
  "detail": "Missing required field: crop"
}
```

### 500 Internal Server Error
```json
{
  "detail": "Predictor not initialized. Please check if trained models are available."
}
```

---

## πŸ”§ Testing Examples

### Test Cases

**1. Complete Input:**
```json
{
  "year": 2024,
  "state": "Punjab",
  "crop": "Rice",
  "season": "Kharif",
  "area": 10.0,
  "production": 25.0,
  "rainfall": 1200,
  "fertilizer": 75,
  "pesticide": 8
}
```

**2. Minimal Input (using defaults):**
```json
{
  "year": 2024,
  "state": "Uttar Pradesh",
  "crop": "Wheat",
  "season": "Rabi",
  "area": 15.5,
  "production": 40.2
}
```

**3. Different Crop:**
```json
{
  "year": 2024,
  "state": "Maharashtra",
  "crop": "Sugarcane",
  "season": "Kharif",
  "area": 20.0,
  "production": 80.0,
  "rainfall": 800
}
```

---

## 🐳 Docker Commands

```bash
# Build image
docker build -t crop-yield-api .

# Run container
docker run -d -p 8000:8000 --name crop-api crop-yield-api

# View logs
docker logs crop-api

# Stop container
docker stop crop-api

# Remove container
docker rm crop-api
```

---

## πŸ“± Integration Notes

1. **Content-Type**: Always use `application/json`
2. **HTTP Method**: Use `POST` for predictions
3. **Required Fields**: year, state, crop, season, area, production
4. **Optional Fields**: rainfall, fertilizer, pesticide (have sensible defaults)
5. **Response Format**: Always returns JSON with units included in values
6. **Error Handling**: Check HTTP status codes and `detail` field in errors

---

## 🌍 Production Deployment

For production deployment, consider:

1. **Environment Variables**: Configure port, host via env vars
2. **Load Balancing**: Use nginx or similar for multiple instances  
3. **Monitoring**: Add logging and metrics collection
4. **Security**: Add authentication if needed
5. **CORS**: Configure CORS for web applications

---

## πŸ†˜ Troubleshooting

**Model Not Loading:**
- Ensure `trained_models/` directory exists with model files
- Check `preprocessor.pkl` and `random_forest_model.pkl` are present

**Port Already in Use:**
- Change port: `uvicorn app:app --port 8001`
- Kill existing process: `pkill -f uvicorn`

**API Not Responding:**
- Check health endpoint: `curl http://localhost:8000/health`
- View logs for errors
- Ensure all dependencies are installed