Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
1942 lines (1382 loc) · 47.2 KB
/
Copy pathapp.py
File metadata and controls
1942 lines (1382 loc) · 47.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import streamlit as st
import pandas as pd
import plotly.express as px
from reportlab.platypus import (
SimpleDocTemplate,
Paragraph,
Table,
TableStyle,
Spacer
)
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib import colors
from reportlab.lib.units import inch
from datetime import datetime
# -----------------------------------------
# PAGE CONFIGURATION
# -----------------------------------------
st.set_page_config(
page_title="WattLens AI",
page_icon="⚡",
layout="wide"
)
# -----------------------------------------
# SESSION STATE
# -----------------------------------------
if "usage_data" not in st.session_state:
st.session_state.usage_data = []
# -----------------------------------------
# SIDEBAR
# -----------------------------------------
page = st.sidebar.radio(
"Navigation",
[
"🏠 Home",
"⚡ Energy Analyzer",
"📊 Dashboard",
"📄 Bill Analyzer",
"🔮 Prediction",
"📑 PDF Report",
"ℹ About"
]
)
# -----------------------------------------
# HOME PAGE
# -----------------------------------------
if page == "🏠 Home":
st.title("⚡ WattLens AI")
st.write("AI-Powered Home Energy Analytics & Bill Prediction")
st.markdown(
"""
### AI Powered Electricity Bill Optimizer
Analyze your electricity usage,
estimate bills,
optimize appliance consumption,
predict future expenses,
and generate professional reports.
"""
)
col1, col2, col3 = st.columns(3)
with col1:
st.metric("AI Features", "8+")
with col2:
st.metric("Supported Appliances", "25+")
with col3:
st.metric("Prediction Accuracy", "95%")
st.divider()
st.subheader("🚀 Features")
st.markdown("""
- ⚡ Appliance Energy Analysis
- 📊 Interactive Dashboard
- 📄 Bill Analyzer
- 🤖 AI Recommendations
- 💰 Savings Simulator
- 🔮 Future Bill Prediction
- 📑 PDF Report
- 📈 Data Visualization
""")
# -----------------------------------------
# ENERGY ANALYZER
# -----------------------------------------
elif page == "⚡ Energy Analyzer":
st.title("⚡ Smart Energy Analyzer")
st.subheader("🏠 Household Information")
col1, col2 = st.columns(2)
with col1:
user_name = st.text_input(
"👤 User Name",
value=st.session_state.get("user_name", "")
)
st.session_state.user_name = user_name
family_members = st.number_input(
"👨👩👧👦 Family Members",
min_value=1,
value=4
)
with col2:
house_type = st.selectbox(
"🏠 House Type",
[
"Apartment",
"Independent House",
"Villa",
"Hostel / PG",
"Commercial"
]
)
rooms = st.number_input(
"🚪 Number of Rooms",
min_value=1,
value=3
)
st.divider()
st.subheader("⚡ Electricity Information")
col1, col2 = st.columns(2)
with col1:
state = st.selectbox(
"📍 Select State",
[
"Andhra Pradesh",
"Telangana",
"Tamil Nadu",
"Karnataka",
"Kerala",
"Maharashtra",
"Delhi",
"Other"
]
)
billing_month = st.selectbox(
"📅 Billing Month",
[
"January","February","March",
"April","May","June",
"July","August","September",
"October","November","December"
]
)
st.divider()
appliances = {
"💡 Lighting": {
"LED Bulb": 9,
"CFL Bulb": 18,
"Tube Light": 20,
"Incandescent Bulb": 60,
"Decorative Light": 15,
"Outdoor Light": 25,
},
"🌬 Fans & Cooling": {
"Ceiling Fan": 75,
"BLDC Ceiling Fan": 35,
"Table Fan": 55,
"Pedestal Fan": 60,
"Exhaust Fan": 40,
"Air Cooler": 220,
"Air Conditioner (1 Ton)": 1200,
"Air Conditioner (1.5 Ton)": 1500,
"Air Conditioner (2 Ton)": 2000,
},
"🍳 Kitchen": {
"Refrigerator (Small)": 120,
"Refrigerator (Large)": 180,
"Deep Freezer": 300,
"Microwave Oven": 1200,
"OTG Oven": 1500,
"Induction Stove": 1800,
"Electric Kettle": 1500,
"Rice Cooker": 700,
"Mixer Grinder": 500,
"Juicer": 400,
"Dishwasher": 1800,
"Water Purifier": 35,
"Chimney": 250,
"Toaster": 800,
},
"👕 Laundry": {
"Washing Machine": 500,
"Clothes Dryer": 2500,
"Electric Iron": 1000,
},
"💻 Electronics": {
"LED TV (32 inch)": 60,
"LED TV (55 inch)": 120,
"Desktop Computer": 250,
"Laptop": 65,
"Gaming PC": 500,
"WiFi Router": 12,
"Printer": 100,
"Monitor": 40,
},
"📱 Charging": {
"Mobile Charger": 10,
"Tablet Charger": 15,
"Smartwatch Charger": 5,
"Power Bank Charger": 18,
},
"🚿 Bathroom": {
"Water Heater (Geyser)": 2000,
"Hair Dryer": 1500,
"Electric Shaver": 15,
},
"🔌 Utility": {
"Water Pump": 750,
"Vacuum Cleaner": 1200,
"Pressure Washer": 1800,
"Inverter": 50,
"Air Purifier": 50,
"Humidifier": 30,
"Dehumidifier": 300,
"Aquarium Pump": 25,
}
}
# -----------------------------------------------------
# ELECTRICITY PROVIDER DEFAULT RATES
# -----------------------------------------------------
provider_rates = {
"APSPDCL (Andhra Pradesh South)": 7.85,
"APEPDCL (Andhra Pradesh East)": 7.60,
"TGNPDCL (Telangana North)": 8.10,
"TSSPDCL (Telangana South)": 8.25,
"TANGEDCO (Tamil Nadu)": 6.50,
"BESCOM (Bengaluru)": 8.20,
"KSEB (Kerala)": 6.80,
"MSEDCL (Maharashtra)": 9.10,
"BSES Rajdhani (Delhi)": 8.40,
"BSES Yamuna (Delhi)": 8.35,
"TPDDL (Delhi)": 8.15,
"Other": 8.00
}
st.subheader("🏠 Appliance Information")
room = st.selectbox(
"Select Room",
[
"Living Room",
"Bedroom",
"Kitchen",
"Bathroom",
"Dining Room",
"Balcony",
"Garage",
"Office",
"Other"
]
)
category = st.selectbox(
"🏠 Select Category",
list(appliances.keys())
)
appliance = st.selectbox(
"⚡ Select Appliance",
list(appliances[category].keys())
)
default_power = appliances[category][appliance]
power = st.number_input(
"Power (Watts)",
value=default_power
)
quantity = st.number_input(
"🔢 Quantity",
min_value=1,
value=1
)
hours = st.slider(
"⏰ Hours Used Per Day",
min_value=0.0,
max_value=24.0,
value=5.0,
step=0.5
)
add = st.button("➕ Add Appliance")
if add:
monthly_units = (
power *
quantity *
hours *
30
) / 1000
st.session_state.usage_data.append(
{
"Room": room,
"Category": category,
"Appliance": appliance,
"Power (W)": power,
"Quantity": quantity,
"Hours/day": hours,
"Monthly Units (kWh)": round(monthly_units, 2)
}
)
st.success(f"✅ {appliance} added successfully!")
if st.session_state.usage_data:
st.divider()
st.subheader("📋 Added Appliances")
df = pd.DataFrame(st.session_state.usage_data)
display_df = df[
[
"Room",
"Appliance",
"Power (W)",
"Quantity",
"Hours/day",
"Monthly Units (kWh)"
]
]
event = st.dataframe(
display_df,
use_container_width=True,
on_select="rerun",
selection_mode="single-row"
)
selected_rows = event.selection.rows
if len(selected_rows) > 0:
selected_index = selected_rows[0]
selected = df.iloc[selected_index]
st.divider()
st.subheader("📌 Selected Appliance")
c1, c2, c3 = st.columns(3)
with c1:
st.metric("Appliance", selected["Appliance"])
with c2:
st.metric("Power", f'{selected["Power (W)"]} W')
with c3:
st.metric("Monthly Units",
f'{selected["Monthly Units (kWh)"]:.2f} kWh')
if st.button(
"🗑 Remove Appliance",
type="primary",
use_container_width=True
):
del st.session_state.usage_data[selected_index]
st.success("Appliance removed successfully.")
st.rerun()
st.divider()
if df.empty:
st.warning("⚠ Please add appliances in the Energy Analyzer first.")
st.stop()
total_units = df["Monthly Units (kWh)"].sum()
unit_rate = st.session_state.get("unit_rate", 8.0)
# Carbon Footprint (Approximation)
carbon_footprint = total_units * 0.82
st.session_state.carbon_footprint = carbon_footprint
# Save values for other pages
st.session_state.unit_rate = unit_rate
st.session_state.total_units = total_units
st.session_state.df = df
st.divider()
st.subheader("⚡ Electricity Tariff")
providers = [
"Custom Flat Rate",
"APSPDCL (Andhra Pradesh South)",
"APEPDCL (Andhra Pradesh East)",
"TSSPDCL (Telangana South)",
"TGNPDCL (Telangana North)",
"BESCOM (Karnataka)",
"TANGEDCO (Tamil Nadu)",
"KSEB (Kerala)"
]
provider = st.selectbox(
"Electricity Provider",
providers,
index=providers.index(
st.session_state.get("provider", "Custom Flat Rate")
)
)
st.session_state.provider = provider
billing_method = st.radio(
"Billing Method",
["Flat Rate", "Slab Tariff"],
index=0 if st.session_state.get("billing_method", "Flat Rate") == "Flat Rate" else 1
)
st.session_state.billing_method = billing_method
# ---------------------------------------------
# Sample Slab Tariff
# ---------------------------------------------
# ---------------------------------------------
# Electricity Board Slabs
# ---------------------------------------------
provider_slabs = {
"APSPDCL (Andhra Pradesh South)": [
(50, 2.00),
(50, 3.50),
(100, 5.50),
(float("inf"), 7.00)
],
"APEPDCL (Andhra Pradesh East)": [
(50, 2.00),
(50, 3.50),
(100, 5.50),
(float("inf"), 7.00)
],
"TSSPDCL (Telangana South)": [
(50, 2.50),
(50, 4.00),
(100, 6.00),
(float("inf"), 8.00)
],
"TGNPDCL (Telangana North)": [
(50, 2.50),
(50, 4.00),
(100, 6.00),
(float("inf"), 8.00)
],
"BESCOM (Karnataka)": [
(50, 2.80),
(50, 4.20),
(100, 6.20),
(float("inf"), 8.50)
],
"TANGEDCO (Tamil Nadu)": [
(100, 0.00),
(100, 2.25),
(300, 4.50),
(float("inf"), 6.00)
]
}
# ---------------------------------------------
# BILLING METHOD
# ---------------------------------------------
if billing_method == "Flat Rate":
if provider == "Custom Flat Rate":
unit_rate = st.number_input(
"Enter Electricity Rate (₹/Unit)",
min_value=1.0,
value=st.session_state.get("unit_rate", 8.0),
step=0.5
)
else:
default_rate = provider_rates.get(provider, 8.0)
unit_rate = st.number_input(
"Default Electricity Rate (Editable)",
min_value=1.0,
value=float(default_rate),
step=0.5
)
st.session_state.unit_rate = unit_rate
estimated_bill = total_units * unit_rate
else:
remaining_units = total_units
estimated_bill = 0
bill_breakdown = []
slabs = provider_slabs.get(
provider,
[
(50,2),
(50,4),
(100,6),
(float("inf"),8)
]
)
for slab_units, slab_rate in slabs:
units_in_slab = min(remaining_units, slab_units)
cost = units_in_slab * slab_rate
estimated_bill += cost
bill_breakdown.append({
"Units": units_in_slab,
"Rate": slab_rate,
"Cost": cost
})
remaining_units -= units_in_slab
if remaining_units <= 0:
break
st.session_state.bill_breakdown = bill_breakdown
st.session_state.estimated_bill = estimated_bill
st.session_state.total_units = total_units
st.session_state.billing_method = billing_method
cost_per_person = estimated_bill / family_members
cost_per_room = estimated_bill / rooms
st.subheader("📈 Household Energy Summary")
if billing_method == "Slab Tariff":
st.subheader("🧾 Bill Breakdown")
slab_labels = [
"0–50 Units",
"51–100 Units",
"101–200 Units",
"Above 200 Units"
]
breakdown_df = pd.DataFrame(st.session_state.bill_breakdown)
breakdown_df["Slab Range"] = slab_labels[:len(breakdown_df)]
breakdown_df = breakdown_df.rename(columns={
"Units": "Units Used",
"Rate": "Rate (₹/Unit)",
"Cost": "Amount (₹)"
})
breakdown_df = breakdown_df[
[
"Slab Range",
"Units Used",
"Rate (₹/Unit)",
"Amount (₹)"
]
]
st.dataframe(
breakdown_df,
use_container_width=True,
hide_index=True
)
col1, col2, col3 = st.columns(3)
with col1:
st.metric(
"👨👩👧👦 Cost per Family Member",
f"₹ {cost_per_person:.2f}"
)
with col2:
st.metric(
"🚪 Cost per Room",
f"₹ {cost_per_room:.2f}"
)
with col3:
st.metric(
"🔌 Appliances Added",
len(df)
)
st.divider()
st.subheader("🌍 Carbon Footprint")
co2 = total_units * 0.82
trees = co2 / 21
col1, col2 = st.columns(2)
with col1:
st.metric(
"CO₂ Emissions",
f"{co2:.1f} kg/month"
)
with col2:
st.metric(
"Trees Needed",
f"{trees:.1f}"
)
st.divider()
st.subheader("⚡ Appliance Statistics")
highest = df.loc[
df["Monthly Units (kWh)"].idxmax()
]
lowest = df.loc[
df["Monthly Units (kWh)"].idxmin()
]
unique_appliances = df["Appliance"].nunique()
if unique_appliances == 1:
st.success(
f"🏆 Highest Consumer : {highest['Appliance']}"
)
st.write(
f"Monthly Units : {highest['Monthly Units (kWh)']:.2f} kWh"
)
st.info(
"ℹ Only one appliance type available.\n\n"
"Add another appliance type to compare consumption."
)
else:
c1, c2 = st.columns(2)
with c1:
st.success(
f"🏆 Highest Consumer : {highest['Appliance']}"
)
st.write(
f"Monthly Units : {highest['Monthly Units (kWh)']:.2f} kWh"
)
with c2:
st.info(
f"🌱 Lowest Consumer : {lowest['Appliance']}"
)
st.write(
f"Monthly Units : {lowest['Monthly Units (kWh)']:.2f} kWh"
)
st.metric(
"💵 Estimated Monthly Bill",
f"₹ {estimated_bill:.2f}"
)
col1, col2 = st.columns(2)
with col1:
if st.button("🗑 Clear All"):
st.session_state.usage_data = []
st.rerun()
with col2:
st.download_button(
"📥 Download CSV",
df.to_csv(index=False),
"energy_report.csv",
"text/csv"
)
# -----------------------------------------
# DASHBOARD
# -----------------------------------------
elif page == "📊 Dashboard":
st.title("📊 Smart Energy Dashboard")
if len(st.session_state.usage_data) == 0:
st.warning("⚠ Please add appliances in the Energy Analyzer first.")
else:
df = pd.DataFrame(st.session_state.usage_data)
# ---------------------------------------
# Appliance Summary (Grouped)
# ---------------------------------------
summary_df = (
df.groupby("Appliance", as_index=False)
.agg({
"Monthly Units (kWh)": "sum",
"Power (W)": "sum"
})
)
unit_rate = st.session_state.get("unit_rate", 8.0)
estimated_bill = st.session_state.get("estimated_bill", 0)
st.subheader("📋 Appliance Data")
st.dataframe(df, use_container_width=True)
total_units = df["Monthly Units (kWh)"].sum()
st.metric(
"⚡ Total Monthly Units",
f"{total_units:.2f} kWh"
)
st.divider()
st.divider()
st.subheader("📊 Appliance-wise Consumption")
fig2 = px.bar(
summary_df,
x="Appliance",
y="Monthly Units (kWh)",
color="Monthly Units (kWh)",
text="Monthly Units (kWh)"
)
fig2.update_traces(
textposition="outside"
)
st.plotly_chart(
fig2,
use_container_width=True
)
st.divider()
highest = df.loc[
df["Monthly Units (kWh)"].idxmax()
]
percentage = (
highest["Monthly Units (kWh)"] /
total_units
) * 100
st.success(
f"🏆 Highest Consumer: **{highest['Appliance']}**\n\n"
f"⚡ {highest['Monthly Units (kWh)']:.2f} kWh/month\n\n"
f"📊 {percentage:.1f}% of total household consumption"
)
st.divider()
st.subheader("🌱 Smart Energy Score")
# ----------------------------------------
# SMART ENERGY SCORE
# ----------------------------------------
score = 100
# Overall Monthly Consumption (60 Marks)
if total_units <= 100:
score -= 0
elif total_units <= 200:
score -= 10
elif total_units <= 300:
score -= 20
elif total_units <= 400:
score -= 35
else:
score -= 50
# High Power Appliance Penalty (20 Marks)
high_power_count = len(
df[df["Power (W)"] >= 1500]
)
score -= high_power_count * 5
# Long Usage Penalty (20 Marks)
long_usage = len(
df[df["Hours/day"] >= 8]
)
score -= long_usage * 3
score = max(0, min(score, 100))
st.metric(
"Energy Score",
f"{score}/100"
)
if score >= 90:
grade = "A+"
elif score >= 80:
grade = "A"
elif score >= 70:
grade = "B"
elif score >= 60:
grade = "C"
else:
grade = "D"
st.metric(
"🏆 Energy Grade",
grade
)
st.session_state.energy_score = score
st.session_state.energy_grade = grade
if score >= 90:
st.success("🌟 Excellent! Your home is highly energy efficient.")
elif score >= 75:
st.info("👍 Good! Small improvements can reduce your bill further.")
elif score >= 60:
st.warning("⚠ Average efficiency. Consider reducing high-power appliances.")
else:
st.error("🚨 High electricity consumption detected.")
st.divider()
st.subheader("🤖 AI Smart Recommendation")
highest = df.loc[
df["Monthly Units (kWh)"].idxmax()
]
percentage = (
highest["Monthly Units (kWh)"] /
total_units
) * 100
st.warning(
f"""
### ⚡ Highest Energy Consumer
**{highest['Appliance']}**
⚡ Monthly Consumption:
**{highest['Monthly Units (kWh)']:.2f} kWh**
📊 Share of Total Consumption:
**{percentage:.1f}%**
💡 AI Recommendation:
Reduce its daily usage by **1 hour**
or switch to an energy-efficient model.
This appliance has the greatest potential for reducing your electricity bill.
"""
)
st.divider()
st.subheader("💰 Smart Savings Simulator")
df["Display Name"] = (
df["Room"] + " - " + df["Appliance"]
)
selected = st.selectbox(
"Select Appliance to Optimize",
df["Display Name"]
)
selected_row = df[
df["Display Name"] == selected
].iloc[0]
current_hours = selected_row["Hours/day"]
st.write(
f"Current Daily Usage: **{current_hours:.1f} hours/day**"
)
new_hours = st.slider(
"Reduce Daily Usage To",
min_value=0.0,
max_value=current_hours,
value=max(0.0, current_hours - 1),
step=0.5
)
hours_saved = current_hours - new_hours
saved_units = (
selected_row["Power (W)"] *
selected_row["Quantity"] *
hours_saved *
30
) / 1000