shubham5027's picture
Create app.py
1a94b3f verified
raw
history blame
1.98 kB
import gradio as gr
import pickle
import numpy as np
# Load the trained model
model_file = 'Yield_Ridge.sav'
with open(model_file, 'rb') as file:
model = pickle.load(file)
# Define prediction function
def predict_yield(crop: str, year: int, rainfall: float, temperature: float, fertilizer: float):
"""
Predicts crop yield based on user inputs.
Parameters:
crop (str): Name of the crop.
year (int): Year of prediction.
rainfall (float): Average annual rainfall (in mm).
temperature (float): Average annual temperature (in °C).
fertilizer (float): Amount of fertilizer used (in kg/ha).
Returns:
str: Predicted yield (in tons per hectare).
"""
# Create a feature array for prediction
features = np.array([[crop_mapping[crop], year, rainfall, temperature, fertilizer]])
prediction = model.predict(features)[0]
return f"{prediction:.2f} tons/ha"
# Crop mapping (example mapping; adjust as per your dataset)
crop_mapping = {
"Wheat": 1,
"Rice": 2,
"Maize": 3,
"Sugarcane": 4
}
# Define Gradio interface
with gr.Blocks() as yield_app:
gr.Markdown("## Yield Prediction")
gr.Markdown("Predict crop yield based on environmental and agricultural inputs.")
with gr.Row():
crop = gr.Dropdown(label="Select Crop", choices=list(crop_mapping.keys()), value="Wheat")
year = gr.Number(label="Year", value=2025)
with gr.Row():
rainfall = gr.Number(label="Rainfall (in mm)", value=700.0)
temperature = gr.Number(label="Temperature (in °C)", value=25.0)
fertilizer = gr.Number(label="Fertilizer (in kg/ha)", value=120.0)
output = gr.Textbox(label="Predicted Yield", interactive=False)
predict_button = gr.Button("Predict Yield")
predict_button.click(
predict_yield,
inputs=[crop, year, rainfall, temperature, fertilizer],
outputs=output
)
# Launch the app
yield_app.launch()