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
| 5 |
+
|
| 6 |
+
import json
|
| 7 |
+
import joblib
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pandas as pd
|
| 10 |
+
import gradio as gr
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
# Load model and metadata
|
| 14 |
+
MODEL_PATH = "model.pkl"
|
| 15 |
+
META_PATH = "model_meta.json"
|
| 16 |
+
|
| 17 |
+
def load_model_and_metadata():
|
| 18 |
+
"""Load trained model and metadata."""
|
| 19 |
+
if not Path(MODEL_PATH).exists():
|
| 20 |
+
raise FileNotFoundError(f"Model not found at {MODEL_PATH}")
|
| 21 |
+
if not Path(META_PATH).exists():
|
| 22 |
+
raise FileNotFoundError(f"Metadata not found at {META_PATH}")
|
| 23 |
+
|
| 24 |
+
model = joblib.load(MODEL_PATH)
|
| 25 |
+
with open(META_PATH) as f:
|
| 26 |
+
meta = json.load(f)
|
| 27 |
+
|
| 28 |
+
return model, meta
|
| 29 |
+
|
| 30 |
+
# Load model once at startup
|
| 31 |
+
try:
|
| 32 |
+
model, meta = load_model_and_metadata()
|
| 33 |
+
numeric_cols = meta["numeric_cols"]
|
| 34 |
+
label_classes = meta["label_classes"]
|
| 35 |
+
except Exception as e:
|
| 36 |
+
raise RuntimeError(f"Failed to load model: {e}")
|
| 37 |
+
|
| 38 |
+
def predict_crop(N, P, K, temperature, humidity, ph, rainfall):
|
| 39 |
+
"""
|
| 40 |
+
Predict crop recommendation based on soil and weather parameters.
|
| 41 |
+
|
| 42 |
+
Args:
|
| 43 |
+
N: Nitrogen content in soil (0-140)
|
| 44 |
+
P: Phosphorus content in soil (5-145)
|
| 45 |
+
K: Potassium content in soil (5-205)
|
| 46 |
+
temperature: Average temperature in Celsius (8-44)
|
| 47 |
+
humidity: Relative humidity in % (14-100)
|
| 48 |
+
ph: pH of soil (3.5-10)
|
| 49 |
+
rainfall: Annual rainfall in mm (20-3000)
|
| 50 |
+
|
| 51 |
+
Returns:
|
| 52 |
+
Tuple of (recommended_crop, confidence, top_3_dict)
|
| 53 |
+
"""
|
| 54 |
+
# Create input DataFrame
|
| 55 |
+
input_data = pd.DataFrame({
|
| 56 |
+
'N': [N],
|
| 57 |
+
'P': [P],
|
| 58 |
+
'K': [K],
|
| 59 |
+
'temperature': [temperature],
|
| 60 |
+
'humidity': [humidity],
|
| 61 |
+
'ph': [ph],
|
| 62 |
+
'rainfall': [rainfall]
|
| 63 |
+
})
|
| 64 |
+
|
| 65 |
+
# Predict
|
| 66 |
+
prediction_encoded = model.predict(input_data)[0]
|
| 67 |
+
probabilities = model.predict_proba(input_data)[0]
|
| 68 |
+
|
| 69 |
+
# Map to crop name
|
| 70 |
+
recommended_crop = label_classes[prediction_encoded]
|
| 71 |
+
confidence = probabilities[prediction_encoded]
|
| 72 |
+
|
| 73 |
+
# Get top 3
|
| 74 |
+
top_3_indices = np.argsort(probabilities)[::-1][:3]
|
| 75 |
+
top_3_dict = {}
|
| 76 |
+
for rank, idx in enumerate(top_3_indices, 1):
|
| 77 |
+
crop = label_classes[idx]
|
| 78 |
+
conf = probabilities[idx]
|
| 79 |
+
top_3_dict[f"{rank}. {crop}"] = f"{conf:.2%}"
|
| 80 |
+
|
| 81 |
+
return recommended_crop, f"{confidence:.2%}", top_3_dict
|
| 82 |
+
|
| 83 |
+
# Create Gradio interface
|
| 84 |
+
with gr.Blocks(title="Crop Recommendation System", theme=gr.themes.Soft()) as demo:
|
| 85 |
+
gr.Markdown("""
|
| 86 |
+
# 🌾 Crop Recommendation System
|
| 87 |
+
|
| 88 |
+
Enter soil and weather parameters to get AI-powered crop recommendations with confidence scores.
|
| 89 |
+
""")
|
| 90 |
+
|
| 91 |
+
with gr.Row():
|
| 92 |
+
with gr.Column(scale=1):
|
| 93 |
+
gr.Markdown("### Soil Parameters")
|
| 94 |
+
N = gr.Slider(label="Nitrogen (N)", minimum=0, maximum=140, value=90, step=1)
|
| 95 |
+
P = gr.Slider(label="Phosphorus (P)", minimum=5, maximum=145, value=42, step=1)
|
| 96 |
+
K = gr.Slider(label="Potassium (K)", minimum=5, maximum=205, value=43, step=1)
|
| 97 |
+
|
| 98 |
+
with gr.Column(scale=1):
|
| 99 |
+
gr.Markdown("### Weather Parameters")
|
| 100 |
+
temperature = gr.Slider(label="Temperature (°C)", minimum=8, maximum=44, value=21, step=0.1)
|
| 101 |
+
humidity = gr.Slider(label="Humidity (%)", minimum=14, maximum=100, value=82, step=1)
|
| 102 |
+
ph = gr.Slider(label="Soil pH", minimum=3.5, maximum=10, value=6.5, step=0.1)
|
| 103 |
+
rainfall = gr.Slider(label="Annual Rainfall (mm)", minimum=20, maximum=3000, value=203, step=10)
|
| 104 |
+
|
| 105 |
+
predict_btn = gr.Button("🔍 Get Crop Recommendation", variant="primary", size="lg")
|
| 106 |
+
|
| 107 |
+
with gr.Row():
|
| 108 |
+
with gr.Column(scale=2):
|
| 109 |
+
recommended = gr.Textbox(
|
| 110 |
+
label="🌾 Recommended Crop",
|
| 111 |
+
interactive=False,
|
| 112 |
+
text_align="center",
|
| 113 |
+
scale=1
|
| 114 |
+
)
|
| 115 |
+
confidence = gr.Textbox(
|
| 116 |
+
label="✅ Confidence",
|
| 117 |
+
interactive=False,
|
| 118 |
+
text_align="center",
|
| 119 |
+
scale=1
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
with gr.Column(scale=1):
|
| 123 |
+
top_3 = gr.JSON(label="📈 Top 3 Recommendations", interactive=False)
|
| 124 |
+
|
| 125 |
+
predict_btn.click(
|
| 126 |
+
fn=predict_crop,
|
| 127 |
+
inputs=[N, P, K, temperature, humidity, ph, rainfall],
|
| 128 |
+
outputs=[recommended, confidence, top_3]
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
gr.Markdown("""
|
| 132 |
+
---
|
| 133 |
+
### Parameter Ranges (based on training data)
|
| 134 |
+
- **Nitrogen (N)**: 0-140 kg/ha
|
| 135 |
+
- **Phosphorus (P)**: 5-145 kg/ha
|
| 136 |
+
- **Potassium (K)**: 5-205 kg/ha
|
| 137 |
+
- **Temperature**: 8-44°C
|
| 138 |
+
- **Humidity**: 14-100%
|
| 139 |
+
- **pH**: 3.5-10
|
| 140 |
+
- **Rainfall**: 20-3000 mm/year
|
| 141 |
+
""")
|
| 142 |
+
|
| 143 |
+
if __name__ == "__main__":
|
| 144 |
+
demo.launch(share=False)
|
model.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:55f4db2247f7113353648d1a4cefb13a83c156387261660211d7937a5aae5772
|
| 3 |
+
size 10637949
|
model_meta.json
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"target_col": "label",
|
| 3 |
+
"numeric_cols": [
|
| 4 |
+
"N",
|
| 5 |
+
"P",
|
| 6 |
+
"K",
|
| 7 |
+
"temperature",
|
| 8 |
+
"humidity",
|
| 9 |
+
"ph",
|
| 10 |
+
"rainfall"
|
| 11 |
+
],
|
| 12 |
+
"cat_cols": [],
|
| 13 |
+
"classes": [
|
| 14 |
+
"apple",
|
| 15 |
+
"banana",
|
| 16 |
+
"blackgram",
|
| 17 |
+
"chickpea",
|
| 18 |
+
"coconut",
|
| 19 |
+
"coffee",
|
| 20 |
+
"cotton",
|
| 21 |
+
"grapes",
|
| 22 |
+
"jute",
|
| 23 |
+
"kidneybeans",
|
| 24 |
+
"lentil",
|
| 25 |
+
"maize",
|
| 26 |
+
"mango",
|
| 27 |
+
"mothbeans",
|
| 28 |
+
"mungbean",
|
| 29 |
+
"muskmelon",
|
| 30 |
+
"orange",
|
| 31 |
+
"papaya",
|
| 32 |
+
"pigeonpeas",
|
| 33 |
+
"pomegranate",
|
| 34 |
+
"rice",
|
| 35 |
+
"watermelon"
|
| 36 |
+
],
|
| 37 |
+
"label_classes": [
|
| 38 |
+
"apple",
|
| 39 |
+
"banana",
|
| 40 |
+
"blackgram",
|
| 41 |
+
"chickpea",
|
| 42 |
+
"coconut",
|
| 43 |
+
"coffee",
|
| 44 |
+
"cotton",
|
| 45 |
+
"grapes",
|
| 46 |
+
"jute",
|
| 47 |
+
"kidneybeans",
|
| 48 |
+
"lentil",
|
| 49 |
+
"maize",
|
| 50 |
+
"mango",
|
| 51 |
+
"mothbeans",
|
| 52 |
+
"mungbean",
|
| 53 |
+
"muskmelon",
|
| 54 |
+
"orange",
|
| 55 |
+
"papaya",
|
| 56 |
+
"pigeonpeas",
|
| 57 |
+
"pomegranate",
|
| 58 |
+
"rice",
|
| 59 |
+
"watermelon"
|
| 60 |
+
],
|
| 61 |
+
"use_smote": false,
|
| 62 |
+
"optuna_best_params": {
|
| 63 |
+
"n_estimators": 679,
|
| 64 |
+
"max_depth": 11,
|
| 65 |
+
"learning_rate": 0.1491643700183361,
|
| 66 |
+
"subsample": 0.9942200798137729,
|
| 67 |
+
"colsample_bytree": 0.8219727639354084,
|
| 68 |
+
"gamma": 0.009290561506072492,
|
| 69 |
+
"reg_lambda": 0.05810214543756159,
|
| 70 |
+
"reg_alpha": 0.0030983439938857015
|
| 71 |
+
}
|
| 72 |
+
}
|