shubham5027 commited on
Commit
959b774
·
verified ·
1 Parent(s): 18d0d66

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -59
app.py CHANGED
@@ -1,62 +1,66 @@
1
  import gradio as gr
2
- import pickle
3
  import numpy as np
 
4
 
5
- # Load the trained model
6
- model_file = 'voting_yield.sav'
7
- with open(model_file, 'rb') as file:
8
- model = pickle.load(file)
9
-
10
- # Define prediction function
11
- def predict_yield(crop: str, year: int, rainfall: float, temperature: float, fertilizer: float):
12
- """
13
- Predicts crop yield based on user inputs.
14
-
15
- Parameters:
16
- crop (str): Name of the crop.
17
- year (int): Year of prediction.
18
- rainfall (float): Average annual rainfall (in mm).
19
- temperature (float): Average annual temperature (in °C).
20
- fertilizer (float): Amount of fertilizer used (in kg/ha).
21
-
22
- Returns:
23
- str: Predicted yield (in tons per hectare).
24
- """
25
- # Create a feature array for prediction
26
- features = np.array([[crop_mapping[crop], year, rainfall, temperature, fertilizer]])
27
- prediction = model.predict(features)[0]
28
- return f"{prediction:.2f} tons/ha"
29
-
30
- # Crop mapping (example mapping; adjust as per your dataset)
31
- crop_mapping = {
32
- "Wheat": 1,
33
- "Rice": 2,
34
- "Maize": 3,
35
- "Sugarcane": 4
36
- }
37
-
38
- # Define Gradio interface
39
- with gr.Blocks() as yield_app:
40
- gr.Markdown("## Yield Prediction")
41
- gr.Markdown("Predict crop yield based on environmental and agricultural inputs.")
42
-
43
- with gr.Row():
44
- crop = gr.Dropdown(label="Select Crop", choices=list(crop_mapping.keys()), value="Wheat")
45
- year = gr.Number(label="Year", value=2025)
46
-
47
- with gr.Row():
48
- rainfall = gr.Number(label="Rainfall (in mm)", value=700.0)
49
- temperature = gr.Number(label="Temperature (in °C)", value=25.0)
50
- fertilizer = gr.Number(label="Fertilizer (in kg/ha)", value=120.0)
51
-
52
- output = gr.Textbox(label="Predicted Yield", interactive=False)
53
-
54
- predict_button = gr.Button("Predict Yield")
55
- predict_button.click(
56
- predict_yield,
57
- inputs=[crop, year, rainfall, temperature, fertilizer],
58
- outputs=output
59
- )
60
-
61
- # Launch the app
62
- yield_app.launch()
 
 
 
 
 
1
  import gradio as gr
 
2
  import numpy as np
3
+ import joblib
4
 
5
+ # Load the pre-trained crop yield prediction model
6
+ crop_yield_model = joblib.load('voting_yield.sav')
7
+
8
+ # Define states, crops, and seasons for dropdown menus
9
+ states = [
10
+ 'Andaman and Nicobar Islands', 'Andhra Pradesh', 'Arunachal Pradesh', 'Assam', 'Bihar', 'Chandigarh',
11
+ 'Chhattisgarh', 'Dadra and Nagar Haveli', 'Goa', 'Gujarat', 'Haryana', 'Himachal Pradesh',
12
+ 'Jammu and Kashmir', 'Jharkhand', 'Karnataka', 'Kerala', 'Madhya Pradesh', 'Maharashtra', 'Manipur',
13
+ 'Meghalaya', 'Mizoram', 'Nagaland', 'Odisha', 'Puducherry', 'Punjab', 'Rajasthan', 'Sikkim', 'Tamil Nadu',
14
+ 'Telangana', 'Tripura', 'Uttar Pradesh', 'Uttarakhand', 'West Bengal'
15
+ ]
16
+
17
+ crops = [
18
+ 'Arecanut', 'Barley', 'Banana', 'Blackpepper', 'Brinjal', 'Cabbage', 'Cardamom', 'Cashewnuts', 'Cauliflower',
19
+ 'Coriander', 'Cotton', 'Garlic', 'Grapes', 'Horsegram', 'Jowar', 'Jute', 'Ladyfinger', 'Maize',
20
+ 'Mango', 'Moong', 'Onion', 'Orange', 'Papaya', 'Pineapple', 'Potato', 'Rapeseed', 'Ragi', 'Rice',
21
+ 'Sesamum', 'Soyabean', 'Sunflower', 'Sweetpotato', 'Tapioca', 'Tomato', 'Turmeric', 'Wheat'
22
+ ]
23
+
24
+ seasons = ['Kharif', 'Rabi', 'Summer', 'Whole Year']
25
+
26
+ def predict_yield(state, crop, season, pH, rainfall, temperature, area, production):
27
+ """Predict crop yield based on user inputs."""
28
+ state_encoded = [1 if s == state else 0 for s in states]
29
+ crop_encoded = [1 if c == crop else 0 for c in crops]
30
+ season_encoded = [1 if s == season else 0 for s in seasons]
31
+
32
+ input_features = np.array(state_encoded + crop_encoded + season_encoded + [pH, rainfall, temperature, area, production])
33
+ input_features = input_features.reshape(1, -1)
34
+
35
+ try:
36
+ predicted_yield = crop_yield_model.predict(input_features)[0]
37
+ return f"The predicted yield is {predicted_yield:.2f} tons per hectare."
38
+ except Exception as e:
39
+ return f"Error: {e}"
40
+
41
+ # Gradio interface
42
+ def interface():
43
+ """Define the Gradio interface."""
44
+ inputs = [
45
+ gr.Dropdown(choices=states, label="Select State"),
46
+ gr.Dropdown(choices=crops, label="Select Crop"),
47
+ gr.Dropdown(choices=seasons, label="Select Season"),
48
+ gr.Number(label="Soil pH Value", value=7.0, precision=2),
49
+ gr.Number(label="Rainfall (mm)", value=100.0, precision=1),
50
+ gr.Number(label="Temperature (°C)", value=25.0, precision=1),
51
+ gr.Number(label="Area (hectares)", value=1.0, precision=2),
52
+ gr.Number(label="Production (tons)", value=2.0, precision=2)
53
+ ]
54
+
55
+ outputs = gr.Textbox(label="Predicted Yield")
56
+
57
+ gr.Interface(
58
+ fn=predict_yield,
59
+ inputs=inputs,
60
+ outputs=outputs,
61
+ title="Crop Yield Prediction",
62
+ description="Enter the details below to predict crop yield using the trained model."
63
+ ).launch()
64
+
65
+ if __name__ == "__main__":
66
+ interface()