forked from mmfarabi/EcoSphereAI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
2760 lines (2366 loc) · 123 KB
/
app.py
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 joblib
import sqlite3
from openai import OpenAI
from datetime import datetime
import plotly.express as px
import folium
from streamlit_folium import folium_static
from joblib import Parallel, delayed
from datetime import datetime, time, date
from PIL import Image
import io
import base64
import os
# Initialize SQLite database
def init_db():
conn = sqlite3.connect("app.db")
c = conn.cursor()
# Create users table with full_name and avatar
c.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE,
password TEXT,
full_name TEXT,
avatar BLOB)''')
# Create sessions1 table
c.execute('''CREATE TABLE IF NOT EXISTS sessions1
(id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
input_data TEXT,
predictions TEXT,
insights TEXT,
timestamp DATETIME)''')
# Create sessions2 table
c.execute('''CREATE TABLE IF NOT EXISTS sessions2
(id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
input_data TEXT,
predictions TEXT,
insights TEXT,
timestamp DATETIME)''')
# Create sessions3 table
c.execute('''CREATE TABLE IF NOT EXISTS sessions3
(id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
input_data TEXT,
predictions TEXT,
insights TEXT,
timestamp DATETIME)''')
# Create sessions4 table
c.execute('''CREATE TABLE IF NOT EXISTS sessions4
(id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
input_data TEXT,
predictions TEXT,
insights TEXT,
timestamp DATETIME)''')
# Create sessions5 table
c.execute('''CREATE TABLE IF NOT EXISTS sessions5
(id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
input_data TEXT,
predictions TEXT,
insights TEXT,
timestamp DATETIME)''')
# Create sessions6 table
c.execute('''CREATE TABLE IF NOT EXISTS sessions6
(id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
input_data TEXT,
predictions TEXT,
insights TEXT,
timestamp DATETIME)''')
# Create sessions7 table
c.execute('''CREATE TABLE IF NOT EXISTS sessions7
(id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
input_data TEXT,
predictions TEXT,
insights TEXT,
timestamp DATETIME)''')
# Create sessions8 table
c.execute('''CREATE TABLE IF NOT EXISTS sessions8
(id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
input_data TEXT,
predictions TEXT,
insights TEXT,
timestamp DATETIME)''')
# Create sessions9 table
c.execute('''CREATE TABLE IF NOT EXISTS sessions9
(id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
input_data TEXT,
predictions TEXT,
insights TEXT,
timestamp DATETIME)''')
# Create tickets1 table
c.execute('''CREATE TABLE IF NOT EXISTS tickets1
(id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
username TEXT,
full_name TEXT,
ticket_text TEXT,
timestamp DATETIME)''')
# Create tickets2 table
c.execute('''CREATE TABLE IF NOT EXISTS tickets2
(id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
username TEXT,
full_name TEXT,
ticket_text TEXT,
timestamp DATETIME)''')
# Create tickets3 table
c.execute('''CREATE TABLE IF NOT EXISTS tickets3
(id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
username TEXT,
full_name TEXT,
ticket_text TEXT,
timestamp DATETIME)''')
# Create tickets4 table
c.execute('''CREATE TABLE IF NOT EXISTS tickets4
(id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
username TEXT,
full_name TEXT,
ticket_text TEXT,
timestamp DATETIME)''')
# Create tickets5 table
c.execute('''CREATE TABLE IF NOT EXISTS tickets5
(id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
username TEXT,
full_name TEXT,
ticket_text TEXT,
timestamp DATETIME)''')
# Create tickets6 table
c.execute('''CREATE TABLE IF NOT EXISTS tickets6
(id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
username TEXT,
full_name TEXT,
ticket_text TEXT,
timestamp DATETIME)''')
# Create tickets7 table
c.execute('''CREATE TABLE IF NOT EXISTS tickets7
(id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
username TEXT,
full_name TEXT,
ticket_text TEXT,
timestamp DATETIME)''')
# Create tickets8 table
c.execute('''CREATE TABLE IF NOT EXISTS tickets8
(id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
username TEXT,
full_name TEXT,
ticket_text TEXT,
timestamp DATETIME)''')
# Create tickets9 table
c.execute('''CREATE TABLE IF NOT EXISTS tickets9
(id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
username TEXT,
full_name TEXT,
ticket_text TEXT,
timestamp DATETIME)''')
conn.commit()
conn.close()
# Initialize database
init_db()
# Initialize Gemini AI client
client = OpenAI(
api_key="AIzaSyB9nIGLfLqAqkCvhjSPHudNcnxefFjOHxI", # Replace with your actual Gemini API key
base_url="https://generativelanguage.googleapis.com/v1beta/"
)
# Function to create a rounded image
def rounded_image(image):
# Convert image to base64
buffered = io.BytesIO()
image.save(buffered, format="PNG")
img_str = base64.b64encode(buffered.getvalue()).decode()
# Create a circular mask
rounded_image_html = f"""
<style>
.rounded-image {{
border-radius: 50%;
overflow: hidden;
width: 100px;
height: 100px;
object-fit: cover;
}}
</style>
<img src="data:image/png;base64,{img_str}" class="rounded-image">
"""
return rounded_image_html
# Function to validate password
def validate_password(password):
if len(password) < 8:
return False, "Password must be at least 8 characters long."
return True, ""
# Function to update user information
def update_user_info(user_id, full_name, username, password, avatar):
conn = sqlite3.connect("app.db")
c = conn.cursor()
if avatar is not None:
c.execute('''UPDATE users SET full_name = ?, username = ?, password = ?, avatar = ? WHERE id = ?''',
(full_name, username, password, avatar, user_id))
else:
c.execute('''UPDATE users SET full_name = ?, username = ?, password = ? WHERE id = ?''',
(full_name, username, password, user_id))
conn.commit()
conn.close()
# Function to fetch user information
def fetch_user_info(user_id):
conn = sqlite3.connect("app.db")
c = conn.cursor()
c.execute('''SELECT full_name, username, password, avatar FROM users WHERE id = ?''', (user_id,))
user_info = c.fetchone()
conn.close()
return user_info
# Dashboard Page
def dashboard_page():
# Function to validate dataset columns
def validate_dataset(dataset, required_columns):
if not all(column in dataset.columns for column in required_columns):
return False
return True
# Load default datasets
nodes = pd.read_csv("nodes.csv")
energy_usage = pd.read_csv("energy_usage.csv")
environment = pd.read_csv("environment.csv")
procurement = pd.read_csv("procurement.csv")
traffic = pd.read_csv("traffic.csv")
# Streamlit App Title
st.title("EcoSphereAI Dashboard")
# Create tabs for navigation
tab1, tab2, tab3, tab4, tab5 = st.tabs(["Nodes", "Energy Usage", "Environment", "Procurement", "Traffic"])
# Nodes Tab
with tab1:
st.header("Nodes Data")
# File Upload Option for Nodes
uploaded_nodes = st.file_uploader("Upload Nodes CSV", type=["csv"], key="nodes")
if uploaded_nodes is not None:
try:
nodes = pd.read_csv(uploaded_nodes)
required_columns = ['Node_ID', 'Region', 'Population_Served', 'Connectivity_Status', 'Existing_Infrastructure', 'Latitude', 'Longitude', 'Type']
if not validate_dataset(nodes, required_columns):
st.warning("Invalid dataset uploaded. Please ensure the dataset contains the required columns.")
nodes = pd.read_csv("nodes.csv")
except Exception as e:
st.warning(f"Invalid dataset uploaded. Error: {e}")
nodes = pd.read_csv("nodes.csv")
# Display the DataFrame
st.write(nodes)
# Cards for Nodes Metrics
st.subheader("Nodes Metrics")
col1, col2, col3, col4 = st.columns(4)
col1.markdown("**Total Nodes**")
col1.markdown(f"<div style='text-align: center; font-size: 24px;'>{len(nodes)}</div>", unsafe_allow_html=True)
col2.markdown("**Total Regions**")
col2.markdown(f"<div style='text-align: center; font-size: 24px;'>{nodes['Region'].nunique()}</div>", unsafe_allow_html=True)
col3.markdown("**Total Population Served**")
col3.markdown(f"<div style='text-align: center; font-size: 24px;'>{nodes['Population_Served'].sum()}</div>", unsafe_allow_html=True)
col4.markdown("**Connected Nodes**")
col4.markdown(f"<div style='text-align: center; font-size: 24px;'>{nodes[nodes['Connectivity_Status'] == 'Connected'].shape[0]}</div>", unsafe_allow_html=True)
col5, col6 = st.columns(2)
col5.markdown("**Unconnected Nodes**")
col5.markdown(f"<div style='text-align: center; font-size: 24px;'>{nodes[nodes['Connectivity_Status'] == 'Unconnected'].shape[0]}</div>", unsafe_allow_html=True)
# Organization Types
st.subheader("Organization Types")
org_types = nodes['Type'].value_counts().reset_index()
org_types.columns = ['Type', 'Count']
st.write(org_types)
# Node Search Option
st.subheader("Search for a Node")
search_node_id = st.text_input("Enter Node ID to search:")
searched_node = None
if search_node_id:
filtered_nodes = nodes[nodes['Node_ID'].astype(str).str.contains(search_node_id)]
if not filtered_nodes.empty:
searched_node = filtered_nodes.iloc[0]
st.success(f"Node {searched_node['Node_ID']} found!")
else:
st.warning("No matching Node ID found.")
# Node Locations on Map with Enhanced Popups
st.subheader("Node Locations on Map")
stamen_terrain = folium.TileLayer(
tiles='https://stamen-tiles.a.ssl.fastly.net/terrain/{z}/{x}/{y}.png',
attr='Map tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>. Data by <a href="http://openstreetmap.org">OpenStreetMap</a>, under <a href="http://www.openstreetmap.org/copyright">ODbL</a>.',
name='Stamen Terrain'
)
if searched_node is not None:
map_center = [searched_node['Latitude'], searched_node['Longitude']]
zoom_level = 10
else:
map_center = [nodes['Latitude'].mean(), nodes['Longitude'].mean()]
zoom_level = 2
map = folium.Map(location=map_center, zoom_start=zoom_level)
stamen_terrain.add_to(map)
for idx, row in nodes.iterrows():
if row['Connectivity_Status'] == 'Connected':
color = 'green'
else:
color = 'red'
popup_content = f"""
<b>Node ID:</b> {row['Node_ID']}<br>
<b>Region:</b> {row['Region']}<br>
<b>Population Served:</b> {row['Population_Served']}<br>
<b>Connectivity Status:</b> {row['Connectivity_Status']}<br>
<b>Existing Infrastructure:</b> {'Yes' if row['Existing_Infrastructure'] == 1 else 'No'}<br>
<b>Latitude:</b> {row['Latitude']}<br>
<b>Longitude:</b> {row['Longitude']}<br>
<b>Type:</b> {row['Type']}
"""
folium.Marker(
location=[row['Latitude'], row['Longitude']],
popup=folium.Popup(popup_content, max_width=300),
icon=folium.Icon(color=color, icon='flag')
).add_to(map)
if searched_node is not None:
searched_popup_content = f"""
<b>Node ID:</b> {searched_node['Node_ID']}<br>
<b>Region:</b> {searched_node['Region']}<br>
<b>Population Served:</b> {searched_node['Population_Served']}<br>
<b>Connectivity Status:</b> {searched_node['Connectivity_Status']}<br>
<b>Existing Infrastructure:</b> {'Yes' if searched_node['Existing_Infrastructure'] == 1 else 'No'}<br>
<b>Latitude:</b> {searched_node['Latitude']}<br>
<b>Longitude:</b> {searched_node['Longitude']}<br>
<b>Type:</b> {searched_node['Type']}
"""
folium.Marker(
location=[searched_node['Latitude'], searched_node['Longitude']],
popup=folium.Popup(searched_popup_content, max_width=300),
icon=folium.Icon(color='blue', icon='star')
).add_to(map)
folium_static(map)
# Regional Connectivity Insights
st.subheader("Regional Connectivity Insights")
nodes['Existing_Infrastructure'] = nodes['Existing_Infrastructure'].map({'Yes': 1, 'No': 0})
nodes['Connectivity_Status'] = nodes['Connectivity_Status'].map({'Connected': 1, 'Unconnected': 0})
regional_analysis = nodes.groupby('Region').agg({
'Connectivity_Status': 'mean',
'Population_Served': 'sum',
'Existing_Infrastructure': 'mean',
'Node_ID': 'count',
}).reset_index()
regional_analysis.rename(columns={
'Connectivity_Status': 'Connectivity_Rate',
'Existing_Infrastructure': 'Infrastructure_Rate',
'Node_ID': 'Node_Count'
}, inplace=True)
st.write(regional_analysis[['Region', 'Connectivity_Rate', 'Population_Served', 'Infrastructure_Rate']])
st.subheader("Regions with the Lowest Connectivity Rates (Priority for Improvement)")
low_connectivity_regions = regional_analysis.sort_values(by='Connectivity_Rate', ascending=True)[['Region', 'Connectivity_Rate', 'Population_Served']]
st.write(low_connectivity_regions)
st.subheader("Connectivity Ratio by Region")
connectivity_ratio = nodes.groupby('Region')['Connectivity_Status'].apply(lambda x: (x == 1).mean()).reset_index()
fig = px.bar(connectivity_ratio, x='Region', y='Connectivity_Status', labels={'Connectivity_Status': 'Connected Ratio'}, color_discrete_sequence=['#1f77b4'])
st.plotly_chart(fig)
# Energy Usage Tab
with tab2:
st.header("Energy Usage Data")
# File Upload Option for Energy Usage
uploaded_energy_usage = st.file_uploader("Upload Energy Usage CSV", type=["csv"], key="energy_usage")
if uploaded_energy_usage is not None:
try:
energy_usage = pd.read_csv(uploaded_energy_usage)
required_columns = ['Energy_Usage_kWh', 'Carbon_Emissions_kg_CO2', 'Energy_Source', 'Peak_Usage_Time']
if not validate_dataset(energy_usage, required_columns):
st.warning("Invalid dataset uploaded. Please ensure the dataset contains the required columns.")
energy_usage = pd.read_csv("energy_usage.csv")
except Exception as e:
st.warning(f"Invalid dataset uploaded. Error: {e}")
energy_usage = pd.read_csv("energy_usage.csv")
# Display the DataFrame
st.write(energy_usage)
st.header("Energy Usage Metrics")
col1, col2, col3 = st.columns(3)
col1.markdown("**Total Energy Used (kWh)**")
col1.markdown(f"<div style='text-align: center; font-size: 24px;'>{energy_usage['Energy_Usage_kWh'].sum()}</div>", unsafe_allow_html=True)
col2.markdown("**Total Carbon Emissions (kg CO2)**")
col2.markdown(f"<div style='text-align: center; font-size: 24px;'>{energy_usage['Carbon_Emissions_kg_CO2'].sum()}</div>", unsafe_allow_html=True)
col3.markdown("**Energy Sources**")
col3.markdown(f"<div style='text-align: center; font-size: 24px;'>{energy_usage['Energy_Source'].nunique()}</div>", unsafe_allow_html=True)
st.subheader("Energy Source Breakdown (Total Energy Produced)")
energy_source_energy = energy_usage.groupby('Energy_Source')['Energy_Usage_kWh'].sum().reset_index()
for idx, row in energy_source_energy.iterrows():
st.markdown(f"**{row['Energy_Source']}**: {row['Energy_Usage_kWh']:.2f} kWh")
st.subheader("Energy Source Breakdown (Total Carbon Emissions)")
energy_source_emissions = energy_usage.groupby('Energy_Source')['Carbon_Emissions_kg_CO2'].sum().reset_index()
for idx, row in energy_source_emissions.iterrows():
st.markdown(f"**{row['Energy_Source']}**: {row['Carbon_Emissions_kg_CO2']:.2f} kg CO2")
st.subheader("Carbon Emissions by Energy Source")
fig = px.bar(energy_source_emissions, x='Energy_Source', y='Carbon_Emissions_kg_CO2', labels={'Carbon_Emissions_kg_CO2': 'Carbon Emissions (kg CO2)'}, color_discrete_sequence=['#ff7f0e'])
st.plotly_chart(fig)
st.subheader("Energy Sources Used")
energy_sources = energy_usage['Energy_Source'].value_counts().reset_index()
energy_sources.columns = ['Energy_Source', 'Count']
fig = px.bar(energy_sources, x='Energy_Source', y='Count', labels={'Count': 'Number of Nodes'}, color_discrete_sequence=['#1f77b4'])
st.plotly_chart(fig)
st.subheader("Peak Usage Time")
peak_usage = energy_usage.groupby('Peak_Usage_Time')['Energy_Usage_kWh'].sum().reset_index()
fig = px.line(peak_usage, x='Peak_Usage_Time', y='Energy_Usage_kWh', labels={'Energy_Usage_kWh': 'Energy Usage (kWh)'}, color_discrete_sequence=['#2ca02c'])
st.plotly_chart(fig)
# Environment Tab
with tab3:
st.header("Environment Data")
# File Upload Option for Environment
uploaded_environment = st.file_uploader("Upload Environment CSV", type=["csv"], key="environment")
if uploaded_environment is not None:
try:
environment = pd.read_csv(uploaded_environment)
required_columns = ['Region_Name', 'Disaster_Risk_Level', 'Past_Disruptions']
if not validate_dataset(environment, required_columns):
st.warning("Invalid dataset uploaded. Please ensure the dataset contains the required columns.")
environment = pd.read_csv("environment.csv")
except Exception as e:
st.warning(f"Invalid dataset uploaded. Error: {e}")
environment = pd.read_csv("environment.csv")
# Display the DataFrame
st.write(environment)
st.header("Environment Metrics")
st.subheader("Disaster Risk Level Metrics")
col1, col2, col3, col4 = st.columns(4)
col1.markdown("**Total Disasters**")
col1.markdown(f"<div style='text-align: center; font-size: 24px;'>{environment['Disaster_Risk_Level'].count()}</div>", unsafe_allow_html=True)
col2.markdown("**Low Risk Level**")
col2.markdown(f"<div style='text-align: center; font-size: 24px;'>{environment[environment['Disaster_Risk_Level'] == 'Low'].shape[0]}</div>", unsafe_allow_html=True)
col3.markdown("**Medium Risk Level**")
col3.markdown(f"<div style='text-align: center; font-size: 24px;'>{environment[environment['Disaster_Risk_Level'] == 'Medium'].shape[0]}</div>", unsafe_allow_html=True)
col4.markdown("**High Risk Level**")
col4.markdown(f"<div style='text-align: center; font-size: 24px;'>{environment[environment['Disaster_Risk_Level'] == 'High'].shape[0]}</div>", unsafe_allow_html=True)
st.subheader("Total Past Disruptions")
total_past_disruptions = environment['Past_Disruptions'].sum()
st.markdown(f"<div style='text-align: center; font-size: 24px;'>{total_past_disruptions}</div>", unsafe_allow_html=True)
st.subheader("Risk Level by Regions")
risk_levels = environment.groupby(['Region_Name', 'Disaster_Risk_Level']).size().reset_index(name='Count')
fig = px.bar(risk_levels, x='Count', y='Region_Name', color='Disaster_Risk_Level', orientation='h',
labels={'Count': 'Number of Regions', 'Region_Name': 'Region'},
color_discrete_sequence=['#1f77b4', '#ff7f0e', '#2ca02c'])
st.plotly_chart(fig)
# Procurement Tab
with tab4:
st.header("Procurement Data")
# File Upload Option for Procurement
uploaded_procurement = st.file_uploader("Upload Procurement CSV", type=["csv"], key="procurement")
if uploaded_procurement is not None:
try:
procurement = pd.read_csv(uploaded_procurement)
required_columns = ['Equipment_Used', 'Cost_USD', 'Quantity']
if not validate_dataset(procurement, required_columns):
st.warning("Invalid dataset uploaded. Please ensure the dataset contains the required columns.")
procurement = pd.read_csv("procurement.csv")
except Exception as e:
st.warning(f"Invalid dataset uploaded. Error: {e}")
procurement = pd.read_csv("procurement.csv")
# Display the DataFrame
st.write(procurement)
st.header("Procurement Metrics")
st.subheader("Equipment Cost Breakdown")
equipment_cost = procurement.groupby('Equipment_Used')['Cost_USD'].sum().reset_index()
for idx, row in equipment_cost.iterrows():
st.markdown(f"**{row['Equipment_Used']}**: {row['Cost_USD']:.2f} USD")
st.subheader("Total Cost USD Spent")
total_cost = procurement['Cost_USD'].sum()
st.markdown(f"<div style='text-align: center; font-size: 24px;'>{total_cost:.2f} USD</div>", unsafe_allow_html=True)
st.subheader("Total Equipment Used")
equipment_quantity = procurement.groupby('Equipment_Used')['Quantity'].sum().reset_index()
for idx, row in equipment_quantity.iterrows():
st.markdown(f"**{row['Equipment_Used']}**: {row['Quantity']}")
st.subheader("Total Equipment Used by Type")
fig = px.bar(equipment_quantity, x='Equipment_Used', y='Quantity', labels={'Quantity': 'Total Quantity'}, color_discrete_sequence=['#d62728'])
st.plotly_chart(fig)
st.subheader("Total Cost Spent by Equipment Type")
fig = px.bar(equipment_cost, x='Equipment_Used', y='Cost_USD', labels={'Cost_USD': 'Total Cost (USD)'}, color_discrete_sequence=['#9467bd'])
st.plotly_chart(fig)
# Traffic Tab
with tab5:
st.header("Traffic Data")
# File Upload Option for Traffic
uploaded_traffic = st.file_uploader("Upload Traffic CSV", type=["csv"], key="traffic")
if uploaded_traffic is not None:
try:
traffic = pd.read_csv(uploaded_traffic)
required_columns = ['Node_ID', 'Date', 'Time', 'Data_Usage_GB', 'Peak_Usage_GB']
if not validate_dataset(traffic, required_columns):
st.warning("Invalid dataset uploaded. Please ensure the dataset contains the required columns.")
traffic = pd.read_csv("traffic.csv")
except Exception as e:
st.warning(f"Invalid dataset uploaded. Error: {e}")
traffic = pd.read_csv("traffic.csv")
# Display the DataFrame
st.write(traffic)
st.header("Traffic Metrics")
st.subheader("Traffic Metrics")
st.markdown("**Total Data Usage (GB)**")
st.markdown(f"<div style='text-align: center; font-size: 24px;'>{traffic['Data_Usage_GB'].sum()}</div>", unsafe_allow_html=True)
st.markdown("**Total Peak Usage (GB)**")
st.markdown(f"<div style='text-align: center; font-size: 24px;'>{traffic['Peak_Usage_GB'].sum()}</div>", unsafe_allow_html=True)
st.markdown("**Highest Data Usage Node ID**")
st.markdown(f"<div style='text-align: center; font-size: 24px;'>{traffic.loc[traffic['Data_Usage_GB'].idxmax(), 'Node_ID']}</div>", unsafe_allow_html=True)
st.markdown("**Highest Peak Usage Node ID**")
st.markdown(f"<div style='text-align: center; font-size: 24px;'>{traffic.loc[traffic['Peak_Usage_GB'].idxmax(), 'Node_ID']}</div>", unsafe_allow_html=True)
traffic['DateTime'] = pd.to_datetime(traffic['Date'] + ' ' + traffic['Time'])
st.subheader("Data Usage Over Time (Area Chart)")
fig_data_usage = px.area(traffic, x='DateTime', y='Data_Usage_GB', labels={'Data_Usage_GB': 'Data Usage (GB)'}, color_discrete_sequence=['#1f77b4'])
fig_data_usage.update_xaxes(tickangle=-45)
st.plotly_chart(fig_data_usage, use_container_width=True)
st.subheader("Peak Usage Over Time (Area Chart)")
fig_peak_usage = px.area(traffic, x='DateTime', y='Peak_Usage_GB', labels={'Peak_Usage_GB': 'Peak Usage (GB)'}, color_discrete_sequence=['#ff7f0e'])
fig_peak_usage.update_xaxes(tickangle=-45)
st.plotly_chart(fig_peak_usage, use_container_width=True)
# Settings Page
def settings_page():
st.title("Settings")
if st.session_state.user_id is not None:
user_info = fetch_user_info(st.session_state.user_id)
if user_info:
full_name = st.text_input("Full Name:", value=user_info[0])
username = st.text_input("Username:", value=user_info[1])
password = st.text_input("Password:", type="password", value=user_info[2])
avatar = st.file_uploader("Upload Avatar Image:", type=["jpg", "jpeg", "png"])
if st.button("Update Information"):
if avatar is not None:
avatar_bytes = avatar.read()
update_user_info(st.session_state.user_id, full_name, username, password, avatar_bytes)
st.session_state.avatar = avatar_bytes
else:
update_user_info(st.session_state.user_id, full_name, username, password, None)
st.success("Information updated successfully!")
else:
st.write("No user information found.")
else:
st.warning("You need to log in to view this page.")
# AI Tool 1: Energy & CO₂ Optimizer
def energy_co2_optimizer():
st.title("Energy Optimization & Carbon Emissions Tracker")
st.write("This tool predicts energy usage and carbon emissions based on input parameters.")
# Load ML models
energy_model_path = 'energy_usage_model.pkl'
carbon_model_path = 'carbon_emissions_model.pkl'
energy_model = joblib.load(energy_model_path)
carbon_model = joblib.load(carbon_model_path)
# Function to collect user input
def collect_user_input():
st.subheader("Provide Input for Prediction")
user_input = {}
user_input['Node_ID'] = st.text_input("Enter Node ID:")
start_date = st.date_input("Enter Start Date (YYYY-MM-DD):")
end_date = st.date_input("Enter End Date (YYYY-MM-DD):")
user_input['Population_Served'] = st.number_input("Enter Population Served:", min_value=1)
user_input['Region'] = st.text_input("Enter Region:").lower()
# Energy Source with "Other" option
energy_source_options = ["Grid", "Solar", "Generator", "Other"]
energy_source = st.selectbox("Select the Energy Source:", energy_source_options)
if energy_source == "Other":
energy_source = st.text_input("Enter the Energy Source manually:")
user_input['Energy_Source'] = energy_source
peak_usage = st.selectbox("Select the Peak Usage Time:", ["Morning", "Afternoon", "Evening", "Night"])
user_input['Peak_Usage_Time'] = peak_usage
# Type with "Other" option
type_options = ["Government Office", "Health Center", "School", "Other"]
type_input = st.selectbox("Select the Type:", type_options)
if type_input == "Other":
type_input = st.text_input("Enter the Type manually:")
user_input['Type'] = type_input
infrastructure_input = st.radio("Existing Infrastructure:", ["Yes", "No"])
user_input['Existing_Infrastructure'] = infrastructure_input
return user_input, start_date, end_date
# Function to predict energy and carbon emissions
def predict_energy_and_carbon(input_data, start_date, end_date):
date_range = pd.date_range(start=start_date, end=end_date, freq='D')
predictions = []
for date in date_range:
month = date.month
day = date.day
input_df = pd.DataFrame([input_data])
input_df['Month'] = month
input_df['Day'] = day
for col in energy_model.feature_names_in_:
if col not in input_df.columns:
input_df[col] = 0
input_df.columns = input_df.columns.astype(str)
input_df = input_df[energy_model.feature_names_in_]
energy_pred = energy_model.predict(input_df)
carbon_pred = carbon_model.predict(input_df)
predictions.append({
'Date': date.strftime('%Y-%m-%d'),
'Energy_Usage_kWh': energy_pred[0],
'Carbon_Emissions_kg_CO2': carbon_pred[0]
})
predictions_df = pd.DataFrame(predictions)
return predictions_df
# Function to get Gemini AI insights
def get_gemini_insights(user_input, predictions_df):
input_text = f"""
User Input:
{user_input}
Predicted Data:
{predictions_df.to_string(index=False)}
Analyze the above data and provide insights, suggestions, and notes for energy optimization and carbon emissions reduction.
Format your response in the following structure:
- **Insights**: List key observations from the data in short, concise bullet points.
- **Suggestions**: Provide actionable suggestions in short, concise bullet points.
- **Notes**: Add any additional notes or considerations in short, concise bullet points.
"""
response = client.chat.completions.create(
model="gemini-1.5-flash",
n=1,
messages=[
{
"role": "system",
"content": "You are an expert in energy optimization and carbon emissions reduction. Your goal is to analyze the provided data and provide actionable insights, suggestions, and notes to optimize energy usage and reduce carbon emissions."
},
{
"role": "user",
"content": input_text
}
]
)
return response.choices[0].message.content
# Function to save session data
def save_session(user_id, input_data, predictions, insights):
conn = sqlite3.connect("app.db")
c = conn.cursor()
c.execute('''INSERT INTO sessions1 (user_id, input_data, predictions, insights, timestamp)
VALUES (?, ?, ?, ?, ?)''',
(user_id, str(input_data), predictions.to_json(), insights, datetime.now()))
conn.commit()
conn.close()
# Function to fetch session data
def fetch_sessions(user_id):
conn = sqlite3.connect("app.db")
c = conn.cursor()
c.execute('''SELECT * FROM sessions1 WHERE user_id = ?''', (user_id,))
sessions = c.fetchall()
conn.close()
return sessions
# Function to save a ticket
def save_ticket(user_id, username, full_name, ticket_text):
conn = sqlite3.connect("app.db")
c = conn.cursor()
c.execute('''INSERT INTO tickets1 (user_id, username, full_name, ticket_text, timestamp)
VALUES (?, ?, ?, ?, ?)''',
(user_id, username, full_name, ticket_text, datetime.now()))
conn.commit()
conn.close()
# Function to fetch all tickets
def fetch_tickets():
conn = sqlite3.connect("app.db")
c = conn.cursor()
c.execute('''SELECT * FROM tickets1 ORDER BY timestamp DESC''')
tickets = c.fetchall()
conn.close()
return tickets
# Tabs for AI Tool, Session, and Ticket
tab1, tab2, tab3 = st.tabs(["AI Tool", "Session", "Ticket"])
with tab1:
st.header("AI Tool")
user_input, start_date, end_date = collect_user_input()
if st.button("Predict"):
predictions_df = predict_energy_and_carbon(user_input, start_date, end_date)
# Display predictions as a DataFrame
st.write("Prediction Results:")
st.dataframe(predictions_df)
insights = get_gemini_insights(user_input, predictions_df)
st.write("Gemini AI Insights, Suggestions, and Notes:")
st.write(insights)
save_session(st.session_state.user_id, user_input, predictions_df, insights)
st.success("Session saved successfully!")
with tab2:
st.header("Session")
sessions = fetch_sessions(st.session_state.user_id)
if sessions:
for session in sessions:
# Use expander for each session
with st.expander(f"Session ID: {session[0]} - {session[5]}"):
st.write(f"Timestamp: {session[5]}")
st.write("Input Data:")
# Convert input data from string to dictionary
input_data = eval(session[2])
# Display input data as bullet points
st.markdown("- **Node ID:** " + str(input_data.get('Node_ID', 'N/A')))
st.markdown("- **Population Served:** " + str(input_data.get('Population_Served', 'N/A')))
st.markdown("- **Region:** " + str(input_data.get('Region', 'N/A')))
st.markdown("- **Energy Source:** " + str(input_data.get('Energy_Source', 'N/A')))
st.markdown("- **Peak Usage Time:** " + str(input_data.get('Peak_Usage_Time', 'N/A')))
st.markdown("- **Type:** " + str(input_data.get('Type', 'N/A')))
st.markdown("- **Existing Infrastructure:** " + str(input_data.get('Existing_Infrastructure', 'N/A')))
st.write("Predictions:")
# Convert JSON predictions back to DataFrame
predictions_df = pd.read_json(session[3])
st.dataframe(predictions_df)
st.write("Insights:")
st.write(session[4])
# Download session data as .txt
session_data = f"Input Data:\n{session[2]}\n\nPredictions:\n{predictions_df.to_string(index=False)}\n\nInsights:\n{session[4]}"
st.download_button(
label=f"Download Session {session[0]}",
data=session_data,
file_name=f"tech_{st.session_state.user_id}_energy_carbon_tracker{session[0]}.txt",
mime="text/plain"
)
else:
st.write("No sessions found.")
with tab3:
st.header("Ticket")
st.write("Submit a ticket to report an issue or provide feedback.")
# Ticket submission form
ticket_text = st.text_area("Describe the issue or feedback:")
if st.button("Submit Ticket"):
if ticket_text.strip():
save_ticket(st.session_state.user_id, st.session_state.username, st.session_state.full_name, ticket_text)
st.success("Ticket submitted successfully!")
else:
st.error("Please enter a description for the ticket.")
# Display all tickets
st.write("### All Tickets")
tickets = fetch_tickets()
if tickets:
for ticket in tickets:
st.write(f"**Ticket ID:** {ticket[0]}")
st.write(f"**Submitted by:** {ticket[3]} (Username: {ticket[2]}, User ID: {ticket[1]})")
st.write(f"**Timestamp:** {ticket[5]}")
st.write(f"**Description:** {ticket[4]}")
st.write("---")
else:
st.write("No tickets found.")
# AI Tool 2: Maintenance Forecaster
def maintenance_forecaster():
st.title("Predictive Maintenance System")
# Load the pre-trained model and data
model_path = 'maintenance_model.pkl'
model = joblib.load(model_path)
merged_data_path = 'maintenance_merged_data.csv'
merged_data = pd.read_csv(merged_data_path)
# Preprocess the merged dataset
merged_data = merged_data.drop(columns=['Log_ID', 'Technician_ID', 'Latitude', 'Longitude'])
type_mapping = {'Government Office': 1, 'Health Center': 2, 'School': 3}
merged_data['Type'] = merged_data['Type'].map(type_mapping)
connectivity_mapping = {'Connected': 1, 'Unconnected': 2}
merged_data['Connectivity_Status'] = merged_data['Connectivity_Status'].map(connectivity_mapping)
infrastructure_mapping = {'Yes': 1, 'No': 2}
merged_data['Existing_Infrastructure'] = merged_data['Existing_Infrastructure'].map(infrastructure_mapping)
merged_data['Node_ID'] = merged_data['Node_ID'].str.extract('(\d+)').astype(int)
merged_data = pd.get_dummies(merged_data, columns=['Region'], drop_first=True)
training_columns = merged_data.drop(columns=['Issue_Type']).columns
# Function to predict issue occurrence
def predict_issue_occurrence(input_data):
prediction = model.predict(input_data)
return prediction[0]
# Function to get Gemini AI insights
def get_gemini_insights(user_input, prediction):
input_text = f"""
User Input:
{user_input}
Predicted Issue Type:
{prediction}
Analyze the above data and provide insights, suggestions, and notes for predictive maintenance.
Format your response in the following structure:
- **Insights**: List key observations from the data in short, concise bullet points.
- **Suggestions**: Provide actionable suggestions in short, concise bullet points.
- **Notes**: Add any additional notes or considerations in short, concise bullet points.
"""
response = client.chat.completions.create(
model="gemini-1.5-flash",
n=1,
messages=[
{"role": "system", "content": "You are a predictive maintenance expert. Your task is to provide concise, actionable insights and recommendations in a structured format."},
{"role": "user", "content": input_text}
]
)
return response.choices[0].message.content
# Function to save session data
def save_session(user_id, input_data, prediction, insights):
conn = sqlite3.connect("app.db")
c = conn.cursor()
c.execute('''INSERT INTO sessions2 (user_id, input_data, prediction, insights, timestamp)
VALUES (?, ?, ?, ?, ?)''',
(user_id, str(input_data), str(prediction), insights, datetime.now()))
conn.commit()
conn.close()
# Function to fetch session data
def fetch_sessions(user_id):
conn = sqlite3.connect("app.db")
c = conn.cursor()
c.execute('''SELECT * FROM sessions2 WHERE user_id = ?''', (user_id,))
sessions = c.fetchall()
conn.close()
return sessions
# Function to save a ticket
def save_ticket(user_id, username, full_name, ticket_text):
conn = sqlite3.connect("app.db")
c = conn.cursor()
c.execute('''INSERT INTO tickets2 (user_id, username, full_name, ticket_text, timestamp)
VALUES (?, ?, ?, ?, ?)''',
(user_id, username, full_name, ticket_text, datetime.now()))
conn.commit()
conn.close()
# Function to fetch all tickets
def fetch_tickets():
conn = sqlite3.connect("app.db")
c = conn.cursor()
c.execute('''SELECT * FROM tickets2 ORDER BY timestamp DESC''')
tickets = c.fetchall()
conn.close()
return tickets
# Tabs for AI Tool, Session, and Ticket
tab1, tab2, tab3 = st.tabs(["AI Tool", "Session", "Ticket"])
with tab1:
st.header("AI Tool")
st.write("Please enter the following details:")
# Input fields
node_id = st.text_input("Node ID (e.g., Node_1, Node_2, etc.):")
type_options = {"Government Office": 1, "Health Center": 2, "School": 3, "Other": 4}
type_input = st.selectbox("Type", list(type_options.keys()))
if type_input == "Other":
type_input = st.text_input("Enter the Type manually:")
type_value = 4 # Assign a unique value for "Other"
else:
type_value = type_options[type_input]
region = st.text_input("Region:").lower()
population_served = st.number_input("Population Served:", min_value=0)
connectivity_status = st.selectbox("Connectivity Status", ["Connected", "Unconnected"])
existing_infrastructure = st.selectbox("Existing Infrastructure", ["Yes", "No"])
resolution_time_hours = st.number_input("Resolution Time (Hours):", min_value=0.0)
if st.button("Predict"):
# Preprocess input data
input_data = pd.DataFrame({
'Node_ID': [int(node_id.split('_')[1])],
'Type': [type_value],
'Region': [region],
'Population_Served': [population_served],
'Connectivity_Status': [1 if connectivity_status == "Connected" else 2],
'Existing_Infrastructure': [1 if existing_infrastructure == "Yes" else 2],
'Resolution_Time_Hours': [resolution_time_hours]
})
input_data = pd.get_dummies(input_data, columns=['Region'], drop_first=True)
input_data = input_data.reindex(columns=training_columns, fill_value=0)
# Predict
prediction = predict_issue_occurrence(input_data)
st.write(f"Predicted Issue Type: {prediction}")
# Get Gemini insights
user_input = {
'Node_ID': node_id,
'Type': type_input,
'Region': region,
'Population_Served': population_served,
'Connectivity_Status': connectivity_status,
'Existing_Infrastructure': existing_infrastructure,
'Resolution_Time_Hours': resolution_time_hours
}
insights = get_gemini_insights(user_input, prediction)
st.write("Gemini AI Insights and Recommendations:")