Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,119 +1,91 @@
|
|
| 1 |
import os
|
| 2 |
import streamlit as st
|
| 3 |
-
import urllib3
|
| 4 |
from bs4 import BeautifulSoup
|
|
|
|
|
|
|
| 5 |
import pandas as pd
|
| 6 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
from groq import Groq
|
| 8 |
|
| 9 |
# Initialize Groq client
|
| 10 |
client = Groq(api_key=os.environ.get('GroqApi'))
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
# Predefined appliance list with typical loads in watts
|
| 16 |
-
APPLIANCE_OPTIONS = {
|
| 17 |
-
"Fan": 75,
|
| 18 |
-
"Air Conditioner (1 Ton)": 1500,
|
| 19 |
-
"Air Conditioner (1.5 Ton)": 2200,
|
| 20 |
-
"Refrigerator": 150,
|
| 21 |
-
"LED Bulb (20W)": 20,
|
| 22 |
-
"Tube Light": 40,
|
| 23 |
-
"Iron": 1000,
|
| 24 |
-
"Microwave Oven": 1200,
|
| 25 |
-
"Washing Machine": 500,
|
| 26 |
-
"Electric Heater": 1500,
|
| 27 |
-
"Laptop": 50,
|
| 28 |
-
"Desktop Computer": 200,
|
| 29 |
-
"Television (LCD/LED)": 120,
|
| 30 |
-
"Water Pump": 1000,
|
| 31 |
-
"Geyser (Electric)": 3000
|
| 32 |
-
}
|
| 33 |
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
st.session_state.appliance_data = []
|
| 37 |
-
if "tariff_data" not in st.session_state:
|
| 38 |
-
st.session_state.tariff_data = {"rate_per_unit": 25} # Default fallback rate
|
| 39 |
-
|
| 40 |
-
def scrape_tariff_data(url):
|
| 41 |
-
"""Scrape tariff data from the specified URL."""
|
| 42 |
try:
|
| 43 |
http = urllib3.PoolManager()
|
| 44 |
-
response = http.request(
|
| 45 |
if response.status == 200:
|
| 46 |
-
soup = BeautifulSoup(response.data,
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
rate = 25 # Placeholder value, replace with extraction from `text`
|
| 50 |
-
return {"rate_per_unit": rate}
|
| 51 |
else:
|
| 52 |
-
st.warning(f"Failed to fetch
|
|
|
|
| 53 |
except Exception as e:
|
| 54 |
-
st.error(f"
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
# Streamlit App Configuration
|
| 58 |
-
st.title("Pakistani Electricity Bill Calculator")
|
| 59 |
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
if
|
| 63 |
-
|
| 64 |
-
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
-
#
|
| 67 |
-
st.
|
|
|
|
| 68 |
|
| 69 |
-
# Step
|
| 70 |
-
st.
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
|
|
|
|
|
|
| 76 |
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
-
#
|
| 87 |
-
st.
|
| 88 |
-
if st.session_state.
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
total_energy_wh += data["quantity"] * data["load"] * data["usage_hours"]
|
| 95 |
-
st.write(f"**Total Load: {total_load} Watts**")
|
| 96 |
-
else:
|
| 97 |
-
st.write("No appliances added yet.")
|
| 98 |
|
| 99 |
-
#
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
else:
|
| 104 |
-
|
| 105 |
-
monthly_energy_kwh = total_energy_kwh * 30
|
| 106 |
-
rate_per_unit = st.session_state.tariff_data.get("rate_per_unit", 25)
|
| 107 |
-
monthly_bill = monthly_energy_kwh * rate_per_unit
|
| 108 |
-
|
| 109 |
-
# Query AI Model (optional, for additional insights)
|
| 110 |
-
query = f"Calculate the monthly electricity bill for appliances with a total energy consumption of {monthly_energy_kwh:.2f} kWh per month."
|
| 111 |
-
response = client.chat.completions.create(
|
| 112 |
-
messages=[{"role": "user", "content": query}],
|
| 113 |
-
model="llama3-8b-8192",
|
| 114 |
-
)
|
| 115 |
|
| 116 |
-
# Display Results
|
| 117 |
-
st.write(f"**Total Monthly Electricity Bill: PKR {monthly_bill:.2f}**")
|
| 118 |
-
st.write("**AI Model Insight:**")
|
| 119 |
-
st.write(response.choices[0].message.content)
|
|
|
|
| 1 |
import os
|
| 2 |
import streamlit as st
|
|
|
|
| 3 |
from bs4 import BeautifulSoup
|
| 4 |
+
import urllib3
|
| 5 |
+
import faiss
|
| 6 |
import pandas as pd
|
| 7 |
+
from langchain.vectorstores import FAISS
|
| 8 |
+
from langchain.embeddings import HuggingFaceEmbeddings
|
| 9 |
+
from langchain.chains import RetrievalQA
|
| 10 |
+
from langchain.prompts import PromptTemplate
|
| 11 |
+
from langchain.llms import HuggingFaceHub
|
| 12 |
from groq import Groq
|
| 13 |
|
| 14 |
# Initialize Groq client
|
| 15 |
client = Groq(api_key=os.environ.get('GroqApi'))
|
| 16 |
|
| 17 |
+
# Initialize FAISS index
|
| 18 |
+
if "vectorstore" not in st.session_state:
|
| 19 |
+
st.session_state.vectorstore = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
+
def scrape_web_data(url):
|
| 22 |
+
"""Scrape tariff data from the given URL."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
try:
|
| 24 |
http = urllib3.PoolManager()
|
| 25 |
+
response = http.request("GET", url)
|
| 26 |
if response.status == 200:
|
| 27 |
+
soup = BeautifulSoup(response.data, "html.parser")
|
| 28 |
+
all_text = soup.get_text()
|
| 29 |
+
return [{"Data": line.strip()} for line in all_text.split("\n") if line.strip()]
|
|
|
|
|
|
|
| 30 |
else:
|
| 31 |
+
st.warning(f"Failed to fetch data: {response.status}")
|
| 32 |
+
return []
|
| 33 |
except Exception as e:
|
| 34 |
+
st.error(f"An error occurred: {e}")
|
| 35 |
+
return []
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
+
def store_tariff_data(data):
|
| 38 |
+
"""Store tariff data into a FAISS vector database."""
|
| 39 |
+
if data:
|
| 40 |
+
df = pd.DataFrame(data)
|
| 41 |
+
embeddings = HuggingFaceEmbeddings()
|
| 42 |
+
vectorstore = FAISS.from_dataframe(df, embeddings)
|
| 43 |
+
st.session_state.vectorstore = vectorstore
|
| 44 |
+
st.success("Tariff data successfully stored in the vector database!")
|
| 45 |
|
| 46 |
+
# Streamlit UI
|
| 47 |
+
st.title("Electricity Bill Calculator - Pakistan")
|
| 48 |
+
st.subheader("Real-Time Tariff Data Retrieval")
|
| 49 |
|
| 50 |
+
# Step 1: Scraping Tariff Data
|
| 51 |
+
website_url = st.text_input("Enter NEPRA Tariff URL:")
|
| 52 |
+
if st.button("Scrape Tariff Data"):
|
| 53 |
+
scraped_data = scrape_web_data(website_url)
|
| 54 |
+
if scraped_data:
|
| 55 |
+
store_tariff_data(scraped_data)
|
| 56 |
+
st.write("Scraped Data:")
|
| 57 |
+
for item in scraped_data[:5]: # Show first 5 data items for reference
|
| 58 |
+
st.write(item["Data"])
|
| 59 |
|
| 60 |
+
# Step 2: Appliance Data Input
|
| 61 |
+
st.subheader("Step 2: Enter Appliance Details")
|
| 62 |
+
appliances = st.text_area(
|
| 63 |
+
"Enter appliance details in the format: Appliance, Load(Watts), Usage(Hours per Day)",
|
| 64 |
+
"Fan, 75, 6\nRefrigerator, 150, 24\nLED Bulb, 20, 5",
|
| 65 |
+
)
|
| 66 |
+
appliance_list = [line.split(",") for line in appliances.split("\n") if line.strip()]
|
| 67 |
+
appliance_data = [
|
| 68 |
+
{"appliance": item[0].strip(), "load": float(item[1].strip()), "usage": float(item[2].strip())}
|
| 69 |
+
for item in appliance_list
|
| 70 |
+
]
|
| 71 |
|
| 72 |
+
# Step 3: Calculate Bill
|
| 73 |
+
if st.button("Calculate Bill"):
|
| 74 |
+
if st.session_state.vectorstore:
|
| 75 |
+
# Query FAISS for tariff information
|
| 76 |
+
retriever = st.session_state.vectorstore.as_retriever()
|
| 77 |
+
chain = RetrievalQA.from_chain_type(llm=HuggingFaceHub(model="google/flan-t5-base"), retriever=retriever)
|
| 78 |
+
tariff_query = "What is the rate per unit for electricity in PKR?"
|
| 79 |
+
result = chain.run(tariff_query)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
+
# Parse the result and calculate the bill
|
| 82 |
+
try:
|
| 83 |
+
rate_per_unit = float(result.split()[0]) # Extract numerical value from result
|
| 84 |
+
total_units = sum((item["load"] * item["usage"] * 30) / 1000 for item in appliance_data)
|
| 85 |
+
total_bill = total_units * rate_per_unit
|
| 86 |
+
st.success(f"Your estimated monthly electricity bill is: PKR {total_bill:.2f}")
|
| 87 |
+
except Exception as e:
|
| 88 |
+
st.error(f"Error calculating bill: {e}")
|
| 89 |
else:
|
| 90 |
+
st.error("No tariff data available. Please scrape tariff data first.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
|
|
|
|
|
|
|
|
|
|
|
|