Engineer786 commited on
Commit
958d7d9
·
verified ·
1 Parent(s): 8cc90d8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -96
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 tempfile
 
 
 
 
7
  from groq import Groq
8
 
9
  # Initialize Groq client
10
  client = Groq(api_key=os.environ.get('GroqApi'))
11
 
12
- # Tariff URL for scraping
13
- TARIFF_URL = "https://iesco.com.pk/index.php/customer-services/tariff-guide"
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
- # Initialize session state
35
- if "appliance_data" not in st.session_state:
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('GET', url)
45
  if response.status == 200:
46
- soup = BeautifulSoup(response.data, 'html.parser')
47
- text = soup.get_text()
48
- # Simulating tariff rate extraction (replace with accurate extraction logic)
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 tariff data. Status code: {response.status}")
 
53
  except Exception as e:
54
- st.error(f"Error scraping tariff data: {e}")
55
- return {"rate_per_unit": 25} # Default fallback rate
56
-
57
- # Streamlit App Configuration
58
- st.title("Pakistani Electricity Bill Calculator")
59
 
60
- # Step 1: Fetch Tariff Data
61
- st.header("Step 1: Fetch Tariff Data")
62
- if st.button("Fetch Tariff Data"):
63
- st.session_state.tariff_data = scrape_tariff_data(TARIFF_URL)
64
- st.success("Tariff data updated successfully!")
 
 
 
65
 
66
- # Display current tariff data
67
- st.write(f"**Current Tariff Rate:** PKR {st.session_state.tariff_data['rate_per_unit']} per kWh")
 
68
 
69
- # Step 2: Add Appliances
70
- st.sidebar.header("Add Appliances")
71
- appliance = st.sidebar.selectbox("Select Appliance", options=list(APPLIANCE_OPTIONS.keys()))
72
- default_load = APPLIANCE_OPTIONS[appliance]
73
- quantity = st.sidebar.number_input("Number of Appliances", min_value=1, value=1)
74
- load = st.sidebar.number_input("Load (Watts per Appliance)", min_value=1, value=default_load)
75
- usage_hours = st.sidebar.number_input("Usage Time (Hours per Day)", min_value=0.0, value=6.0)
 
 
76
 
77
- if st.sidebar.button("Add Appliance"):
78
- st.session_state.appliance_data.append({
79
- "appliance": appliance,
80
- "load": load,
81
- "quantity": quantity,
82
- "usage_hours": usage_hours
83
- })
84
- st.sidebar.success(f"Added {quantity} {appliance}(s) to the list!")
 
 
 
85
 
86
- # Display Appliance List
87
- st.header("Step 3: Appliance List")
88
- if st.session_state.appliance_data:
89
- total_load = 0
90
- total_energy_wh = 0
91
- for idx, data in enumerate(st.session_state.appliance_data):
92
- st.write(f"{idx + 1}. {data['appliance']} - {data['quantity']} units, {data['load']}W each, {data['usage_hours']} hours/day")
93
- total_load += data["quantity"] * data["load"]
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
- # Step 4: Calculate Monthly Bill
100
- if st.button("Calculate Monthly Bill"):
101
- if not st.session_state.appliance_data:
102
- st.warning("Please add appliances before calculating the bill.")
 
 
 
 
103
  else:
104
- total_energy_kwh = total_energy_wh / 1000 # Convert energy to kWh
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