File size: 1,981 Bytes
1a94b3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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()