YAMITEK's picture
Update app.py
4b83b02 verified
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 = """
<style>
.stApp {
background-image: url("https://images.pexels.com/photos/265216/pexels-photo-265216.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2");
background-position: center;
background-repeat: no-repeat;
background-attachment: fixed;
margin: 0;
padding: 0;
}
.stForm{
background-color: black;
}
.stButton > button {
background-color: white;
color: black;
}
</style>
"""
# 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("<h1 style='text-align: center; background-color: #f4edcd;color:black'>Crop Yield Prediction</h1>", 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"<span style='color:red;'>{area_error}</span>", 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"<span style='color:red;'>{production_error}</span>", 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"""
<div style="color: black; font-size: 18px; border: 1px solid darkgreen; border-radius: 5px; padding: 10px; background-color: #e6ffe6;">
<strong>Expected Yield is (production per unit area):</strong> {prediction[0]}
</div>
""",
unsafe_allow_html=True
)
except Exception as e:
st.error(f"Error in prediction: {e}")