|
|
"""
|
|
|
Gradio web app for Crop Recommendation System
|
|
|
Deploy to Hugging Face Spaces
|
|
|
"""
|
|
|
|
|
|
import json
|
|
|
import joblib
|
|
|
import numpy as np
|
|
|
import pandas as pd
|
|
|
import gradio as gr
|
|
|
from pathlib import Path
|
|
|
|
|
|
|
|
|
MODEL_PATH = "model.pkl"
|
|
|
META_PATH = "model_meta.json"
|
|
|
|
|
|
def load_model_and_metadata():
|
|
|
"""Load trained model and metadata."""
|
|
|
if not Path(MODEL_PATH).exists():
|
|
|
raise FileNotFoundError(f"Model not found at {MODEL_PATH}")
|
|
|
if not Path(META_PATH).exists():
|
|
|
raise FileNotFoundError(f"Metadata not found at {META_PATH}")
|
|
|
|
|
|
model = joblib.load(MODEL_PATH)
|
|
|
with open(META_PATH) as f:
|
|
|
meta = json.load(f)
|
|
|
|
|
|
return model, meta
|
|
|
|
|
|
|
|
|
try:
|
|
|
model, meta = load_model_and_metadata()
|
|
|
numeric_cols = meta["numeric_cols"]
|
|
|
label_classes = meta["label_classes"]
|
|
|
except Exception as e:
|
|
|
raise RuntimeError(f"Failed to load model: {e}")
|
|
|
|
|
|
def predict_crop(N, P, K, temperature, humidity, ph, rainfall):
|
|
|
"""
|
|
|
Predict crop recommendation based on soil and weather parameters.
|
|
|
|
|
|
Args:
|
|
|
N: Nitrogen content in soil (0-140)
|
|
|
P: Phosphorus content in soil (5-145)
|
|
|
K: Potassium content in soil (5-205)
|
|
|
temperature: Average temperature in Celsius (8-44)
|
|
|
humidity: Relative humidity in % (14-100)
|
|
|
ph: pH of soil (3.5-10)
|
|
|
rainfall: Annual rainfall in mm (20-3000)
|
|
|
|
|
|
Returns:
|
|
|
Tuple of (recommended_crop, confidence, top_3_dict)
|
|
|
"""
|
|
|
|
|
|
input_data = pd.DataFrame({
|
|
|
'N': [N],
|
|
|
'P': [P],
|
|
|
'K': [K],
|
|
|
'temperature': [temperature],
|
|
|
'humidity': [humidity],
|
|
|
'ph': [ph],
|
|
|
'rainfall': [rainfall]
|
|
|
})
|
|
|
|
|
|
|
|
|
prediction_encoded = model.predict(input_data)[0]
|
|
|
probabilities = model.predict_proba(input_data)[0]
|
|
|
|
|
|
|
|
|
recommended_crop = label_classes[prediction_encoded]
|
|
|
confidence = probabilities[prediction_encoded]
|
|
|
|
|
|
|
|
|
top_3_indices = np.argsort(probabilities)[::-1][:3]
|
|
|
top_3_dict = {}
|
|
|
for rank, idx in enumerate(top_3_indices, 1):
|
|
|
crop = label_classes[idx]
|
|
|
conf = probabilities[idx]
|
|
|
top_3_dict[f"{rank}. {crop}"] = f"{conf:.2%}"
|
|
|
|
|
|
return recommended_crop, f"{confidence:.2%}", top_3_dict
|
|
|
|
|
|
|
|
|
with gr.Blocks(title="Crop Recommendation System", theme=gr.themes.Soft()) as demo:
|
|
|
gr.Markdown("""
|
|
|
# πΎ Crop Recommendation System
|
|
|
|
|
|
Enter soil and weather parameters to get AI-powered crop recommendations with confidence scores.
|
|
|
""")
|
|
|
|
|
|
with gr.Row():
|
|
|
with gr.Column(scale=1):
|
|
|
gr.Markdown("### Soil Parameters")
|
|
|
N = gr.Slider(label="Nitrogen (N)", minimum=0, maximum=140, value=90, step=1)
|
|
|
P = gr.Slider(label="Phosphorus (P)", minimum=5, maximum=145, value=42, step=1)
|
|
|
K = gr.Slider(label="Potassium (K)", minimum=5, maximum=205, value=43, step=1)
|
|
|
|
|
|
with gr.Column(scale=1):
|
|
|
gr.Markdown("### Weather Parameters")
|
|
|
temperature = gr.Slider(label="Temperature (Β°C)", minimum=8, maximum=44, value=21, step=0.1)
|
|
|
humidity = gr.Slider(label="Humidity (%)", minimum=14, maximum=100, value=82, step=1)
|
|
|
ph = gr.Slider(label="Soil pH", minimum=3.5, maximum=10, value=6.5, step=0.1)
|
|
|
rainfall = gr.Slider(label="Annual Rainfall (mm)", minimum=20, maximum=3000, value=203, step=10)
|
|
|
|
|
|
predict_btn = gr.Button("π Get Crop Recommendation", variant="primary", size="lg")
|
|
|
|
|
|
with gr.Row():
|
|
|
with gr.Column(scale=2):
|
|
|
recommended = gr.Textbox(
|
|
|
label="πΎ Recommended Crop",
|
|
|
interactive=False,
|
|
|
text_align="center",
|
|
|
scale=1
|
|
|
)
|
|
|
confidence = gr.Textbox(
|
|
|
label="β
Confidence",
|
|
|
interactive=False,
|
|
|
text_align="center",
|
|
|
scale=1
|
|
|
)
|
|
|
|
|
|
with gr.Column(scale=1):
|
|
|
top_3 = gr.JSON(label="π Top 3 Recommendations", interactive=False)
|
|
|
|
|
|
predict_btn.click(
|
|
|
fn=predict_crop,
|
|
|
inputs=[N, P, K, temperature, humidity, ph, rainfall],
|
|
|
outputs=[recommended, confidence, top_3]
|
|
|
)
|
|
|
|
|
|
gr.Markdown("""
|
|
|
---
|
|
|
### Parameter Ranges (based on training data)
|
|
|
- **Nitrogen (N)**: 0-140 kg/ha
|
|
|
- **Phosphorus (P)**: 5-145 kg/ha
|
|
|
- **Potassium (K)**: 5-205 kg/ha
|
|
|
- **Temperature**: 8-44Β°C
|
|
|
- **Humidity**: 14-100%
|
|
|
- **pH**: 3.5-10
|
|
|
- **Rainfall**: 20-3000 mm/year
|
|
|
""")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
demo.launch(share=False)
|
|
|
|