import streamlit as st import pickle import numpy as np import pandas as pd from sklearn.preprocessing import LabelEncoder import re # Load Data df = pd.read_csv('Crop_Yield.csv') cropOptions = list(df['Crop'].unique()) model_path = 'model.pkl' css = """ """ # Inject custom CSS st.markdown(css, unsafe_allow_html=True) # Load Model with open(model_path, 'rb') as file: model = pickle.load(file) # Initialize Label Encoder and encode columns label_encoder_crop = LabelEncoder() df['Crop_encoded'] = label_encoder_crop.fit_transform(df['Crop']) # Create mappings for Area and Item crop_mapping = dict(zip(label_encoder_crop.classes_, range(len(label_encoder_crop.classes_)))) # Create Form with st.form(key="my_form"): st.markdown("

Crop Yield Prediction

", unsafe_allow_html=True) crop = st.selectbox("Choose a Crop:", options=cropOptions) area = st.text_input("Enter the Area in numbers (in hectares):") area_error = "" if re.match(r"^\d+(\.\d+)?$", area) or not area else "Invalid input for area. Enter a numeric value without commas or special characters." if area_error: st.markdown(f"{area_error}", unsafe_allow_html=True) production = st.text_input(" Enter the Production in numbers (in metric tons):") production_error = "" if re.match(r"^\d+(\.\d+)?$", production) or not production else "Invalid input for production. Enter a numeric value without commas or special characters." if production_error: st.markdown(f"{production_error}", unsafe_allow_html=True) rainfall = st.slider("Annual Rainfall (in mm)", min(df['Annual_Rainfall']), max(df['Annual_Rainfall']), value=min(df['Annual_Rainfall'])) fertilizer = st.slider("Fertilizer (in kilograms).", min(df['Fertilizer']), max(df['Fertilizer']), value=min(df['Fertilizer'])) pesticide = st.slider("Pesticide (in kilograms).", min(df['Pesticide']), max(df['Pesticide']), value=min(df['Pesticide'])) submit_button = st.form_submit_button(label="Predict") # Handle Form Submission if submit_button: # Validate Inputs if area_error or production_error: st.error("Please fix the errors above before proceeding.") else: # Prepare Input Data encoded_crop = crop_mapping[crop] input_data = np.array([[pesticide, fertilizer, rainfall,float(production), float(area), encoded_crop]]) # Predict try: prediction = model.predict(input_data) st.markdown( f"""
Expected Yield is (production per unit area): {prediction[0]}
""", unsafe_allow_html=True ) except Exception as e: st.error(f"Error in prediction: {e}")