Engineer786 commited on
Commit
ce2e1f5
·
verified ·
1 Parent(s): 4cbef0b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -50
app.py CHANGED
@@ -1,8 +1,16 @@
1
  import os
2
  import streamlit as st
 
 
 
 
3
  from groq import Groq
4
- import requests
5
- from utils import calculate_bill
 
 
 
 
6
 
7
  # Predefined appliance list with typical loads in watts
8
  APPLIANCE_OPTIONS = {
@@ -23,42 +31,49 @@ APPLIANCE_OPTIONS = {
23
  "Geyser (Electric)": 3000
24
  }
25
 
26
- # Initialize session state for appliance data
27
  if "appliance_data" not in st.session_state:
28
  st.session_state.appliance_data = []
 
 
29
 
30
- # Groq Client Setup
31
- client = Groq(api_key=os.environ.get('GroqApi'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
- # App Configuration
34
  st.title("Pakistani Electricity Bill Calculator")
35
- st.sidebar.header("Add Appliances")
36
- st.sidebar.write("Select appliances, quantity, and usage details to calculate electricity consumption.")
37
 
38
- # Tariff Data
39
- def fetch_tariff_data():
40
- """Fetch tariff data from the WAPDA website."""
41
- url = "https://nepra.org.pk/consumer%20affairs/Electricity%20Bill.php" # Replace with actual URL
42
- try:
43
- response = requests.get(url, timeout=10)
44
- response.raise_for_status()
45
- return response.json()
46
- except requests.exceptions.RequestException as e:
47
- print(f"Error fetching tariff data: {e}")
48
- return {"rate_per_unit": 25} # Return mock data as fallback
49
 
50
- st.write("Fetching real-time tariff data...")
51
- tariff_data = fetch_tariff_data()
52
- st.success("Tariff data fetched successfully!")
53
 
54
- # Appliance Selection
 
55
  appliance = st.sidebar.selectbox("Select Appliance", options=list(APPLIANCE_OPTIONS.keys()))
56
  default_load = APPLIANCE_OPTIONS[appliance]
57
  quantity = st.sidebar.number_input("Number of Appliances", min_value=1, value=1)
58
  load = st.sidebar.number_input("Load (Watts per Appliance)", min_value=1, value=default_load)
59
  usage_hours = st.sidebar.number_input("Usage Time (Hours per Day)", min_value=0.0, value=6.0)
60
 
61
- # Add Appliance Button
62
  if st.sidebar.button("Add Appliance"):
63
  st.session_state.appliance_data.append({
64
  "appliance": appliance,
@@ -69,41 +84,36 @@ if st.sidebar.button("Add Appliance"):
69
  st.sidebar.success(f"Added {quantity} {appliance}(s) to the list!")
70
 
71
  # Display Appliance List
72
- st.header("Appliance List")
73
  if st.session_state.appliance_data:
74
  total_load = 0
75
- total_usage_hours = 0
76
- total_energy_wh = 0 # Total energy in watt-hours
77
  for idx, data in enumerate(st.session_state.appliance_data):
78
- st.write(f"{idx+1}. {data['appliance']} - {data['quantity']} units, {data['load']}W each, {data['usage_hours']} hours/day")
79
  total_load += data["quantity"] * data["load"]
80
  total_energy_wh += data["quantity"] * data["load"] * data["usage_hours"]
81
  st.write(f"**Total Load: {total_load} Watts**")
82
  else:
83
  st.write("No appliances added yet.")
84
 
85
- # Calculate Monthly Bill Button
86
  if st.button("Calculate Monthly Bill"):
87
- # Convert total energy consumption from watt-hours (Wh) to kilowatt-hours (kWh)
88
- total_energy_kwh = total_energy_wh / 1000 # Convert energy to kWh
89
-
90
- # Calculate total monthly energy consumption by multiplying by 30
91
- monthly_energy_kwh = total_energy_kwh * 30
92
-
93
- # Get the rate from tariff data or use a default rate if not found
94
- rate_per_unit = tariff_data.get("rate_per_unit", 25) # Default rate of 25 PKR/kWh
95
-
96
- # Correct Monthly Bill Calculation: Total Monthly Energy in kWh * Rate per kWh (Rate in PKR)
97
- monthly_bill = monthly_energy_kwh * rate_per_unit
98
 
99
- # Query AI Model (optional, if needed for insights)
100
- query = f"Calculate the monthly electricity bill for appliances with a total energy consumption of {monthly_energy_kwh:.2f} kWh per month."
101
- response = client.chat.completions.create(
102
- messages=[{"role": "user", "content": query}],
103
- model="llama3-8b-8192",
104
- )
105
 
106
- # Display Results
107
- st.write(f"**Total Monthly Electricity Bill: PKR {monthly_bill:.2f}**")
108
- st.write("**AI Model Insight:**")
109
- st.write(response.choices[0].message.content)
 
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 = {
 
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,
 
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)