Engineer786 commited on
Commit
09ee594
·
verified ·
1 Parent(s): b256c59

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py.txt +209 -0
  2. requirements.txt +4 -0
app.py.txt ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import requests
3
+ from bs4 import BeautifulSoup
4
+ import urllib3
5
+
6
+ # Constants for electricity and carbon footprint calculations
7
+ APPLIANCE_OPTIONS = {
8
+ "Fan": 75, "Air Conditioner (1 Ton)": 1500, "Air Conditioner (1.5 Ton)": 2200, "Refrigerator": 150,
9
+ "LED Bulb (20W)": 20, "Tube Light": 40, "Iron": 1000, "Microwave Oven": 1200, "Washing Machine": 500,
10
+ "Electric Heater": 1500, "Laptop": 50, "Desktop Computer": 200, "Television (LCD/LED)": 120,
11
+ "Water Pump": 1000, "Geyser (Electric)": 3000
12
+ }
13
+ EMISSION_FACTORS = {
14
+ "car": 0.27, "bus": 0.08, "plane": 0.15, "electricity": 0.5, "meat_diet": 2.5, "veg_diet": 1.0,
15
+ "shopping": 1.5, "heating": 0.2,
16
+ }
17
+ CITIES = {
18
+ "Karachi": (24.8607, 67.0011),
19
+ "Lahore": (31.5497, 74.3436),
20
+ "Islamabad": (33.6844, 73.0479),
21
+ "Rawalpindi": (33.6007, 73.0679),
22
+ "Faisalabad": (31.4187, 73.0791),
23
+ "Peshawar": (34.0151, 71.5249),
24
+ "Quetta": (30.1798, 66.9750),
25
+ "Multan": (30.1984, 71.4687),
26
+ "Hyderabad": (25.3960, 68.3773),
27
+ "Sialkot": (32.4945, 74.5229),
28
+ "Gujranwala": (32.1617, 74.1883),
29
+ "Sargodha": (32.0836, 72.6711),
30
+ "Bahawalpur": (29.3956, 71.6832),
31
+ "Sukkur": (27.7032, 68.8580),
32
+ "Larkana": (27.5608, 68.2126),
33
+ "Sheikhupura": (31.7131, 73.9783),
34
+ "Abbottabad": (34.1690, 73.2428),
35
+ "Mardan": (34.1989, 72.0457),
36
+ "Rahim Yar Khan": (28.4199, 70.3008),
37
+ "Dera Ismail Khan": (31.8323, 70.9024),
38
+ "Khuzdar": (27.8111, 66.6101),
39
+ "Chitral": (35.8508, 71.7864),
40
+ "Gilgit": (35.8818, 74.4640),
41
+ "Skardu": (35.3357, 75.5491),
42
+ "Muzaffarabad": (34.3706, 73.4716),
43
+ "Mirpur": (33.1445, 73.7519),
44
+ "Gujrat": (32.5737, 74.0789),
45
+ "Jhelum": (32.9471, 73.7284),
46
+ "Attock": (33.7680, 72.3602),
47
+ "Okara": (30.8138, 73.4458),
48
+ "Kasur": (31.1157, 74.4464),
49
+ "Vehari": (30.0452, 72.3527),
50
+ "Jhang": (31.2698, 72.3169),
51
+ "Tando Allahyar": (25.4627, 68.7171),
52
+ "Dadu": (26.7303, 67.7760),
53
+ "Nawabshah": (26.2483, 68.4096),
54
+ "Mingora": (35.2012, 72.4258),
55
+ "Kohat": (33.5560, 71.4356),
56
+ "Khanpur": (28.6455, 70.6598),
57
+ "Bannu": (32.9857, 70.6047),
58
+ "Turbat": (26.0023, 63.0485),
59
+ "Gwadar": (25.1236, 62.3228),
60
+ "Zhob": (31.3488, 69.4488),
61
+ "Swat": (35.2228, 72.4258),
62
+ "Mandi Bahauddin": (32.5836, 73.4907),
63
+ "Pakpattan": (30.3423, 73.3860),
64
+ "Chiniot": (31.7204, 72.9784),
65
+ "Bhakkar": (31.6336, 71.0657),
66
+ "Hafizabad": (32.0731, 73.6880),
67
+ }
68
+ OPEN_METEO_URL = "https://api.open-meteo.com/v1/forecast"
69
+ EXCHANGE_RATE_API_URL = "https://open.er-api.com/v6/latest/PKR"
70
+
71
+ # Initialize session state for appliance data and tariff
72
+ if "appliance_data" not in st.session_state:
73
+ st.session_state.appliance_data = []
74
+ if "tariff_rate" not in st.session_state:
75
+ st.session_state.tariff_rate = None
76
+
77
+ # Function to calculate total energy consumption
78
+ def calculate_total_units():
79
+ total_energy_wh = 0
80
+ for data in st.session_state.appliance_data:
81
+ total_energy_wh += data["quantity"] * data["load"] * data["usage_hours"]
82
+ return total_energy_wh / 1000 # Convert watt-hours to kilowatt-hours
83
+
84
+ # Fetch tariff rate
85
+ def fetch_tariff_from_url(url, load_type):
86
+ try:
87
+ http = urllib3.PoolManager()
88
+ response = http.request("GET", url)
89
+ if response.status == 200:
90
+ soup = BeautifulSoup(response.data, 'html.parser')
91
+ tariff_text = soup.get_text()
92
+
93
+ load_type_mapping = {
94
+ "Domestic": "A-1 GENERAL SUPPLY TARIFF RESIDENTIAL",
95
+ "Commercial": "A-2 GENERAL SUPPLY TARIFF COMMERCIAL",
96
+ "Industrial": "B - INDUSTRIAL SUPPLY TARIFFS",
97
+ "Agriculture": "D - AGRICULTURE TARIFF"
98
+ }
99
+
100
+ load_type_label = load_type_mapping.get(load_type, None)
101
+ if load_type_label:
102
+ start_idx = tariff_text.find(load_type_label)
103
+ if start_idx != -1:
104
+ tariff_section = tariff_text[start_idx:start_idx + 1000]
105
+ rates = [float(word) for word in tariff_section.split() if word.replace(".", "").isdigit()]
106
+ if rates:
107
+ return rates[0]
108
+ st.warning(f"Failed to fetch tariff data for {load_type}.")
109
+ except Exception as e:
110
+ st.error(f"Error fetching tariff: {e}")
111
+ return None
112
+
113
+ # Get exchange rate
114
+ def get_exchange_rate():
115
+ try:
116
+ response = requests.get(EXCHANGE_RATE_API_URL)
117
+ response.raise_for_status()
118
+ data = response.json()
119
+ return 1 / data["rates"]["USD"]
120
+ except Exception as e:
121
+ st.error(f"Error fetching exchange rate: {e}")
122
+ return 300
123
+
124
+ # Get heating degree days (for carbon footprint)
125
+ def get_heating_degree_days(latitude, longitude):
126
+ try:
127
+ response = requests.get(
128
+ OPEN_METEO_URL,
129
+ params={"latitude": latitude, "longitude": longitude, "current_weather": True, "temperature_unit": "celsius"}
130
+ )
131
+ data = response.json()
132
+ current_temp = data["current_weather"]["temperature"]
133
+ return max(18 - current_temp, 0)
134
+ except Exception as e:
135
+ st.error(f"Error fetching weather data: {e}")
136
+ return 0
137
+
138
+ # Carbon footprint calculation
139
+ def calculate_footprint(distance_car, distance_bus, distance_plane, electricity_usage, diet_type, shopping_spent_pkr, city, house_area, exchange_rate):
140
+ latitude, longitude = CITIES[city]
141
+ heating_degree_days = get_heating_degree_days(latitude, longitude)
142
+ car_emissions = distance_car * EMISSION_FACTORS["car"]
143
+ bus_emissions = distance_bus * EMISSION_FACTORS["bus"]
144
+ plane_emissions = distance_plane * EMISSION_FACTORS["plane"]
145
+ electricity_emissions = electricity_usage * EMISSION_FACTORS["electricity"]
146
+ diet_emissions = EMISSION_FACTORS[diet_type] * 30
147
+ shopping_emissions = (shopping_spent_pkr / exchange_rate) * EMISSION_FACTORS["shopping"]
148
+ total_emissions = car_emissions + bus_emissions + plane_emissions + electricity_emissions + diet_emissions + shopping_emissions
149
+ return total_emissions
150
+
151
+ # Streamlit Interface
152
+ st.title("Electricity Bill and Carbon Footprint Calculator")
153
+
154
+ # Sidebar for electricity bill calculation
155
+ st.sidebar.subheader("Electricity Bill Calculator")
156
+ tariff_url = st.sidebar.text_input("Enter URL for Tariff Data:")
157
+ load_type = st.sidebar.selectbox("Select Load Type", ["Domestic", "Commercial", "Industrial", "Agriculture"])
158
+ if st.sidebar.button("Fetch Tariff Data"):
159
+ tariff_rate = fetch_tariff_from_url(tariff_url, load_type)
160
+ if tariff_rate:
161
+ st.session_state.tariff_rate = tariff_rate
162
+ st.sidebar.success(f"Tariff Rate: {tariff_rate} PKR/unit")
163
+
164
+ appliance = st.sidebar.selectbox("Select Appliance", options=list(APPLIANCE_OPTIONS.keys()))
165
+ quantity = st.sidebar.number_input("Quantity", min_value=1, value=1)
166
+ usage_hours = st.sidebar.number_input("Usage Hours/Day", min_value=1.0, value=6.0)
167
+
168
+ if st.sidebar.button("Add Appliance"):
169
+ st.session_state.appliance_data.append({
170
+ "appliance": appliance,
171
+ "load": APPLIANCE_OPTIONS[appliance],
172
+ "quantity": quantity,
173
+ "usage_hours": usage_hours
174
+ })
175
+ st.sidebar.success(f"Added {quantity} {appliance}(s)")
176
+
177
+ # Show added appliances and calculate bill
178
+ st.subheader("Appliance List")
179
+ if st.session_state.appliance_data:
180
+ for appliance_data in st.session_state.appliance_data:
181
+ st.write(f"{appliance_data['quantity']} x {appliance_data['appliance']} ({appliance_data['usage_hours']} hours/day)")
182
+ else:
183
+ st.write("No appliances added.")
184
+
185
+ if st.button("Calculate Electricity Bill"):
186
+ if not st.session_state.tariff_rate:
187
+ st.warning("Please fetch tariff data.")
188
+ else:
189
+ total_units_kwh = calculate_total_units()
190
+ monthly_bill = total_units_kwh * 30 * st.session_state.tariff_rate
191
+ st.subheader(f"Electricity Bill: PKR {monthly_bill:.2f}")
192
+
193
+ # Sidebar for carbon footprint calculation
194
+ st.sidebar.subheader("Carbon Footprint Calculator")
195
+ distance_car = st.sidebar.number_input("Car Distance (km)", min_value=0, value=0)
196
+ distance_bus = st.sidebar.number_input("Bus Distance (km)", min_value=0, value=0)
197
+ distance_plane = st.sidebar.number_input("Plane Distance (km)", min_value=0, value=0)
198
+ electricity_usage = st.sidebar.number_input("Electricity Usage (kWh)", min_value=0, value=0)
199
+ diet_type = st.sidebar.selectbox("Diet Type", ["meat_diet", "veg_diet"])
200
+ shopping_spent_pkr = st.sidebar.number_input("Shopping Spend (PKR)", min_value=0, value=0)
201
+ city = st.sidebar.selectbox("Select the nearest city", options=list(CITIES.keys()))
202
+ house_area = st.sidebar.number_input("House Area (m²)", min_value=0, value=0)
203
+
204
+ if st.button("Calculate Carbon Footprint"):
205
+ exchange_rate = get_exchange_rate()
206
+ carbon_footprint = calculate_footprint(
207
+ distance_car, distance_bus, distance_plane, electricity_usage, diet_type, shopping_spent_pkr, city, house_area, exchange_rate
208
+ )
209
+ st.subheader(f"Carbon Footprint: {carbon_footprint:.2f} kg CO₂/month")
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ streamlit
2
+ requests
3
+ beautifulsoup4
4
+ urllib3