Spaces:
Sleeping
Sleeping
| # π 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 | |