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