|
import gradio as gr |
|
import pickle |
|
import numpy as np |
|
|
|
|
|
model_file = 'Yield_Ridge.sav' |
|
with open(model_file, 'rb') as file: |
|
model = pickle.load(file) |
|
|
|
|
|
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). |
|
""" |
|
|
|
features = np.array([[crop_mapping[crop], year, rainfall, temperature, fertilizer]]) |
|
prediction = model.predict(features)[0] |
|
return f"{prediction:.2f} tons/ha" |
|
|
|
|
|
crop_mapping = { |
|
"Wheat": 1, |
|
"Rice": 2, |
|
"Maize": 3, |
|
"Sugarcane": 4 |
|
} |
|
|
|
|
|
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 |
|
) |
|
|
|
|
|
yield_app.launch() |
|
|