CoderHassan's picture
Update app.py
20c7738 verified
raw
history blame
4.28 kB
import os
import streamlit as st
from groq import Gorq
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("EnergyGuru_PowerCalc")
# App Configuration
st.title("EnergyGuru_PowerCalc: AI DRIVEN AL 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:
print(f"Error fetching tariff data: {e}")
return {"rate_per_unit": 25} # Return mock data as fallback
st.write("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_usage_hours = 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.write("No appliances added yet.")
# 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
monthly_energy_kwh = total_energy_kwh * 30
# total monthly energy in kwh = no. of units
monthly_energy_kwh = total_no_of_units
# 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
# Correct Monthly Bill Calculation: Total Monthly Energy in kWh * Rate per kWh (Rate in PKR)
monthly_bill = total_no_of_units * rate_per_unit
# Query AI Model (optional, if needed for insights)
query = f"Calculate the monthly electricity bill for appliances with a total energy consumption of {monthly_energy_kwh:.2f} kWh per month."
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("**AI Model Insight:**")
st.write(response.choices[0].message.content)