ML_Regression / app.py
satya11's picture
Create app.py
8277016 verified
import pandas as pd
import streamlit as st
import pickle
from PIL import Image
# Set page configuration
st.set_page_config(
page_title="Electric Bill Predictor",
page_icon="⚡",
layout="centered",
initial_sidebar_state="expanded"
)
# Custom CSS
st.markdown("""
<style>
.title {
color: #2c3e50;
text-align: center;
margin-bottom: 30px;
}
.input-section {
background-color: #f8f9fa;
padding: 20px;
border-radius: 10px;
margin-bottom: 20px;
border-left: 5px solid #27ae60;
}
.result-box {
background-color: #e8f5e9;
padding: 25px;
border-radius: 10px;
margin-top: 20px;
text-align: center;
font-size: 1.5em;
font-weight: bold;
border: 2px solid #27ae60;
}
.stButton>button {
background-color: #27ae60;
color: white;
border-radius: 8px;
padding: 12px 24px;
width: 100%;
transition: all 0.3s;
font-size: 1.1em;
}
.stButton>button:hover {
background-color: #2ecc71;
transform: scale(1.02);
}
.stSelectbox, .stNumberInput {
margin-bottom: 15px;
}
.footer {
text-align: center;
margin-top: 30px;
color: #777;
font-size: 0.9em;
}
</style>
""", unsafe_allow_html=True)
# Load model with caching and error handling
@st.cache_resource
def load_model():
try:
with open("final_model_.pkl", "rb") as f:
model = pickle.load(f)
st.success("✅ Model loaded successfully!")
return model
except FileNotFoundError:
st.error("❌ Model file not found! Please ensure 'final_model_.pkl' is in the correct directory.")
return None
except Exception as e:
st.error(f"❌ Error loading model: {str(e)}")
return None
model = load_model()
# App title and header
st.markdown("<h1 class='title'>⚡ Smart Electric Bill Predictor</h1>", unsafe_allow_html=True)
st.markdown("Predict your monthly electricity bill based on appliance usage patterns and location.")
# Main input section
with st.expander("🏠 **Property & Usage Details**", expanded=True):
st.markdown("<div class='input-section'>", unsafe_allow_html=True)
col1, col2 = st.columns(2)
with col1:
st.subheader("Appliance Usage (Hours)")
fan = st.slider("Fan Hours per Day", 5.0, 23.0, 13.0, 0.5,
help="Daily usage hours of ceiling/table fans")
fridge = st.slider("Refrigerator Hours", 17.0, 23.0, 18.0, 0.5,
help="Refrigerator running hours (typically 18-24 hours)")
ac = st.slider("Air Conditioner Hours", 0.0, 3.0, 1.0, 0.5,
help="Daily AC usage hours (0 if not used)")
tv = st.slider("Television Hours", 3.0, 22.0, 12.0, 0.5,
help="Daily TV viewing hours")
monitor = st.slider("Computer Monitor Hours", 1.0, 12.0, 8.0, 0.5,
help="Daily computer usage hours")
with col2:
st.subheader("Location & Billing")
city = st.selectbox("City",
['Hyderabad', 'Vadodara', 'Shimla', 'Mumbai', 'Ratnagiri',
'New Delhi', 'Dahej', 'Ahmedabad', 'Noida', 'Nagpur', 'Chennai',
'Faridabad', 'Kolkata', 'Pune', 'Gurgaon', 'Navi Mumbai'],
help="Select your city for regional tariff rates")
company = st.selectbox("Electricity Provider",
['Tata Power Company Ltd.', 'NHPC', 'Jyoti Structure',
'Power Grid Corp', 'Ratnagiri Gas and Power Pvt. Ltd. (RGPPL)',
'Adani Power Ltd.', 'Kalpataru Power', 'Orient Green',
'Sterlite Power Transmission Ltd',
'Neueon Towers / Sujana Towers Ltd.', 'KEC International',
'Indowind Energy', 'Unitech Power Transmission Ltd.',
'Bonfiglioli Transmission Pvt. Ltd.', 'SJVN Ltd.',
'Maha Transco – Maharashtra State Electricity Transmission Co, Ltd.',
'L&T Transmission & Distribution', 'Guj Ind Power',
'Torrent Power Ltd.', 'Reliance Energy', 'GE T&D India Limited',
'NTPC Pvt. Ltd.',
'Optibelt Power Transmission India Private Limited', 'CESC',
'Ringfeder Power Transmission India Pvt. Ltd.', 'Reliance Power',
'JSW Energy Ltd.', 'Sunil Hitech Eng',
'Toshiba Transmission & Distribution Systems (India) Pvt. Ltd.',
'Jaiprakash Power', 'TransRail Lighting', 'NLC India'],
help="Select your electricity provider company")
month = st.selectbox("Month",
["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"],
index=7, # Default to August
help="Select month for seasonal variation")
monthly_hours = st.slider("Total Monthly Usage Hours", 95.0, 926.0, 826.0, 10.0,
help="Sum of all appliance usage hours for the month")
tariff_rate = st.slider("Electricity Tariff Rate (₹/kWh)", 7.4, 9.3, 8.2, 0.1,
help="Current electricity rate per unit")
st.markdown("</div>", unsafe_allow_html=True)
# Prediction button and results
if st.button("🔍 Predict Monthly Bill", use_container_width=True):
if model is None:
st.error("Cannot make prediction - model not loaded.")
else:
try:
# Convert month name to number
month_num = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"].index(month) + 1
input_data = pd.DataFrame([[fan, fridge, ac, tv, monitor, month_num,
city, company, monthly_hours, tariff_rate]],
columns=['Fan', 'Refrigerator', 'AirConditioner',
'Television', 'Monitor', 'Month',
'City', 'Company', 'MonthlyHours',
'TariffRate'])
predicted_price = model.predict(input_data)[0]
# Display result with visual impact
st.markdown(f"""
<div class='result-box'>
<div style='font-size: 1.2em; margin-bottom: 10px;'>Estimated Monthly Bill</div>
<div style='font-size: 2em; color: #27ae60;'>₹ {predicted_price:,.2f} INR</div>
<div style='margin-top: 15px; font-size: 0.8em; color: #555;'>
Based on your usage patterns in {city} ({month})
</div>
</div>
""", unsafe_allow_html=True)
# Add energy saving tips based on prediction
if predicted_price > 5000:
st.warning("💡 High Bill Alert: Consider reducing AC usage and switching to energy-efficient appliances.")
elif predicted_price > 3000:
st.info("💡 Moderate Bill: You might save by using fans instead of AC when possible.")
else:
st.success("💡 Efficient Usage: Your electricity consumption is well managed!")
except Exception as e:
st.error(f"❌ Prediction error: {str(e)}")
# Additional information section
with st.expander("ℹ️ About This Prediction"):
st.markdown("""
**How this prediction works:**
- The model analyzes your appliance usage patterns, location, and local electricity rates
- Calculations consider seasonal variations in energy consumption
- Predictions are based on machine learning models trained on historical billing data
**For more accurate results:**
- Provide exact usage hours from your electricity meter if available
- Update tariff rates according to your latest electricity bill
- Consider seasonal adjustments for AC/heating usage
""")
# Footer
st.markdown("""
<div class='footer'>
Energy Conservation Starts With Awareness • Powered by Machine Learning
</div>
""", unsafe_allow_html=True)