Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import pickle | |
| import numpy as np | |
| import pandas as pd | |
| import os | |
| # Load Model | |
| model_path = "crop_yield_model.pkl" | |
| if not os.path.exists(model_path): | |
| raise FileNotFoundError(f"Model file not found at {model_path}") | |
| with open(model_path, "rb") as file: | |
| model = pickle.load(file) | |
| # Example mapping for categorical variables (if encoded during training) | |
| season_mapping = {"Kharif": 0, "Rabi": 1, "Zaid": 2} | |
| district_mapping = {"District A": 0, "District B": 1, "District C": 2} | |
| crop_mapping = {"Wheat": 0, "Rice": 1, "Maize": 2, "Sugarcane": 3} | |
| # Prediction Function | |
| def predict_yield(area, season, district, crop): | |
| try: | |
| # Convert categorical inputs to numerical if necessary | |
| season_encoded = season_mapping.get(season, -1) | |
| district_encoded = district_mapping.get(district, -1) | |
| crop_encoded = crop_mapping.get(crop, -1) | |
| if -1 in [season_encoded, district_encoded, crop_encoded]: | |
| return "Error: Invalid categorical input value." | |
| # Prepare input | |
| features = np.array([[area, season_encoded, district_encoded, crop_encoded]]) | |
| prediction = model.predict(features) | |
| return f"Predicted Crop Yield: {float(prediction[0]):.2f}" | |
| except Exception as e: | |
| return f"Error in prediction: {str(e)}" | |
| # Gradio Interface | |
| demo = gr.Interface( | |
| fn=predict_yield, | |
| inputs=[ | |
| gr.Number(label="Area (in acres)"), | |
| gr.Dropdown(["Kharif", "Rabi", "Zaid"], label="Season"), | |
| gr.Dropdown(["District A", "District B", "District C"], label="District"), | |
| gr.Dropdown(["Wheat", "Rice", "Maize", "Sugarcane"], label="Crop"), | |
| ], | |
| outputs=gr.Textbox(label="Prediction Result"), | |
| title="Crop Yield Prediction", | |
| description="Enter the details to predict crop yield.", | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() | |