Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,90 +2,127 @@ import os
|
|
| 2 |
import streamlit as st
|
| 3 |
from bs4 import BeautifulSoup
|
| 4 |
import urllib3
|
| 5 |
-
import
|
| 6 |
-
|
| 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
|
| 18 |
-
if "
|
| 19 |
-
st.session_state.
|
| 20 |
|
| 21 |
def scrape_web_data(url):
|
| 22 |
-
"""Scrape
|
| 23 |
try:
|
| 24 |
http = urllib3.PoolManager()
|
| 25 |
-
response = http.request(
|
| 26 |
if response.status == 200:
|
| 27 |
-
soup = BeautifulSoup(response.data,
|
| 28 |
all_text = soup.get_text()
|
| 29 |
-
return [{
|
| 30 |
else:
|
| 31 |
-
st.
|
| 32 |
-
return []
|
| 33 |
except Exception as e:
|
| 34 |
-
st.
|
| 35 |
-
|
| 36 |
|
| 37 |
def store_tariff_data(data):
|
| 38 |
-
"""Store
|
| 39 |
-
if data:
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
# Streamlit UI
|
| 47 |
-
st.title("Electricity Bill Calculator
|
| 48 |
-
st.subheader("Real-Time Tariff Data Retrieval")
|
| 49 |
|
| 50 |
-
# Step 1: Scraping
|
| 51 |
-
|
| 52 |
-
|
|
|
|
| 53 |
scraped_data = scrape_web_data(website_url)
|
| 54 |
if scraped_data:
|
|
|
|
|
|
|
| 55 |
store_tariff_data(scraped_data)
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
st.write(item["Data"])
|
| 59 |
|
| 60 |
-
# Step 2: Appliance
|
| 61 |
st.subheader("Step 2: Enter Appliance Details")
|
| 62 |
-
|
| 63 |
-
|
| 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 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 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 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
else:
|
| 90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import streamlit as st
|
| 3 |
from bs4 import BeautifulSoup
|
| 4 |
import urllib3
|
| 5 |
+
from langchain_community.vectorstores import FAISS
|
| 6 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
from groq import Groq
|
| 8 |
|
| 9 |
# Initialize Groq client
|
| 10 |
client = Groq(api_key=os.environ.get('GroqApi'))
|
| 11 |
|
| 12 |
+
# Initialize session state for scraped data
|
| 13 |
+
if "scraped_data" not in st.session_state:
|
| 14 |
+
st.session_state.scraped_data = []
|
| 15 |
|
| 16 |
def scrape_web_data(url):
|
| 17 |
+
"""Scrape text data from the given URL."""
|
| 18 |
try:
|
| 19 |
http = urllib3.PoolManager()
|
| 20 |
+
response = http.request('GET', url)
|
| 21 |
if response.status == 200:
|
| 22 |
+
soup = BeautifulSoup(response.data, 'html.parser')
|
| 23 |
all_text = soup.get_text()
|
| 24 |
+
return [{'Data': line.strip()} for line in all_text.split('\n') if line.strip()]
|
| 25 |
else:
|
| 26 |
+
st.write(f"Error: {response.status}")
|
|
|
|
| 27 |
except Exception as e:
|
| 28 |
+
st.write(f"An error occurred: {e}")
|
| 29 |
+
return []
|
| 30 |
|
| 31 |
def store_tariff_data(data):
|
| 32 |
+
"""Store the scraped data in FAISS vectorstore."""
|
| 33 |
+
if not data:
|
| 34 |
+
return
|
| 35 |
+
combined_text = "\n".join([item["Data"] for item in data])
|
| 36 |
+
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
| 37 |
+
vectorstore = FAISS.from_texts([combined_text], embeddings)
|
| 38 |
+
vectorstore.save_local("vectorstore/")
|
| 39 |
+
|
| 40 |
+
def query_with_groq(prompt):
|
| 41 |
+
"""Query Groq LLM with the provided prompt."""
|
| 42 |
+
try:
|
| 43 |
+
chat_completion = client.chat.completions.create(
|
| 44 |
+
messages=[
|
| 45 |
+
{
|
| 46 |
+
"role": "user",
|
| 47 |
+
"content": prompt,
|
| 48 |
+
}
|
| 49 |
+
],
|
| 50 |
+
model="llama3-8b-8192",
|
| 51 |
+
)
|
| 52 |
+
return chat_completion.choices[0].message.content
|
| 53 |
+
except Exception as e:
|
| 54 |
+
return f"Error querying Groq: {e}"
|
| 55 |
|
| 56 |
# Streamlit UI
|
| 57 |
+
st.title("Pakistani Electricity Bill Calculator with Groq RAG")
|
|
|
|
| 58 |
|
| 59 |
+
# Step 1: Scraping
|
| 60 |
+
st.subheader("Step 1: Scrape Tariff Data")
|
| 61 |
+
website_url = st.text_input("Enter the tariff URL:")
|
| 62 |
+
if st.button("Scrape Data"):
|
| 63 |
scraped_data = scrape_web_data(website_url)
|
| 64 |
if scraped_data:
|
| 65 |
+
st.session_state.scraped_data = scraped_data
|
| 66 |
+
st.success(f"Scraping completed. {len(scraped_data)} items found.")
|
| 67 |
store_tariff_data(scraped_data)
|
| 68 |
+
else:
|
| 69 |
+
st.warning("No data found. Please check the URL.")
|
|
|
|
| 70 |
|
| 71 |
+
# Step 2: Appliance Inputs
|
| 72 |
st.subheader("Step 2: Enter Appliance Details")
|
| 73 |
+
if "appliance_data" not in st.session_state:
|
| 74 |
+
st.session_state.appliance_data = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
+
appliance_name = st.text_input("Appliance Name")
|
| 77 |
+
appliance_load = st.number_input("Load (Watts per Appliance)", min_value=1, value=100)
|
| 78 |
+
appliance_quantity = st.number_input("Quantity", min_value=1, value=1)
|
| 79 |
+
appliance_usage_hours = st.number_input("Usage Hours per Day", min_value=0.0, value=6.0)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
+
if st.button("Add Appliance"):
|
| 82 |
+
st.session_state.appliance_data.append({
|
| 83 |
+
"name": appliance_name,
|
| 84 |
+
"load": appliance_load,
|
| 85 |
+
"quantity": appliance_quantity,
|
| 86 |
+
"usage_hours": appliance_usage_hours
|
| 87 |
+
})
|
| 88 |
+
st.success(f"Added {appliance_quantity} {appliance_name}(s) to the list!")
|
| 89 |
+
|
| 90 |
+
# Display Appliance List
|
| 91 |
+
if st.session_state.appliance_data:
|
| 92 |
+
st.subheader("Appliance List")
|
| 93 |
+
for idx, appliance in enumerate(st.session_state.appliance_data):
|
| 94 |
+
st.write(f"{idx+1}. {appliance['name']} - {appliance['quantity']} units, "
|
| 95 |
+
f"{appliance['load']}W each, {appliance['usage_hours']} hours/day")
|
| 96 |
+
|
| 97 |
+
# Step 3: Query the RAG system
|
| 98 |
+
st.subheader("Step 3: Query Tariff Information")
|
| 99 |
+
user_query = st.text_input("Enter your query about the tariff:")
|
| 100 |
+
if st.button("Ask Query"):
|
| 101 |
+
if not st.session_state.scraped_data:
|
| 102 |
+
st.warning("Please scrape tariff data first.")
|
| 103 |
else:
|
| 104 |
+
# Load vectorstore
|
| 105 |
+
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
| 106 |
+
vectorstore = FAISS.load_local("vectorstore/", embeddings)
|
| 107 |
+
retriever = vectorstore.as_retriever()
|
| 108 |
+
|
| 109 |
+
# Combine scraped data for context
|
| 110 |
+
context = "\n".join([item["Data"] for item in st.session_state.scraped_data])
|
| 111 |
+
prompt = f"Context: {context}\n\nUser Query: {user_query}\nAnswer:"
|
| 112 |
+
response = query_with_groq(prompt)
|
| 113 |
+
st.write("**Answer:**")
|
| 114 |
+
st.write(response)
|
| 115 |
|
| 116 |
+
# Step 4: Calculate Bill
|
| 117 |
+
st.subheader("Step 4: Calculate Bill")
|
| 118 |
+
tariff_rate = st.number_input("Enter Rate per Unit (PKR)", min_value=0.0, value=25.0)
|
| 119 |
+
if st.button("Calculate Bill"):
|
| 120 |
+
if not st.session_state.appliance_data:
|
| 121 |
+
st.warning("Please add at least one appliance.")
|
| 122 |
+
else:
|
| 123 |
+
total_energy_kwh = sum(
|
| 124 |
+
(appliance["load"] * appliance["quantity"] * appliance["usage_hours"] * 30) / 1000
|
| 125 |
+
for appliance in st.session_state.appliance_data
|
| 126 |
+
)
|
| 127 |
+
monthly_bill = total_energy_kwh * tariff_rate
|
| 128 |
+
st.write(f"**Total Monthly Electricity Bill: PKR {monthly_bill:.2f}**")
|