shubham5027's picture
Update app.py
150569d verified
import gradio as gr
import numpy as np
import joblib
# Load the pre-trained crop yield prediction model
crop_yield_model = joblib.load('voting_yield.sav')
# Predefined options
states = ['Andaman and Nicobar Islands', 'Andhra Pradesh', 'Arunachal Pradesh', 'Assam', 'Bihar', 'Chandigarh',
'Chhattisgarh', 'Dadra and Nagar Haveli', 'Goa', 'Gujarat', 'Haryana', 'Himachal Pradesh',
'Jammu and Kashmir', 'Jharkhand', 'Karnataka', 'Kerala', 'Madhya Pradesh', 'Maharashtra',
'Manipur', 'Meghalaya', 'Mizoram', 'Nagaland', 'Odisha', 'Puducherry', 'Punjab',
'Rajasthan', 'Sikkim', 'Tamil Nadu', 'Telangana', 'Tripura', 'Uttar Pradesh',
'Uttarakhand', 'West Bengal']
crops = ['Arecanut', 'Barley', 'Banana', 'Blackpepper', 'Brinjal', 'Cabbage', 'Cardamom', 'Cashewnuts', 'Cauliflower',
'Coriander', 'Cotton', 'Garlic', 'Grapes', 'Horsegram', 'Jowar', 'Jute', 'Ladyfinger', 'Maize',
'Mango', 'Moong', 'Onion', 'Orange', 'Papaya', 'Pineapple', 'Potato', 'Rapeseed', 'Ragi', 'Rice',
'Sesamum', 'Soyabean', 'Sunflower', 'Sweetpotato', 'Tapioca', 'Tomato', 'Turmeric', 'Wheat']
seasons = ['Kharif', 'Rabi', 'Summer', 'Whole Year']
def predict_yield(state, crop, season, pH, rainfall, temperature, area, production):
try:
# Encode categorical inputs
state_encoded = [1 if state == s else 0 for s in states]
crop_encoded = [1 if crop == c else 0 for c in crops]
season_encoded = [1 if season == s else 0 for s in seasons]
# Combine inputs
input_features = np.array(state_encoded + crop_encoded + season_encoded + [pH, rainfall, temperature, area, production]).reshape(1, -1)
# Check feature length
expected_features = len(states) + len(crops) + len(seasons) + 5
if input_features.shape[1] != expected_features:
return "Error: Feature shape mismatch!"
else:
predicted_yield = crop_yield_model.predict(input_features)
return f"The predicted yield is: {predicted_yield[0]:.2f} tons/hectare"
except Exception as e:
return f"Error: {str(e)}"
# Gradio Interface
interface = gr.Interface(
fn=predict_yield,
inputs=[
gr.Dropdown(states, label="Select State"),
gr.Dropdown(crops, label="Select Crop"),
gr.Dropdown(seasons, label="Select Season"),
gr.Number(label="Soil pH Value", value=6.5, precision=2),
gr.Number(label="Rainfall (mm)", value=100.0, precision=2),
gr.Number(label="Temperature (°C)", value=25.0, precision=2),
gr.Number(label="Area (hectares)", value=1.0, precision=2),
gr.Number(label="Production (tons)", value=1.0, precision=2),
],
outputs="text",
title="Crop Yield Prediction",
description="Enter the required parameters to predict the crop yield in tons/hectare.",
)
# Launch the app
interface.launch()