CoderHassan's picture
Update app.py
1c2b2ed verified
import os
import streamlit as st
from groq import Groq
import requests
from utils import calculate_bill
# Predefined appliance list with typical loads in watts
APPLIANCE_OPTIONS = {
"Fan": 75,
"Air Conditioner (1 Ton)": 1500,
"Air Conditioner (1.5 Ton)": 2200,
"Refrigerator": 150,
"LED Bulb (20W)": 20,
"Tube Light": 40,
"Iron": 1000,
"Microwave Oven": 1200,
"Washing Machine": 500,
"Electric Heater": 1500,
"Laptop": 50,
"Desktop Computer": 200,
"Television (LCD/LED)": 120,
"Water Pump": 1000,
"Geyser (Electric)": 3000
}
# Initialize session state for appliance data
if "appliance_data" not in st.session_state:
st.session_state.appliance_data = []
# Groq Client Setup
client = Groq(api_key=os.getenv("EnergyGuru_PowerCalc"))
# App Configuration
st.set_page_config(page_title="EnergyGuru_PowerCalc", page_icon="⚑", layout="wide")
st.title("⚑ EnergyGuru_PowerCalc: AI-Driven Bill & Carbon Footprint Tracker")
st.sidebar.header("πŸ”Œ Add Appliances")
st.sidebar.write("Select appliances, quantity, and usage details to calculate electricity consumption.")
# Tariff Data
def fetch_tariff_data():
"""Fetch tariff data from the NEPRA website."""
url = "https://nepra.org.pk/consumer%20affairs/Electricity%20Bill.php" # Replace with actual URL
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
st.error(f"Error fetching tariff data: {e}")
return {"rate_per_unit": 25} # Return mock data as fallback
with st.spinner("Fetching real-time tariff data..."):
tariff_data = fetch_tariff_data()
st.success("Tariff data fetched successfully!")
# Appliance Selection
appliance = st.sidebar.selectbox("Select Appliance", options=list(APPLIANCE_OPTIONS.keys()))
default_load = APPLIANCE_OPTIONS[appliance]
quantity = st.sidebar.number_input("Number of Appliances", min_value=1, value=1)
load = st.sidebar.number_input("Load (Watts per Appliance)", min_value=1, value=default_load)
usage_hours = st.sidebar.number_input("Usage Time (Hours per Day)", min_value=0.0, value=6.0)
# Add Appliance Button
if st.sidebar.button("Add Appliance"):
st.session_state.appliance_data.append({
"appliance": appliance,
"load": load,
"quantity": quantity,
"usage_hours": usage_hours
})
st.sidebar.success(f"Added {quantity} {appliance}(s) to the list!")
# Display Appliance List
st.header("πŸ“‹ Appliance List")
if st.session_state.appliance_data:
total_load = 0
total_energy_wh = 0 # Total energy in watt-hours
for idx, data in enumerate(st.session_state.appliance_data):
st.write(f"{idx+1}. {data['appliance']} - {data['quantity']} units, {data['load']}W each, {data['usage_hours']} hours/day")
total_load += data["quantity"] * data["load"]
total_energy_wh += data["quantity"] * data["load"] * data["usage_hours"]
st.write(f"**Total Load: {total_load} Watts**")
else:
st.info("No appliances added yet.")
# Function to calculate carbon footprint (in kg CO2)
def calculate_carbon_footprint(monthly_energy_kwh):
carbon_emission_factor = 0.75 # kg CO2 per kWh, adjust based on actual data
return monthly_energy_kwh * carbon_emission_factor
# Calculate Monthly Bill Button
if st.button("Calculate Monthly Bill"):
# Convert total energy consumption from watt-hours (Wh) to kilowatt-hours (kWh)
total_energy_kwh = total_energy_wh / 1000 # Convert energy to kWh
# Calculate total monthly energy consumption by multiplying by 30 (days)
monthly_energy_kwh = total_energy_kwh * 30 # Total energy consumption in a month
# Get the rate from tariff data or use a default rate if not found
rate_per_unit = tariff_data.get("rate_per_unit", 25) # Default rate of 25 PKR/kWh
# Calculate Monthly Bill
monthly_bill = monthly_energy_kwh * rate_per_unit
# Calculate the carbon footprint based on monthly energy consumption
carbon_footprint = calculate_carbon_footprint(monthly_energy_kwh)
# Query AI Model for suggestions to reduce carbon footprint
query = f"How can I reduce the carbon footprint of {carbon_footprint:.2f} kg CO2 for a monthly electricity consumption of {monthly_energy_kwh:.2f} kWh?"
response = client.chat.completions.create(
messages=[{"role": "user", "content": query}],
model="llama3-8b-8192",
)
# Display Results
st.write(f"**Total Monthly Electricity Bill: PKR {monthly_bill:.2f}**")
st.write(f"**Total Carbon Footprint: {carbon_footprint:.2f} kg CO2**")
st.header("🌿 Tips to Reduce Carbon Footprint")
st.write(response.choices[0].message.content)
# Footer
st.markdown("---")
st.markdown("### Designed by EnergyGuru ---- Powered by PowerCalc - AI Driven Tracker")