Spaces:
Build error
Build error
MAHENDRA REDDY commited on
Commit ·
f89389e
1
Parent(s): d51fd74
Add application file
Browse files
app.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import joblib
|
| 4 |
+
# Load model
|
| 5 |
+
best_model = joblib.load("crop_recommendation_model.pkl")
|
| 6 |
+
y_labels = best_model.classes_
|
| 7 |
+
# Prediction function
|
| 8 |
+
def predict_crop(N, P, K, temperature, humidity, ph, rainfall):
|
| 9 |
+
input_df = pd.DataFrame([[N, P, K, temperature, humidity, ph, rainfall]],
|
| 10 |
+
columns=['N', 'P', 'K', 'temperature', 'humidity', 'ph', 'rainfall'])
|
| 11 |
+
|
| 12 |
+
prediction = best_model.predict(input_df)[0]
|
| 13 |
+
probabilities = best_model.predict_proba(input_df)[0]
|
| 14 |
+
sorted_probs = sorted(enumerate(probabilities), key=lambda x: x[1], reverse=True)
|
| 15 |
+
|
| 16 |
+
best_crop = prediction
|
| 17 |
+
alternatives = [y_labels[i] for i, _ in sorted_probs[1:4]]
|
| 18 |
+
|
| 19 |
+
return f"✅ Best Crop: {best_crop}", f"✨ Alternatives: {', '.join(alternatives)}"
|
| 20 |
+
# Gradio Interface with api_name enabled
|
| 21 |
+
interface = gr.Interface(
|
| 22 |
+
fn=predict_crop,
|
| 23 |
+
inputs=[
|
| 24 |
+
gr.Number(label="Nitrogen (N)"),
|
| 25 |
+
gr.Number(label="Phosphorous (P)"),
|
| 26 |
+
gr.Number(label="Potassium (K)"),
|
| 27 |
+
gr.Number(label="Temperature (°C)"),
|
| 28 |
+
gr.Number(label="Humidity (%)"),
|
| 29 |
+
gr.Number(label="pH"),
|
| 30 |
+
gr.Number(label="Rainfall (mm)")
|
| 31 |
+
],
|
| 32 |
+
outputs=[
|
| 33 |
+
gr.Textbox(label="Best Crop"),
|
| 34 |
+
gr.Textbox(label="Alternative Crops")
|
| 35 |
+
],
|
| 36 |
+
title="🌱 Smart Crop Recommender",
|
| 37 |
+
description="Predicts the best crop and top 3 alternatives based on your soil and climate data.",
|
| 38 |
+
api_name="/api/predict" # 👈 This enables API endpoint!
|
| 39 |
+
)
|
| 40 |
+
interface.launch(share=True)
|