File size: 12,311 Bytes
605709b 56e5176 5938661 56e5176 605709b 56e5176 605709b 5938661 605709b 5938661 605709b 5938661 605709b 5938661 605709b 5938661 605709b 5938661 605709b 5938661 605709b 5938661 605709b 5938661 605709b 5938661 605709b 5938661 605709b 5938661 605709b |
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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 |
import gradio as gr
import pandas as pd
import joblib
import numpy as np
import os
# Load the trained model
script_dir = os.path.dirname(os.path.abspath(__file__))
model_path = os.path.join(script_dir, "district_yield_pipeline.pkl")
# Check if file exists before trying to load
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)}")
# Define the lists for dropdowns (based on your dataset)
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:
# Create input dataframe
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)]
})
# Make prediction
prediction = model.predict(input_data)[0]
# Format output
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:**
"""
# Add yield interpretation
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"
# Additional insights
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 for better styling
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;
}
"""
# Create the Gradio interface
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")
# Dropdown inputs
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)"
)
# Numeric inputs
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"
)
# Buttons
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"
)
# Example selector
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"
)
# Add information section
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.
""")
# Event handlers
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]
)
# Footer
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.
""")
# Launch the app
if __name__ == "__main__":
demo.launch(
share=False, # Set to True for public sharing
server_name="0.0.0.0", # Important for Hugging Face deployment
server_port=7860 # Default Gradio port
) |