File size: 1,532 Bytes
f89389e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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)