Spaces:
Sleeping
Sleeping
Upload 4 files
Browse files- final_model.joblib +3 -0
- label_encoder.joblib +3 -0
- main.py +129 -0
- requirements.txt +9 -0
final_model.joblib
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a6e8f57ad9c823b75d7c622047b4c0486ade556788767ba079b353a6df018e44
|
| 3 |
+
size 32528345
|
label_encoder.joblib
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7f768bc83fabe555d39a6a0087b4a3aefbba39029dd57f0d07d7dc6b072a66da
|
| 3 |
+
size 985
|
main.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException
|
| 2 |
+
from pydantic import BaseModel, Field
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import joblib
|
| 5 |
+
import os
|
| 6 |
+
import logging
|
| 7 |
+
import numpy as np
|
| 8 |
+
from typing import List, Dict
|
| 9 |
+
|
| 10 |
+
# Set up logging
|
| 11 |
+
logging.basicConfig(level=logging.INFO)
|
| 12 |
+
logger = logging.getLogger(__name__)
|
| 13 |
+
|
| 14 |
+
app = FastAPI(title="Crop Recommendation API")
|
| 15 |
+
|
| 16 |
+
# Define model file paths
|
| 17 |
+
MODEL_PATH = r"final_model.joblib"
|
| 18 |
+
ENCODER_PATH = r"label_encoder.joblib"
|
| 19 |
+
|
| 20 |
+
# Load model and encoder at startup
|
| 21 |
+
try:
|
| 22 |
+
final_RF = joblib.load(MODEL_PATH)
|
| 23 |
+
label_encoder = joblib.load(ENCODER_PATH)
|
| 24 |
+
VALID_CROPS = list(label_encoder.classes_)
|
| 25 |
+
logger.info("Model and encoder loaded successfully")
|
| 26 |
+
except Exception as e:
|
| 27 |
+
logger.error(f"Failed to load model or encoder: {str(e)}")
|
| 28 |
+
raise Exception(f"Failed to load model or encoder: {str(e)}")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# Pydantic model for input validation
|
| 32 |
+
class CropInput(BaseModel):
|
| 33 |
+
N: float = Field(..., ge=0, le=200, description="Nitrogen content in soil (kg/ha)")
|
| 34 |
+
P: float = Field(
|
| 35 |
+
..., ge=0, le=200, description="Phosphorus content in soil (kg/ha)"
|
| 36 |
+
)
|
| 37 |
+
K: float = Field(..., ge=0, le=200, description="Potassium content in soil (kg/ha)")
|
| 38 |
+
temperature: float = Field(..., ge=0, le=50, description="Temperature in Celsius")
|
| 39 |
+
ph: float = Field(..., ge=0, le=14, description="Soil pH value")
|
| 40 |
+
rainfall: float = Field(..., ge=0, le=2000, description="Rainfall in millimeters")
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def get_top_n_classes(
|
| 44 |
+
model, X_df: pd.DataFrame, label_encoder, n: int = 5
|
| 45 |
+
) -> List[Dict]:
|
| 46 |
+
"""Get the top N predicted classes with their probabilities."""
|
| 47 |
+
try:
|
| 48 |
+
probs = model.predict_proba(X_df)[0]
|
| 49 |
+
top_indices = np.argsort(probs)[::-1][:n]
|
| 50 |
+
top_probs = probs[top_indices]
|
| 51 |
+
top_labels = label_encoder.inverse_transform(top_indices)
|
| 52 |
+
return [
|
| 53 |
+
{"crop": label, "probability": float(prob)}
|
| 54 |
+
for label, prob in zip(top_labels, top_probs)
|
| 55 |
+
]
|
| 56 |
+
except Exception as e:
|
| 57 |
+
logger.error(f"Error in get_top_n_classes: {str(e)}")
|
| 58 |
+
raise ValueError(f"Failed to compute top classes: {str(e)}")
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# Synchronous prediction function
|
| 62 |
+
def predict_crop(input_data: Dict) -> Dict:
|
| 63 |
+
try:
|
| 64 |
+
# Convert input to DataFrame
|
| 65 |
+
input_df = pd.DataFrame([input_data])
|
| 66 |
+
|
| 67 |
+
# Validate required columns
|
| 68 |
+
required_cols = ["N", "P", "K", "temperature", "ph", "rainfall"]
|
| 69 |
+
missing_cols = set(required_cols) - set(input_df.columns)
|
| 70 |
+
if missing_cols:
|
| 71 |
+
raise ValueError(f"Missing required columns: {missing_cols}")
|
| 72 |
+
|
| 73 |
+
# Get top 5 predictions
|
| 74 |
+
top_predictions = get_top_n_classes(final_RF, input_df, label_encoder, n=5)
|
| 75 |
+
|
| 76 |
+
return {"predictions": top_predictions, "status": "success"}
|
| 77 |
+
except Exception as e:
|
| 78 |
+
logger.error(f"Prediction error: {str(e)}")
|
| 79 |
+
return {"predictions": [], "status": "failure", "error": str(e)}
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@app.post("/predict_crop")
|
| 83 |
+
async def predict_crop_endpoint(input_data: CropInput):
|
| 84 |
+
try:
|
| 85 |
+
# Check if files exist
|
| 86 |
+
for path in [MODEL_PATH, ENCODER_PATH]:
|
| 87 |
+
if not os.path.exists(path):
|
| 88 |
+
raise HTTPException(status_code=500, detail=f"File not found: {path}")
|
| 89 |
+
|
| 90 |
+
# Convert Pydantic model to dict
|
| 91 |
+
input_dict = input_data.dict()
|
| 92 |
+
|
| 93 |
+
# Make prediction
|
| 94 |
+
result = predict_crop(input_dict)
|
| 95 |
+
|
| 96 |
+
if result["status"] == "failure":
|
| 97 |
+
raise HTTPException(status_code=400, detail=result["error"])
|
| 98 |
+
|
| 99 |
+
return result
|
| 100 |
+
|
| 101 |
+
except Exception as e:
|
| 102 |
+
logger.error(f"Error processing prediction: {str(e)}")
|
| 103 |
+
raise HTTPException(
|
| 104 |
+
status_code=500, detail=f"Error processing prediction: {str(e)}"
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
@app.get("/")
|
| 109 |
+
async def root():
|
| 110 |
+
return {
|
| 111 |
+
"message": "Crop Recommendation API is running. Use /predict_crop endpoint to send input data."
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
@app.get("/valid_inputs")
|
| 116 |
+
async def get_valid_inputs():
|
| 117 |
+
return {
|
| 118 |
+
"N": {"min": 0, "max": 200, "unit": "kg/ha"},
|
| 119 |
+
"P": {"min": 0, "max": 200, "unit": "kg/ha"},
|
| 120 |
+
"K": {"min": 0, "max": 200, "unit": "kg/ha"},
|
| 121 |
+
"temperature": {"min": 0, "max": 50, "unit": "Celsius"},
|
| 122 |
+
"ph": {"min": 0, "max": 14, "unit": "pH"},
|
| 123 |
+
"rainfall": {"min": 0, "max": 2000, "unit": "mm"},
|
| 124 |
+
"possible_crops": VALID_CROPS,
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
# conda activate crop_new
|
| 129 |
+
# uvicorn crop_recommender:app --host 0.0.0.0 --port 8004
|
requirements.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi==0.112.2
|
| 2 |
+
uvicorn==0.32.1
|
| 3 |
+
pandas==2.2.3
|
| 4 |
+
scikit-learn==1.6.1
|
| 5 |
+
numpy==2.0.2
|
| 6 |
+
joblib==1.4.2
|
| 7 |
+
pydantic==2.10.3
|
| 8 |
+
markupsafe==2.1.5
|
| 9 |
+
anyio==4.7.0
|