Spaces:
Running
Running
import gradio as gr | |
import pickle | |
import numpy as np | |
import os | |
# Load the RandomForest model | |
working_dir = os.path.dirname(os.path.abspath(__file__)) | |
model = pickle.load(open(f'{working_dir}/RF_Crop.sav', 'rb')) | |
# Define the prediction function | |
def predict_crop(N, P, K, temperature, humidity, pH, rainfall): | |
user_input = np.array([[N, P, K, temperature, humidity, pH, rainfall]]) | |
if np.all(user_input == 0): | |
return "Please enter valid values." | |
else: | |
prediction = model.predict(user_input) | |
crop = prediction[0] | |
return f"Hey, you should grow **{crop}** based on your soil and environmental factors." | |
# Gradio UI components | |
def main_interface(): | |
with gr.Blocks() as demo: | |
with gr.Tab("Get Recommendation"): | |
gr.Markdown("Enter the details about your soil and environmental factors to get a crop recommendation.") | |
gr.Markdown("**Example Values:** [104, 18, 30, 23.6, 60.3, 6.7, 140.91] or [60, 18, 30, 23.6, 60.3, 8, 40.91]") | |
N = gr.Number(label="Nitrogen (N)", value=0, precision=0) | |
P = gr.Number(label="Phosphorus (P)", value=0, precision=0) | |
K = gr.Number(label="Potassium (K)", value=0, precision=0) | |
temperature = gr.Number(label="Temperature (°C)", value=0.0) | |
humidity = gr.Number(label="Humidity (%)", value=0.0) | |
pH = gr.Number(label="pH", value=0.0) | |
rainfall = gr.Number(label="Rainfall (mm)", value=0.0) | |
output = gr.Textbox(label="Recommendation", interactive=False) | |
gr.Button("Predict").click( | |
predict_crop, | |
inputs=[N, P, K, temperature, humidity, pH, rainfall], | |
outputs=output | |
) | |
return demo | |
# Run the Gradio app | |
if __name__ == "__main__": | |
app = main_interface() | |
app.launch() | |