crop / app.py
MAHENDRA REDDY
Add application file
f89389e
import gradio as gr
import pandas as pd
import joblib
# Load model
best_model = joblib.load("crop_recommendation_model.pkl")
y_labels = best_model.classes_
# Prediction function
def predict_crop(N, P, K, temperature, humidity, ph, rainfall):
input_df = pd.DataFrame([[N, P, K, temperature, humidity, ph, rainfall]],
columns=['N', 'P', 'K', 'temperature', 'humidity', 'ph', 'rainfall'])
prediction = best_model.predict(input_df)[0]
probabilities = best_model.predict_proba(input_df)[0]
sorted_probs = sorted(enumerate(probabilities), key=lambda x: x[1], reverse=True)
best_crop = prediction
alternatives = [y_labels[i] for i, _ in sorted_probs[1:4]]
return f"✅ Best Crop: {best_crop}", f"✨ Alternatives: {', '.join(alternatives)}"
# Gradio Interface with api_name enabled
interface = gr.Interface(
fn=predict_crop,
inputs=[
gr.Number(label="Nitrogen (N)"),
gr.Number(label="Phosphorous (P)"),
gr.Number(label="Potassium (K)"),
gr.Number(label="Temperature (°C)"),
gr.Number(label="Humidity (%)"),
gr.Number(label="pH"),
gr.Number(label="Rainfall (mm)")
],
outputs=[
gr.Textbox(label="Best Crop"),
gr.Textbox(label="Alternative Crops")
],
title="🌱 Smart Crop Recommender",
description="Predicts the best crop and top 3 alternatives based on your soil and climate data.",
api_name="/api/predict" # 👈 This enables API endpoint!
)
interface.launch(share=True)