Energyguru / app.py
akazmi's picture
Create app.py
ff70353 verified
import os
import requests
import streamlit as st
import pandas as pd
from scraper import scrape_tariffs
from groq import Groq
# Initialize Groq client
client = Groq(api_key=os.environ.get('GroqApi'))
# Streamlit App: ⚑ EnergyGuru_PowerCalc: AI-Driven Bill & Carbon Footprint Tracker
st.title("⚑ EnergyGuru_PowerCalc: AI-Driven Bill & Carbon Footprint Tracker")
st.sidebar.header("βš™οΈ User Input")
# Tariff URLs for scraping
tariff_urls = {
"IESCO": "https://iesco.com.pk/index.php/customer-services/tariff-guide",
"FESCO": "https://fesco.com.pk/tariff",
"HESCO": "http://www.hesco.gov.pk/htmls/tariffs.htm",
"KE": "https://www.ke.com.pk/customer-services/tariff-structure/",
"LESCO": "https://www.lesco.gov.pk/ElectricityTariffs",
"PESCO": "https://pesconlinebill.pk/pesco-tariff/",
"QESCO": "http://qesco.com.pk/Tariffs.aspx",
"TESCO": "https://tesco.gov.pk/index.php/electricity-traiff",
}
# Predefined appliances and their power in watts
appliances = {
"LED Bulb (10W)": 10,
"Ceiling Fan (75W)": 75,
"Refrigerator (150W)": 150,
"Air Conditioner (1.5 Ton, 1500W)": 1500,
"Washing Machine (500W)": 500,
"Television (100W)": 100,
"Laptop (65W)": 65,
"Iron (1000W)": 1000,
"Microwave Oven (1200W)": 1200,
"Water Heater (2000W)": 2000,
}
def scrape_data():
"""
Scrapes tariff data from the provided URLs.
"""
st.info("πŸ”„ Scraping tariff data... Please wait.")
scrape_tariffs(list(tariff_urls.values()))
st.success("βœ… Tariff data scraping complete.")
def calculate_carbon_footprint(monthly_energy_kwh):
"""
Calculates the carbon footprint based on energy consumption in kWh.
"""
carbon_emission_factor = 0.75 # kg CO2 per kWh
return monthly_energy_kwh * carbon_emission_factor
# Sidebar: Scrape Tariff Data
if st.sidebar.button("Scrape Tariff Data"):
scrape_data()
# Sidebar: Tariff Selection
st.sidebar.subheader("πŸ’‘ Select Tariff")
try:
tariff_data = pd.read_csv("data/tariffs.csv")
tariff_types = tariff_data["category"].unique()
selected_tariff = st.sidebar.selectbox("Select your tariff category:", tariff_types)
rate_per_kwh = tariff_data[tariff_data["category"] == selected_tariff]["rate"].iloc[0]
st.sidebar.write(f"Rate per kWh: **{rate_per_kwh} PKR**")
except FileNotFoundError:
st.sidebar.error("⚠️ Tariff data not found. Please scrape the data first.")
rate_per_kwh = 0
# Sidebar: User Inputs for Appliances
st.sidebar.subheader("🏠 Add Appliances")
selected_appliance = st.sidebar.selectbox("Select an appliance:", list(appliances.keys()))
appliance_power = appliances[selected_appliance]
appliance_quantity = st.sidebar.number_input(
"Enter quantity:", min_value=1, max_value=10, value=1
)
usage_hours = st.sidebar.number_input(
"Enter usage hours per day:", min_value=1, max_value=24, value=5
)
# Add appliance details to the main list
if "appliance_list" not in st.session_state:
st.session_state["appliance_list"] = []
if st.sidebar.button("Add Appliance"):
st.session_state["appliance_list"].append(
{
"appliance": selected_appliance,
"power": appliance_power,
"quantity": appliance_quantity,
"hours": usage_hours,
}
)
# Display the list of added appliances
st.subheader("πŸ“‹ Added Appliances")
if st.session_state["appliance_list"]:
for idx, appliance in enumerate(st.session_state["appliance_list"], start=1):
st.write(
f"{idx}. **{appliance['appliance']}** - "
f"{appliance['power']}W, {appliance['quantity']} unit(s), "
f"{appliance['hours']} hours/day"
)
# Electricity Bill and Carbon Footprint Calculation
if st.session_state["appliance_list"] and rate_per_kwh > 0:
total_daily_energy_kwh = sum(
(appliance["power"] * appliance["quantity"] * appliance["hours"]) / 1000
for appliance in st.session_state["appliance_list"]
)
monthly_energy_kwh = total_daily_energy_kwh * 30 # Assume 30 days in a month
bill_amount = monthly_energy_kwh * rate_per_kwh # Dynamic tariff rate
carbon_footprint = calculate_carbon_footprint(monthly_energy_kwh)
st.subheader("πŸ’΅ Electricity Bill & 🌍 Carbon Footprint")
st.write(f"πŸ’΅ **Estimated Electricity Bill**: **{bill_amount:.2f} PKR**")
st.write(f"🌍 **Estimated Carbon Footprint**: **{carbon_footprint:.2f} kg CO2 per month**")
# Generate Groq-based advice to reduce carbon footprint
appliance_names = [appliance["appliance"] for appliance in st.session_state["appliance_list"]]
appliance_list_str = ", ".join(appliance_names)
chat_completion = client.chat.completions.create(
messages=[{
"role": "user",
"content": (
f"Provide exactly 3 to 4 short, one-line tips to reduce the carbon footprint caused "
f"by the usage of the following appliances: {appliance_list_str}. The tips should be "
f"practical and relevant to these appliances only."
)
}],
model="llama3-8b-8192",
)
advice = chat_completion.choices[0].message.content
st.subheader("πŸ’‘ Tips to Reduce Carbon Footprint")
st.write(advice)
else:
st.info("ℹ️ Add appliances to calculate the electricity bill and carbon footprint.")
# Footer
st.markdown("---")
st.markdown(
"<div style='text-align: center; padding: 10px;'>"
"Designed by EnergyGuru - Powered by AI Driven Tracker<br>"
"</div>",
unsafe_allow_html=True
)