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 )