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
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
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
# πŸš€ Complete API Documentation - Crop Recommendation System

## Overview

The Crop Recommendation System now includes **THREE powerful endpoints**:

1. **`/predict`** - Crop recommendation based on soil/climate data
2. **`/analyze-image`** - AI-powered image analysis for crops/soil
3. **`/health`** - System health check

All endpoints feature **multi-model fallback** across NVIDIA and Gemini APIs.

---

## πŸ“Š Endpoint 1: Crop Prediction

### `POST /predict`

Predicts optimal crop based on soil and climate parameters with AI-generated suggestions.

#### Request

**Content-Type:** `application/x-www-form-urlencoded` or `multipart/form-data`

**Parameters:**

| Parameter | Type | Required | Description | Example |
|-----------|------|----------|-------------|---------|
| nitrogen | float | Yes | Nitrogen content (kg/ha) | 90 |
| phosphorus | float | Yes | Phosphorus content (kg/ha) | 42 |
| potassium | float | Yes | Potassium content (kg/ha) | 43 |
| temperature | float | Yes | Average temperature (Β°C) | 20.87 |
| humidity | float | Yes | Relative humidity (%) | 82.00 |
| ph | float | Yes | Soil pH level (0-14) | 6.50 |
| rainfall | float | Yes | Average rainfall (mm) | 202.93 |
| location | string | Yes | Geographic location | "Maharashtra, India" |

#### Example Request (curl)

```bash

curl -X POST http://localhost:7860/predict \

  -F "nitrogen=90" \

  -F "phosphorus=42" \

  -F "potassium=43" \

  -F "temperature=20.87" \

  -F "humidity=82.00" \

  -F "ph=6.50" \

  -F "rainfall=202.93" \

  -F "location=Maharashtra, India"

```

#### Example Request (Python)

```python

import requests



data = {

    'nitrogen': 90,

    'phosphorus': 42,

    'potassium': 43,

    'temperature': 20.87,

    'humidity': 82.00,

    'ph': 6.50,

    'rainfall': 202.93,

    'location': 'Maharashtra, India'

}



response = requests.post('http://localhost:7860/predict', data=data)

print(response.json())

```

#### Example Request (JavaScript)

```javascript

const formData = new FormData();

formData.append('nitrogen', '90');

formData.append('phosphorus', '42');

formData.append('potassium', '43');

formData.append('temperature', '20.87');

formData.append('humidity', '82.00');

formData.append('ph', '6.50');

formData.append('rainfall', '202.93');

formData.append('location', 'Maharashtra, India');



fetch('http://localhost:7860/predict', {

    method: 'POST',

    body: formData

})

.then(response => response.json())

.then(data => console.log(data));

```

#### Response (Success - 200)

```json

{

  "predicted_crop": "RICE",

  "ai_suggestions": "RICE is an excellent choice for the given conditions with high humidity (82%) and substantial rainfall (202.93mm). The soil NPK values (90-42-43) are well-suited for rice cultivation, providing adequate nutrients for optimal growth.\n\nOther recommended crops:\n1. JUTE\n2. COCONUT\n3. PAPAYA\n4. BANANA",

  "location": "Maharashtra, India"

}

```

#### Response (Error - 500)

```json

{

  "error": "An error occurred during prediction. Please try again.",

  "details": "Error message details"

}

```

#### AI Model Fallback Order (Text Generation)

1. **NVIDIA Models** (Phase 1):
   - `nvidia/llama-3.1-nemotron-70b-instruct`
   - `meta/llama-3.1-405b-instruct`
   - `meta/llama-3.1-70b-instruct`
   - `mistralai/mixtral-8x7b-instruct-v0.1`

2. **Gemini Models** (Phase 2):
   - `gemini-2.0-flash-exp`
   - `gemini-1.5-flash`
   - `gemini-1.5-flash-8b`
   - `gemini-1.5-pro`

---

## πŸ–ΌοΈ Endpoint 2: Image Analysis

### `POST /analyze-image`

Analyzes agricultural images (crops, soil, plants) using AI vision models.

#### Request

**Content-Type:** `multipart/form-data`

**Parameters:**

| Parameter | Type | Required | Description | Example |
|-----------|------|----------|-------------|---------|
| image | file | Yes | Image file (JPG, PNG) | crop_field.jpg |

| prompt | string | No | Custom analysis prompt | "Identify crop diseases" |



#### Example Request (curl)



```bash

curl -X POST http://localhost:7860/analyze-image \

  -F "image=@/path/to/crop_image.jpg" \
  -F "prompt=Analyze this crop image and identify any diseases or issues"
```



#### Example Request (Python)



```python

import requests



files = {

    'image': open('crop_image.jpg', 'rb')

}



data = {

    'prompt': 'Analyze this crop image and identify any diseases or issues'

}



response = requests.post('http://localhost:7860/analyze-image', 

                        files=files, 

                        data=data)

print(response.json())

```

#### Example Request (JavaScript)

```javascript

const formData = new FormData();

const fileInput = document.querySelector('input[type="file"]');

formData.append('image', fileInput.files[0]);

formData.append('prompt', 'Analyze this crop image');



fetch('http://localhost:7860/analyze-image', {

    method: 'POST',

    body: formData

})

.then(response => response.json())

.then(data => console.log(data));

```

#### Response (Success - 200)

```json

{

  "analysis": "The image shows a healthy rice crop in the vegetative stage. The plants display vibrant green color indicating good nitrogen availability. No visible signs of disease or pest damage. The crop appears to be well-watered with adequate spacing between plants. Recommendations: Continue current nutrient management, monitor for blast disease during heading stage, ensure proper water management.",

  "filename": "crop_image.jpg"

}

```

#### Response (Error - 400)

```json

{

  "error": "No image file provided",

  "details": "Please upload an image file"

}

```

#### Response (Error - 500)

```json

{

  "error": "An error occurred during image analysis. Please try again.",

  "details": "Error message details"

}

```

#### AI Model Fallback Order (Vision)

1. **NVIDIA Vision Models** (Phase 1):
   - `meta/llama-3.2-90b-vision-instruct`
   - `meta/llama-3.2-11b-vision-instruct`
   - `microsoft/phi-3-vision-128k-instruct`
   - `nvidia/neva-22b`

2. **Gemini Vision Models** (Phase 2):
   - `gemini-2.0-flash-exp`
   - `gemini-1.5-flash`
   - `gemini-1.5-flash-8b`
   - `gemini-1.5-pro`

#### Supported Image Formats

- JPG/JPEG
- PNG
- WebP
- BMP
- GIF

#### Image Size Recommendations

- **Minimum:** 224x224 pixels
- **Maximum:** 4096x4096 pixels
- **File Size:** < 10MB recommended

---

## πŸ₯ Endpoint 3: Health Check

### `GET /health`

Returns system health status and configuration information.

#### Request

```bash

curl http://localhost:7860/health

```

#### Response (200)

```json

{

  "status": "healthy",

  "nvidia_api_configured": true,

  "gemini_api_configured": true,

  "text_models_available": 8,

  "vision_models_available": 8

}

```

---

## πŸ”§ Configuration

### Environment Variables

Create a `.env` file:

```bash

# Gemini API Key

GEMINI_API=your_gemini_api_key_here



# NVIDIA API Key

NVIDIA_API_KEY=your_nvidia_api_key_here

```

### Model Configuration

Edit `app.py` to customize models:

```python

# Text generation models

NVIDIA_TEXT_MODELS = [

    "nvidia/llama-3.1-nemotron-70b-instruct",

    # Add more models...

]



# Vision models

NVIDIA_VISION_MODELS = [

    "meta/llama-3.2-90b-vision-instruct",

    # Add more models...

]



# Gemini models (used for both text and vision)

GEMINI_MODELS = [

    "gemini-2.0-flash-exp",

    # Add more models...

]

```

---

## 🎯 Use Cases

### Use Case 1: Crop Recommendation for Farmers

```python

# Farmer inputs soil test results

data = {

    'nitrogen': 85,

    'phosphorus': 40,

    'potassium': 45,

    'temperature': 25.5,

    'humidity': 75,

    'ph': 6.8,

    'rainfall': 180,

    'location': 'Punjab, India'

}



response = requests.post('http://localhost:7860/predict', data=data)

result = response.json()



print(f"Recommended Crop: {result['predicted_crop']}")

print(f"AI Suggestions: {result['ai_suggestions']}")

```

### Use Case 2: Disease Detection from Crop Images

```python

# Upload crop image for disease analysis

files = {'image': open('diseased_crop.jpg', 'rb')}

data = {'prompt': 'Identify any diseases, pests, or nutrient deficiencies in this crop'}



response = requests.post('http://localhost:7860/analyze-image', 

                        files=files, data=data)

result = response.json()



print(f"Analysis: {result['analysis']}")

```

### Use Case 3: Soil Quality Assessment

```python

# Upload soil image for quality analysis

files = {'image': open('soil_sample.jpg', 'rb')}

data = {'prompt': 'Analyze soil quality, texture, and moisture content'}



response = requests.post('http://localhost:7860/analyze-image', 

                        files=files, data=data)

result = response.json()



print(f"Soil Analysis: {result['analysis']}")

```

---

## πŸ”„ Fallback System Behavior

### Scenario 1: All APIs Working
- **Response Time:** 1-3 seconds
- **Model Used:** First NVIDIA model
- **Console Output:** βœ… Success with first model

### Scenario 2: NVIDIA API Down
- **Response Time:** 3-6 seconds
- **Model Used:** First available Gemini model
- **Console Output:** Multiple ❌ for NVIDIA, then βœ… for Gemini

### Scenario 3: All APIs Fail
- **Response Time:** 8-15 seconds
- **Model Used:** Generic fallback
- **Console Output:** All ❌, generic response returned

---

## πŸ“Š Response Times

| Endpoint | Typical | With Fallback | Maximum |
|----------|---------|---------------|---------|
| `/predict` | 1-3s | 3-6s | 15s |
| `/analyze-image` | 2-5s | 5-10s | 20s |
| `/health` | <100ms | N/A | <100ms |

---

## πŸ› Error Handling

### Common Errors

#### 1. Missing Image File (400)
```json

{

  "error": "No image file provided",

  "details": "Please upload an image file"

}

```

**Solution:** Ensure `image` field is included in multipart form data

#### 2. Invalid Parameters (500)
```json

{

  "error": "An error occurred during prediction. Please try again.",

  "details": "could not convert string to float: 'abc'"

}

```

**Solution:** Ensure all numeric parameters are valid numbers

#### 3. All Models Failed (200 with fallback)
```json

{

  "predicted_crop": "RICE",

  "ai_suggestions": "Note: AI suggestions are temporarily unavailable..."

}

```

**Solution:** Check API keys and internet connection

---

## πŸ§ͺ Testing

### Test Script (Python)

```python

import requests



# Test 1: Health Check

print("Testing health endpoint...")

health = requests.get('http://localhost:7860/health')

print(health.json())



# Test 2: Crop Prediction

print("\nTesting prediction endpoint...")

data = {

    'nitrogen': 90, 'phosphorus': 42, 'potassium': 43,

    'temperature': 20.87, 'humidity': 82.00, 'ph': 6.50,

    'rainfall': 202.93, 'location': 'Test Location'

}

prediction = requests.post('http://localhost:7860/predict', data=data)

print(prediction.json())



# Test 3: Image Analysis

print("\nTesting image analysis endpoint...")

files = {'image': open('test_image.jpg', 'rb')}

analysis = requests.post('http://localhost:7860/analyze-image', files=files)

print(analysis.json())

```

---

## πŸ“š Additional Resources

- **NVIDIA NIM API:** https://docs.nvidia.com/nim/
- **Gemini API:** https://ai.google.dev/docs
- **Flask Documentation:** https://flask.palletsprojects.com/

---

## πŸŽ‰ Summary

Your Crop Recommendation System now has:

βœ… **3 Powerful Endpoints**
- Crop prediction with AI suggestions
- Image analysis for crops/soil
- Health monitoring

βœ… **16 AI Models Total**
- 4 NVIDIA text models
- 4 NVIDIA vision models
- 4 Gemini models (text)
- 4 Gemini models (vision)

βœ… **Enterprise-Grade Reliability**
- Automatic failover
- Graceful degradation
- Comprehensive error handling

βœ… **Production Ready**
- RESTful API design
- Proper error responses
- Health check endpoint