|
|
import gradio as gr |
|
|
import pandas as pd |
|
|
import joblib |
|
|
import numpy as np |
|
|
import os |
|
|
|
|
|
|
|
|
script_dir = os.path.dirname(os.path.abspath(__file__)) |
|
|
model_path = os.path.join(script_dir, "district_yield_pipeline.pkl") |
|
|
|
|
|
|
|
|
if os.path.exists(model_path): |
|
|
try: |
|
|
model = joblib.load(model_path) |
|
|
model_loaded = True |
|
|
print("Model loaded successfully!") |
|
|
except Exception as e: |
|
|
model_loaded = False |
|
|
print(f"Error loading model file: {e}") |
|
|
else: |
|
|
model_loaded = False |
|
|
print(f"Model file not found at: {model_path}") |
|
|
print(f"Available files: {os.listdir(script_dir)}") |
|
|
|
|
|
|
|
|
CROPS = [ |
|
|
'Arhar/Tur', 'Bajra', 'Banana', 'Barley', 'Black Pepper', 'Cardamom', |
|
|
'Cashewnut', 'Castor Seed', 'Coconut', 'Coriander', 'Cotton(Lint)', |
|
|
'Cowpea(Lobia)', 'Dry Chillies', 'Garlic', 'Ginger', 'Gram', 'Groundnut', |
|
|
'Guar Seed', 'Horse-Gram', 'Jowar', 'Jute', 'Khesari', 'Linseed', 'Maize', |
|
|
'Masoor', 'Mesta', 'Moong(Green Gram)', 'Moth', 'Niger Seed', |
|
|
'Oilseeds Total', 'Onion', 'Other Rabi Pulses', 'Other Cereals', |
|
|
'Other Kharif Pulses', 'Other Oilseeds', 'Other Summer Pulses', |
|
|
'Peas & Beans (Pulses)', 'Potato', 'Ragi', 'Rapeseed &Mustard', 'Rice', |
|
|
'Safflower', 'Sannhamp', 'Sesamum', 'Small Millets', 'Soyabean', |
|
|
'Sugarcane', 'Sunflower', 'Sweet Potato', 'Tapioca', 'Tobacco', |
|
|
'Turmeric', 'Urad', 'Wheat' |
|
|
] |
|
|
|
|
|
SEASONS = ['Autumn', 'Kharif', 'Rabi', 'Summer', 'Whole Year', 'Winter'] |
|
|
|
|
|
STATES = [ |
|
|
'Andhra Pradesh', 'Arunachal Pradesh', 'Assam', 'Bihar', 'Chhattisgarh', |
|
|
'Delhi', 'Goa', 'Gujarat', 'Haryana', 'Himachal Pradesh', |
|
|
'Jammu And Kashmir', 'Jharkhand', 'Karnataka', 'Kerala', 'Madhya Pradesh', |
|
|
'Maharashtra', 'Manipur', 'Meghalaya', 'Mizoram', 'Nagaland', 'Odisha', |
|
|
'Puducherry', 'Punjab', 'Sikkim', 'Tamil Nadu', 'Telangana', 'Tripura', |
|
|
'Uttar Pradesh', 'Uttarakhand', 'West Bengal' |
|
|
] |
|
|
|
|
|
YEARS = list(range(1997, 2020)) |
|
|
|
|
|
def predict_yield(crop, season, state, area, annual_rainfall, fertilizer, pesticide, year): |
|
|
""" |
|
|
Predict crop yield based on input features |
|
|
""" |
|
|
if not model_loaded: |
|
|
return "โ Error: Model not loaded. Please check if the model file exists.", "" |
|
|
|
|
|
try: |
|
|
|
|
|
input_data = pd.DataFrame({ |
|
|
'Crop': [crop], |
|
|
'Season': [season], |
|
|
'State': [state], |
|
|
'Area': [float(area)], |
|
|
'Annual_Rainfall': [float(annual_rainfall)], |
|
|
'Fertilizer': [float(fertilizer)], |
|
|
'Pesticide': [float(pesticide)], |
|
|
'Year': [int(year)] |
|
|
}) |
|
|
|
|
|
|
|
|
prediction = model.predict(input_data)[0] |
|
|
|
|
|
|
|
|
result_text = f""" |
|
|
### ๐พ Prediction Results |
|
|
|
|
|
**Predicted Crop Yield:** `{prediction:.2f}` tonnes/hectare |
|
|
|
|
|
--- |
|
|
|
|
|
**Input Summary:** |
|
|
- ๐ฑ **Crop:** {crop} |
|
|
- ๐
**Season:** {season} |
|
|
- ๐ **State:** {state} |
|
|
- ๐ **Area:** {area} hectares |
|
|
- ๐ง๏ธ **Annual Rainfall:** {annual_rainfall} mm |
|
|
- ๐ **Fertilizer:** {fertilizer} kg |
|
|
- ๐งช **Pesticide:** {pesticide} kg |
|
|
- ๐
**Year:** {year} |
|
|
|
|
|
--- |
|
|
|
|
|
**Yield Category:** |
|
|
""" |
|
|
|
|
|
|
|
|
if prediction < 1: |
|
|
result_text += "โ ๏ธ **Low Yield** - Consider improving farming practices" |
|
|
elif prediction < 5: |
|
|
result_text += "โ
**Moderate Yield** - Good performance" |
|
|
elif prediction < 50: |
|
|
result_text += "๐ **High Yield** - Excellent performance" |
|
|
else: |
|
|
result_text += "๐ **Exceptional Yield** - Outstanding performance" |
|
|
|
|
|
|
|
|
insights = f""" |
|
|
### ๐ก Insights & Recommendations |
|
|
|
|
|
Based on the prediction of **{prediction:.2f} tonnes/hectare**: |
|
|
|
|
|
1. **Water Management:** With {annual_rainfall} mm of rainfall, ensure proper irrigation during dry spells. |
|
|
2. **Nutrient Balance:** Current fertilizer usage is {fertilizer} kg. Monitor soil health regularly. |
|
|
3. **Pest Control:** Pesticide usage at {pesticide} kg. Follow integrated pest management practices. |
|
|
4. **Area Optimization:** Managing {area} hectares requires strategic planning for maximum efficiency. |
|
|
|
|
|
**Note:** This prediction is based on historical data and machine learning models. |
|
|
Actual yields may vary based on weather conditions, soil quality, and farming practices. |
|
|
""" |
|
|
|
|
|
return result_text, insights |
|
|
|
|
|
except Exception as e: |
|
|
return f"โ Error making prediction: {str(e)}", "" |
|
|
|
|
|
def load_example(example_name): |
|
|
"""Load predefined examples""" |
|
|
examples = { |
|
|
"Rice - Kharif Season": ("Rice", "Kharif", "West Bengal", 5000, 2000, 500000, 1000, 2015), |
|
|
"Wheat - Rabi Season": ("Wheat", "Rabi", "Punjab", 3000, 1200, 400000, 800, 2015), |
|
|
"Cotton - Kharif Season": ("Cotton(Lint)", "Kharif", "Gujarat", 4000, 800, 350000, 900, 2015), |
|
|
"Sugarcane - Whole Year": ("Sugarcane", "Whole Year", "Maharashtra", 2500, 1500, 600000, 1200, 2015), |
|
|
"Potato - Rabi Season": ("Potato", "Rabi", "Uttar Pradesh", 1500, 900, 250000, 600, 2015) |
|
|
} |
|
|
|
|
|
return examples.get(example_name, ("Rice", "Kharif", "Karnataka", 1000, 1500, 100000, 500, 2015)) |
|
|
|
|
|
|
|
|
custom_css = """ |
|
|
#main-container { |
|
|
max-width: 1200px; |
|
|
margin: auto; |
|
|
} |
|
|
.gradio-container { |
|
|
font-family: 'Arial', sans-serif; |
|
|
} |
|
|
#prediction-output { |
|
|
border: 2px solid #4CAF50; |
|
|
border-radius: 10px; |
|
|
padding: 20px; |
|
|
background-color: #f9f9f9; |
|
|
} |
|
|
#insights-output { |
|
|
border: 2px solid #2196F3; |
|
|
border-radius: 10px; |
|
|
padding: 20px; |
|
|
background-color: #f0f8ff; |
|
|
} |
|
|
""" |
|
|
|
|
|
|
|
|
with gr.Blocks(css=custom_css, title="Crop Yield Prediction System") as demo: |
|
|
|
|
|
gr.Markdown(""" |
|
|
# ๐พ Crop Yield Prediction System |
|
|
|
|
|
### Predict agricultural crop yields using Machine Learning |
|
|
|
|
|
This AI-powered system predicts crop yield based on various agricultural parameters including crop type, |
|
|
season, location, and farming inputs. The model achieves **97.82% accuracy** using Gradient Boosting. |
|
|
|
|
|
--- |
|
|
""") |
|
|
|
|
|
with gr.Row(): |
|
|
with gr.Column(scale=1): |
|
|
gr.Markdown("## ๐ Input Parameters") |
|
|
|
|
|
|
|
|
crop_input = gr.Dropdown( |
|
|
choices=CROPS, |
|
|
label="๐ฑ Select Crop Type", |
|
|
value="Rice", |
|
|
info="Choose the crop you want to predict yield for" |
|
|
) |
|
|
|
|
|
season_input = gr.Dropdown( |
|
|
choices=SEASONS, |
|
|
label="๐
Select Season", |
|
|
value="Kharif", |
|
|
info="Select the growing season" |
|
|
) |
|
|
|
|
|
state_input = gr.Dropdown( |
|
|
choices=STATES, |
|
|
label="๐ Select State", |
|
|
value="Karnataka", |
|
|
info="Choose the state where the crop is grown" |
|
|
) |
|
|
|
|
|
year_input = gr.Dropdown( |
|
|
choices=YEARS, |
|
|
label="๐
Select Year", |
|
|
value=2015, |
|
|
info="Select the year for prediction (1997-2019)" |
|
|
) |
|
|
|
|
|
|
|
|
area_input = gr.Number( |
|
|
label="๐ Area (in hectares)", |
|
|
value=1000, |
|
|
info="Total cultivation area" |
|
|
) |
|
|
|
|
|
rainfall_input = gr.Number( |
|
|
label="๐ง๏ธ Annual Rainfall (in mm)", |
|
|
value=1500, |
|
|
info="Average annual rainfall" |
|
|
) |
|
|
|
|
|
fertilizer_input = gr.Number( |
|
|
label="๐ Fertilizer (in kg)", |
|
|
value=100000, |
|
|
info="Total fertilizer used" |
|
|
) |
|
|
|
|
|
pesticide_input = gr.Number( |
|
|
label="๐งช Pesticide (in kg)", |
|
|
value=500, |
|
|
info="Total pesticide used" |
|
|
) |
|
|
|
|
|
|
|
|
with gr.Row(): |
|
|
predict_btn = gr.Button("๐ฎ Predict Yield", variant="primary", size="lg") |
|
|
clear_btn = gr.ClearButton( |
|
|
components=[crop_input, season_input, state_input, year_input, |
|
|
area_input, rainfall_input, fertilizer_input, pesticide_input], |
|
|
value="๐ Clear" |
|
|
) |
|
|
|
|
|
|
|
|
gr.Markdown("### ๐ Quick Examples") |
|
|
example_dropdown = gr.Dropdown( |
|
|
choices=[ |
|
|
"Rice - Kharif Season", |
|
|
"Wheat - Rabi Season", |
|
|
"Cotton - Kharif Season", |
|
|
"Sugarcane - Whole Year", |
|
|
"Potato - Rabi Season" |
|
|
], |
|
|
label="Load Example", |
|
|
value=None |
|
|
) |
|
|
|
|
|
with gr.Column(scale=1): |
|
|
gr.Markdown("## ๐ Prediction Results") |
|
|
|
|
|
prediction_output = gr.Markdown( |
|
|
label="Prediction", |
|
|
elem_id="prediction-output" |
|
|
) |
|
|
|
|
|
insights_output = gr.Markdown( |
|
|
label="Insights", |
|
|
elem_id="insights-output" |
|
|
) |
|
|
|
|
|
|
|
|
with gr.Accordion("โน๏ธ About This Model", open=False): |
|
|
gr.Markdown(""" |
|
|
### Model Information |
|
|
|
|
|
- **Algorithm:** Gradient Boosting Regressor |
|
|
- **Training Accuracy:** 98.91% Rยฒ Score |
|
|
- **Testing Accuracy:** 97.82% Rยฒ Score |
|
|
- **RMSE:** 122.72 |
|
|
- **Dataset:** Indian Agricultural Crop Yield Data (1997-2019) |
|
|
- **Features:** 8 input features including crop type, season, location, year, and farming inputs |
|
|
|
|
|
### How to Use |
|
|
|
|
|
1. Select the crop type from the dropdown |
|
|
2. Choose the appropriate growing season |
|
|
3. Select the state where cultivation occurs |
|
|
4. Select the year for prediction |
|
|
5. Enter numerical values for area, rainfall, fertilizer, and pesticide |
|
|
6. Click "Predict Yield" to get results |
|
|
7. Review the prediction and insights provided |
|
|
|
|
|
### Data Ranges (for reference) |
|
|
|
|
|
- **Area:** 0.5 - 50,000,000 hectares |
|
|
- **Rainfall:** 300 - 6,500 mm/year |
|
|
- **Fertilizer:** 100 - 100,000,000 kg |
|
|
- **Pesticide:** 1 - 300,000 kg |
|
|
- **Year:** 1997 - 2019 |
|
|
|
|
|
### Disclaimer |
|
|
|
|
|
Predictions are based on historical data and statistical patterns. Actual yields may vary |
|
|
due to unforeseen factors such as extreme weather events, pest outbreaks, or changes in |
|
|
farming practices. Always consult with agricultural experts for important farming decisions. |
|
|
""") |
|
|
|
|
|
|
|
|
predict_btn.click( |
|
|
fn=predict_yield, |
|
|
inputs=[crop_input, season_input, state_input, area_input, |
|
|
rainfall_input, fertilizer_input, pesticide_input, year_input], |
|
|
outputs=[prediction_output, insights_output] |
|
|
) |
|
|
|
|
|
example_dropdown.change( |
|
|
fn=load_example, |
|
|
inputs=[example_dropdown], |
|
|
outputs=[crop_input, season_input, state_input, area_input, |
|
|
rainfall_input, fertilizer_input, pesticide_input, year_input] |
|
|
) |
|
|
|
|
|
|
|
|
gr.Markdown(""" |
|
|
--- |
|
|
|
|
|
### ๐ Deployment Information |
|
|
|
|
|
**Model Version:** 1.0.0 |
|
|
**Last Updated:** 2025 |
|
|
**Powered by:** Gradio + Scikit-learn + Gradient Boosting |
|
|
|
|
|
For questions or feedback, please contact the development team. |
|
|
""") |
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
demo.launch( |
|
|
share=False, |
|
|
server_name="0.0.0.0", |
|
|
server_port=7860 |
|
|
) |