File size: 53,071 Bytes
6947cdd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c721dce
 
 
 
 
 
 
 
 
 
 
 
 
6947cdd
c721dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6947cdd
 
 
 
 
 
 
c721dce
 
 
6947cdd
c721dce
 
 
6947cdd
c721dce
 
 
 
 
 
 
 
6947cdd
 
c721dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6947cdd
c721dce
6947cdd
 
 
c721dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f24cec
c721dce
 
 
 
 
 
6f24cec
c721dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f24cec
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
# import streamlit as st
# import requests
# import json
# import pandas as pd
# import pydeck as pdk
# from transformers import pipeline
# from datetime import datetime
# import os
# import time

# # Configure page
# st.set_page_config(
#     page_title="DisasterRelief AI Hub",
#     page_icon="πŸ†˜",
#     layout="wide",
#     initial_sidebar_state="expanded"
# )

# # Initialize session state
# if 'reports' not in st.session_state:
#     st.session_state.reports = []
# if 'relief_centers' not in st.session_state:
#     st.session_state.relief_centers = []

# # Load or initialize data files
# @st.cache_data
# def load_emergency_contacts():
#     """Load emergency contacts from JSON file or create default"""
#     default_contacts = {
#         "emergency_services": [
#             {"name": "Police Emergency", "number": "15", "description": "Police emergency hotline"},
#             {"name": "Fire Brigade", "number": "16", "description": "Fire emergency services"},
#             {"name": "Medical Emergency", "number": "1122", "description": "Emergency medical services"},
#             {"name": "Rescue 1122", "number": "1122", "description": "Emergency rescue services"}
#         ],
#         "disaster_helplines": [
#             {"name": "NDMA Helpline", "number": "051-9205086", "description": "National Disaster Management Authority"},
#             {"name": "PDMA Punjab", "number": "042-99203081", "description": "Provincial Disaster Management Authority"},
#             {"name": "Red Crescent", "number": "051-9250404", "description": "Pakistan Red Crescent Society"}
#         ],
#         "safety_guidelines": [
#             "Keep emergency numbers saved in your phone",
#             "Have a family emergency plan ready",
#             "Keep emergency supplies (water, food, flashlight, first aid kit)",
#             "Stay informed through official channels",
#             "Follow evacuation orders immediately when issued"
#         ]
#     }
#     return default_contacts

# def save_reports():
#     """Save reports to session state"""
#     # In a real deployment, you'd save to a persistent database
#     pass

# def load_reports():
#     """Load existing reports"""
#     return st.session_state.reports

# # Initialize AI models
# @st.cache_resource
# def load_summarizer():
#     """Load the summarization model"""
#     try:
#         return pipeline("summarization", model="facebook/bart-large-cnn", max_length=150, min_length=30)
#     except Exception as e:
#         st.error(f"Error loading summarizer: {e}")
#         return None

# @st.cache_resource
# def load_qa_model():
#     """Load the Q&A model"""
#     try:
#         return pipeline("question-answering", model="deepset/roberta-base-squad2")
#     except Exception as e:
#         st.error(f"Error loading Q&A model: {e}")
#         return None

# # Geocoding functions
# def geocode_location(location_name):
#     """Get coordinates for a location using Nominatim API"""
#     try:
#         url = f"https://nominatim.openstreetmap.org/search"
#         params = {
#             'q': location_name,
#             'format': 'json',
#             'limit': 1
#         }
#         headers = {'User-Agent': 'DisasterReliefApp/1.0'}
        
#         response = requests.get(url, params=params, headers=headers, timeout=5)
#         data = response.json()
        
#         if data:
#             return float(data[0]['lat']), float(data[0]['lon'])
#         return None, None
#     except Exception as e:
#         st.error(f"Geocoding error: {e}")
#         return None, None

# def find_nearby_places(lat, lon, place_type="hospital"):
#     """Find nearby places using Overpass API"""
#     try:
#         overpass_url = "http://overpass-api.de/api/interpreter"
        
#         # Define search tags based on place type
#         if place_type == "hospital":
#             amenity_tag = "hospital"
#         elif place_type == "shelter":
#             amenity_tag = "social_facility"
#         elif place_type == "food_bank":
#             amenity_tag = "food_bank"
#         else:
#             amenity_tag = "hospital"
        
#         # Overpass query to find nearby places
#         overpass_query = f"""
#         [out:json][timeout:25];
#         (
#           node["amenity"="{amenity_tag}"](around:5000,{lat},{lon});
#           way["amenity"="{amenity_tag}"](around:5000,{lat},{lon});
#           relation["amenity"="{amenity_tag}"](around:5000,{lat},{lon});
#         );
#         out center meta;
#         """
        
#         response = requests.get(overpass_url, params={'data': overpass_query}, timeout=10)
#         data = response.json()
        
#         places = []
#         for element in data.get('elements', [])[:10]:  # Limit to 10 results
#             name = element.get('tags', {}).get('name', f'Unnamed {place_type}')
#             if element['type'] == 'node':
#                 place_lat, place_lon = element['lat'], element['lon']
#             else:
#                 place_lat, place_lon = element.get('center', {}).get('lat'), element.get('center', {}).get('lon')
            
#             if place_lat and place_lon:
#                 places.append({
#                     'name': name,
#                     'lat': place_lat,
#                     'lon': place_lon,
#                     'type': place_type
#                 })
        
#         return places
#     except Exception as e:
#         st.error(f"Error finding nearby places: {e}")
#         return []

# # Chatbot function
# def simple_chatbot(question):
#     """Simple rule-based chatbot for common queries"""
#     question_lower = question.lower()
    
#     # Common emergency queries
#     if any(word in question_lower for word in ['emergency', 'help', 'urgent']):
#         return "🚨 For immediate emergencies, call:\nβ€’ Police: 15\nβ€’ Medical Emergency: 1122\nβ€’ Fire: 16"
    
#     elif any(word in question_lower for word in ['hospital', 'medical', 'doctor']):
#         return "πŸ₯ To find nearby hospitals:\n1. Use the 'Relief Centers' tab\n2. Enter your location\n3. Select 'Hospital' from the dropdown\n\nFor medical emergencies, call 1122 immediately."
    
#     elif any(word in question_lower for word in ['shelter', 'evacuate', 'safe place']):
#         return "🏠 To find emergency shelters:\n1. Go to 'Relief Centers' tab\n2. Enter your location\n3. Select 'Shelter' option\n\nIn case of evacuation orders, follow official instructions immediately."
    
#     elif any(word in question_lower for word in ['food', 'hunger', 'supplies']):
#         return "🍽️ For food assistance:\n1. Check 'Relief Centers' for food banks\n2. Contact local NGOs listed in Emergency Contacts\n3. Call Red Crescent: 051-9250404"
    
#     elif any(word in question_lower for word in ['report', 'incident', 'missing']):
#         return "πŸ“ To report incidents:\n1. Go to 'Report Incident' tab\n2. Fill out the form with details\n3. Submit your report\n\nFor missing persons, also contact local police: 15"
    
#     elif any(word in question_lower for word in ['contact', 'number', 'helpline']):
#         return "πŸ“ž Key emergency contacts:\nβ€’ Police: 15\nβ€’ Medical: 1122\nβ€’ NDMA: 051-9205086\nβ€’ Red Crescent: 051-9250404\n\nCheck 'Emergency Contacts' tab for complete list."
    
#     else:
#         return "πŸ€– I can help you with:\nβ€’ Finding nearby relief centers\nβ€’ Emergency contact numbers\nβ€’ Reporting incidents\nβ€’ Safety guidelines\n\nPlease ask specific questions about these topics or call 1122 for emergencies."

# # Main app layout
# def main():
#     # Header
#     st.title("πŸ†˜ DisasterRelief AI Hub")
#     st.markdown("### Community-driven disaster assistance platform")
    
#     # Sidebar
#     st.sidebar.title("Navigation")
#     tab_selection = st.sidebar.selectbox(
#         "Choose a service:",
#         ["πŸ₯ Relief Centers", "πŸ“ Report Incident", "πŸ“ž Emergency Contacts", "πŸ“„ AI Alert Summarizer", "πŸ€– AI Assistant"]
#     )
    
#     # Main content based on tab selection
#     if tab_selection == "πŸ₯ Relief Centers":
#         relief_centers_tab()
#     elif tab_selection == "πŸ“ Report Incident":
#         report_incident_tab()
#     elif tab_selection == "πŸ“ž Emergency Contacts":
#         emergency_contacts_tab()
#     elif tab_selection == "πŸ“„ AI Alert Summarizer":
#         ai_summarizer_tab()
#     elif tab_selection == "πŸ€– AI Assistant":
#         ai_assistant_tab()

# def relief_centers_tab():
#     st.header("πŸ₯ Find Nearby Relief Centers")
    
#     col1, col2 = st.columns([2, 1])
    
#     with col1:
#         location_input = st.text_input("Enter your location (city, area, or address):", placeholder="e.g., Lahore, Karachi, Islamabad")
    
#     with col2:
#         place_type = st.selectbox("Type of facility:", ["hospital", "shelter", "food_bank"])
    
#     search_button = st.button("πŸ” Search Relief Centers", type="primary")
    
#     if search_button and location_input:
#         with st.spinner("Searching for relief centers..."):
#             # Geocode the location
#             lat, lon = geocode_location(location_input)
            
#             if lat and lon:
#                 # Find nearby places
#                 places = find_nearby_places(lat, lon, place_type)
                
#                 if places:
#                     st.success(f"Found {len(places)} {place_type}(s) near {location_input}")
                    
#                     # Create map data
#                     map_data = pd.DataFrame(places)
#                     map_data['lat'] = map_data['lat'].astype(float)
#                     map_data['lon'] = map_data['lon'].astype(float)
                    
#                     # Display map
#                     st.subheader("πŸ“ Map View")
                    
#                     view_state = pdk.ViewState(
#                         latitude=lat,
#                         longitude=lon,
#                         zoom=12,
#                         pitch=0
#                     )
                    
#                     layer = pdk.Layer(
#                         'ScatterplotLayer',
#                         data=map_data,
#                         get_position='[lon, lat]',
#                         get_color='[255, 0, 0, 160]',
#                         get_radius=200,
#                         pickable=True
#                     )
                    
#                     st.pydeck_chart(pdk.Deck(
#                         map_style='mapbox://styles/mapbox/light-v9',
#                         initial_view_state=view_state,
#                         layers=[layer],
#                         tooltip={"text": "{name}\nType: {type}"}
#                     ))
                    
#                     # Display list
#                     st.subheader("πŸ“‹ Relief Centers List")
#                     for i, place in enumerate(places, 1):
#                         with st.expander(f"{i}. {place['name']}"):
#                             st.write(f"**Type:** {place['type'].replace('_', ' ').title()}")
#                             st.write(f"**Coordinates:** {place['lat']:.6f}, {place['lon']:.6f}")
#                             st.write(f"**Google Maps:** [Open in Maps](https://www.google.com/maps/search/?api=1&query={place['lat']},{place['lon']})")
                
#                 else:
#                     st.warning(f"No {place_type}s found near {location_input}. Try a different location or facility type.")
            
#             else:
#                 st.error("Could not find the specified location. Please check the spelling and try again.")
    
#     elif search_button:
#         st.warning("Please enter a location to search.")

# def report_incident_tab():
#     st.header("πŸ“ Report Community Incident")
    
#     with st.form("incident_report_form"):
#         col1, col2 = st.columns(2)
        
#         with col1:
#             incident_type = st.selectbox(
#                 "Incident Type:",
#                 ["Road Block", "Missing Person", "Medical Help Needed", "Fire Emergency", "Flood", "Other Emergency"]
#             )
            
#             location = st.text_input("Location:", placeholder="Specific address or landmark")
        
#         with col2:
#             reporter_name = st.text_input("Your Name (Optional):", placeholder="Anonymous")
#             contact_info = st.text_input("Contact Info (Optional):", placeholder="Phone number or email")
        
#         description = st.text_area("Description:", placeholder="Provide detailed information about the incident...")
        
#         submit_button = st.form_submit_button("πŸ“€ Submit Report", type="primary")
        
#         if submit_button:
#             if incident_type and location and description:
#                 # Create report
#                 report = {
#                     "id": len(st.session_state.reports) + 1,
#                     "type": incident_type,
#                     "location": location,
#                     "description": description,
#                     "reporter": reporter_name if reporter_name else "Anonymous",
#                     "contact": contact_info if contact_info else "Not provided",
#                     "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
#                     "status": "Reported"
#                 }
                
#                 st.session_state.reports.insert(0, report)  # Add to beginning
#                 save_reports()
                
#                 st.success("βœ… Report submitted successfully! Thank you for helping the community.")
                
#                 # Show emergency advice based on incident type
#                 if incident_type == "Medical Help Needed":
#                     st.info("🚨 For immediate medical emergencies, call 1122")
#                 elif incident_type == "Fire Emergency":
#                     st.info("🚨 For fire emergencies, call 16 immediately")
#                 elif incident_type == "Missing Person":
#                     st.info("🚨 Also report to local police: 15")
            
#             else:
#                 st.error("Please fill in all required fields.")
    
#     # Display recent reports
#     st.subheader("πŸ“‹ Recent Community Reports")
    
#     if st.session_state.reports:
#         for report in st.session_state.reports[:10]:  # Show last 10 reports
#             with st.expander(f"{report['type']} - {report['location']} ({report['timestamp']})"):
#                 st.write(f"**Description:** {report['description']}")
#                 st.write(f"**Reporter:** {report['reporter']}")
#                 st.write(f"**Status:** {report['status']}")
#                 if report['contact'] != "Not provided":
#                     st.write(f"**Contact:** {report['contact']}")
#     else:
#         st.info("No reports submitted yet. Be the first to help your community!")

# def emergency_contacts_tab():
#     st.header("πŸ“ž Emergency Contacts & Safety Resources")
    
#     contacts = load_emergency_contacts()
    
#     # Emergency Services
#     st.subheader("🚨 Emergency Services")
    
#     col1, col2 = st.columns(2)
    
#     with col1:
#         for contact in contacts["emergency_services"][:2]:
#             st.markdown(f"""
#             <div style="background-color: #ff4444; color: white; padding: 15px; margin: 10px 0; border-radius: 5px;">
#                 <h4 style="margin: 0; color: white;">{contact['name']}</h4>
#                 <h2 style="margin: 5px 0; color: white;">{contact['number']}</h2>
#                 <p style="margin: 0; color: white;">{contact['description']}</p>
#             </div>
#             """, unsafe_allow_html=True)
    
#     with col2:
#         for contact in contacts["emergency_services"][2:]:
#             st.markdown(f"""
#             <div style="background-color: #ff4444; color: white; padding: 15px; margin: 10px 0; border-radius: 5px;">
#                 <h4 style="margin: 0; color: white;">{contact['name']}</h4>
#                 <h2 style="margin: 5px 0; color: white;">{contact['number']}</h2>
#                 <p style="margin: 0; color: white;">{contact['description']}</p>
#             </div>
#             """, unsafe_allow_html=True)
    
#     # Disaster Helplines
#     st.subheader("🏒 Disaster Management Helplines")
    
#     for contact in contacts["disaster_helplines"]:
#         st.markdown(f"""
#         <div style="background-color: #f0f2f6; padding: 15px; margin: 10px 0; border-radius: 5px; border-left: 4px solid #1f77b4;">
#             <h4 style="margin: 0;">{contact['name']}: {contact['number']}</h4>
#             <p style="margin: 5px 0;">{contact['description']}</p>
#         </div>
#         """, unsafe_allow_html=True)
    
#     # Safety Guidelines
#     st.subheader("πŸ›‘οΈ Safety Guidelines")
    
#     for i, guideline in enumerate(contacts["safety_guidelines"], 1):
#         st.markdown(f"**{i}.** {guideline}")
    
#     # Quick Action Section
#     st.subheader("⚑ Quick Actions")
    
#     col1, col2, col3 = st.columns(3)
    
#     with col1:
#         if st.button("πŸ“ž Call Emergency (1122)", type="primary"):
#             st.info("On mobile devices, this would initiate a call to 1122")
    
#     with col2:
#         if st.button("πŸ“ Share Location"):
#             st.info("Location sharing feature would be activated")
    
#     with col3:
#         if st.button("🚨 Send Alert"):
#             st.info("Emergency alert would be sent to registered contacts")

# def ai_summarizer_tab():
#     st.header("πŸ“„ AI Alert Summarizer")
#     st.markdown("Paste long official disaster alerts below to get a concise AI-powered summary.")
    
#     # Text input
#     alert_text = st.text_area(
#         "Official Alert Text:",
#         placeholder="Paste the long official disaster alert here...",
#         height=200
#     )
    
#     col1, col2 = st.columns([1, 3])
    
#     with col1:
#         summarize_button = st.button("πŸ€– Summarize Alert", type="primary", disabled=not alert_text)
    
#     if summarize_button and alert_text:
#         with st.spinner("Analyzing and summarizing the alert..."):
#             summarizer = load_summarizer()
            
#             if summarizer:
#                 try:
#                     # Ensure text is not too long for the model
#                     max_input_length = 1000  # Adjust based on model limits
#                     if len(alert_text) > max_input_length:
#                         alert_text = alert_text[:max_input_length] + "..."
                    
#                     # Generate summary
#                     summary_result = summarizer(alert_text, max_length=150, min_length=30, do_sample=False)
#                     summary = summary_result[0]['summary_text']
                    
#                     # Display results
#                     st.subheader("πŸ“‹ Summary")
#                     st.success("βœ… Alert summarized successfully!")
                    
#                     # Format as bullet points
#                     sentences = summary.split('. ')
#                     st.markdown("**Key Points:**")
#                     for i, sentence in enumerate(sentences, 1):
#                         if sentence.strip():
#                             sentence = sentence.strip()
#                             if not sentence.endswith('.'):
#                                 sentence += '.'
#                             st.markdown(f"β€’ {sentence}")
                    
#                     # Additional analysis
#                     st.subheader("πŸ“Š Alert Analysis")
                    
#                     col1, col2, col3 = st.columns(3)
                    
#                     with col1:
#                         st.metric("Original Length", f"{len(alert_text)} chars")
                    
#                     with col2:
#                         st.metric("Summary Length", f"{len(summary)} chars")
                    
#                     with col3:
#                         compression_ratio = round((1 - len(summary)/len(alert_text)) * 100, 1)
#                         st.metric("Compression", f"{compression_ratio}%")
                    
#                     # Extract urgency level (simple keyword analysis)
#                     urgency_keywords = {
#                         'high': ['immediate', 'urgent', 'emergency', 'critical', 'evacuate', 'danger'],
#                         'medium': ['warning', 'alert', 'caution', 'prepare', 'monitor'],
#                         'low': ['advisory', 'information', 'update', 'notice']
#                     }
                    
#                     text_lower = alert_text.lower()
#                     urgency_score = {'high': 0, 'medium': 0, 'low': 0}
                    
#                     for level, keywords in urgency_keywords.items():
#                         urgency_score[level] = sum(1 for keyword in keywords if keyword in text_lower)
                    
#                     urgency_level = max(urgency_score, key=urgency_score.get)
#                     urgency_colors = {'high': 'πŸ”΄', 'medium': '🟑', 'low': '🟒'}
                    
#                     st.markdown(f"**Urgency Level:** {urgency_colors[urgency_level]} {urgency_level.upper()}")
                
#                 except Exception as e:
#                     st.error(f"Error generating summary: {e}")
#                     st.info("Tip: Try with a shorter text or check your internet connection.")
            
#             else:
#                 st.error("AI summarizer is not available. Please try again later.")
    
#     # Example alerts
#     st.subheader("πŸ’‘ Example Usage")
    
#     example_alert = """
#     URGENT FLOOD WARNING - DISTRICT LAHORE
    
#     The Meteorological Department has issued a severe flood warning for Lahore district effective immediately. Heavy monsoon rains of 150-200mm are expected in the next 24 hours. The Ravi River water level has risen to dangerous levels. Citizens living in low-lying areas including Shahdara, Kot Lakhpat, and areas near Ravi River are advised to evacuate immediately. Emergency shelters have been established at Government Schools in each tehsil. All citizens are advised to avoid unnecessary travel and stay indoors. Emergency services are on high alert. For assistance, contact District Emergency Operations Center at 042-99200100. This is a developing situation and updates will be provided regularly through official channels.
#     """
    
#     if st.button("Try Example Alert"):
#         st.text_area("Example Alert:", value=example_alert, height=150, key="example")

# def ai_assistant_tab():
#     st.header("πŸ€– AI Assistant")
#     st.markdown("Ask me questions about emergency services, relief centers, or safety guidelines!")
    
#     # Chat interface
#     if 'chat_history' not in st.session_state:
#         st.session_state.chat_history = []
    
#     # Display chat history
#     chat_container = st.container()
    
#     with chat_container:
#         for i, (question, answer) in enumerate(st.session_state.chat_history):
#             # User message
#             st.markdown(f"""
#             <div style="background-color: #e6f3ff; padding: 10px; margin: 10px 0; border-radius: 10px; border-left: 4px solid #0066cc;">
#                 <strong>You:</strong> {question}
#             </div>
#             """, unsafe_allow_html=True)
            
#             # AI response
#             st.markdown(f"""
#             <div style="background-color: #f0f8f0; padding: 10px; margin: 10px 0; border-radius: 10px; border-left: 4px solid #009900;">
#                 <strong>AI Assistant:</strong><br>{answer}
#             </div>
#             """, unsafe_allow_html=True)
    
#     # Input form
#     with st.form("chat_form", clear_on_submit=True):
#         user_question = st.text_input(
#             "Ask a question:",
#             placeholder="e.g., Where is the nearest hospital in Karachi?"
#         )
        
#         col1, col2 = st.columns([1, 5])
        
#         with col1:
#             ask_button = st.form_submit_button("Ask", type="primary")
        
#         with col2:
#             if st.form_submit_button("Clear Chat"):
#                 st.session_state.chat_history = []
#                 st.rerun()
    
#     if ask_button and user_question:
#         with st.spinner("Thinking..."):
#             # Get AI response
#             ai_response = simple_chatbot(user_question)
            
#             # Add to chat history
#             st.session_state.chat_history.append((user_question, ai_response))
            
#             # Limit chat history to last 10 exchanges
#             if len(st.session_state.chat_history) > 10:
#                 st.session_state.chat_history = st.session_state.chat_history[-10:]
            
#             st.rerun()
    
#     # Quick question buttons
#     st.subheader("πŸ”— Common Questions")
    
#     col1, col2 = st.columns(2)
    
#     with col1:
#         if st.button("πŸ₯ Find nearest hospital"):
#             st.session_state.chat_history.append(
#                 ("Find nearest hospital", simple_chatbot("Find nearest hospital"))
#             )
#             st.rerun()
        
#         if st.button("πŸ“ž Emergency numbers"):
#             st.session_state.chat_history.append(
#                 ("Emergency numbers", simple_chatbot("Emergency numbers"))
#             )
#             st.rerun()
    
#     with col2:
#         if st.button("🏠 Find shelter"):
#             st.session_state.chat_history.append(
#                 ("Find shelter", simple_chatbot("Find shelter"))
#             )
#             st.rerun()
        
#         if st.button("πŸ“ How to report incident"):
#             st.session_state.chat_history.append(
#                 ("How to report incident", simple_chatbot("How to report incident"))
#             )
#             st.rerun()

# # Footer
# def show_footer():
#     st.markdown("---")
#     st.markdown("""
#     <div style="text-align: center; color: #666; padding: 20px;">
#         <p>πŸ†˜ <strong>DisasterRelief AI Hub</strong> - Helping communities in times of need</p>
#         <p>For immediate emergencies, always call official emergency services: Police (15), Medical (1122), Fire (16)</p>
#         <p>Built with ❀️ using Streamlit and Hugging Face AI</p>
#     </div>
#     """, unsafe_allow_html=True)

# if __name__ == "__main__":
#     main()
#     show_footer()



import streamlit as st
import requests
import json
import pandas as pd
import pydeck as pdk
from transformers import pipeline
from datetime import datetime
import os
import time

# Configure page
st.set_page_config(
    page_title="DisasterRelief AI Hub",
    page_icon="οΏ½",
    layout="wide",
    initial_sidebar_state="expanded"
)

# Initialize session state
if 'reports' not in st.session_state:
    st.session_state.reports = []
if 'relief_centers' not in st.session_state:
    st.session_state.relief_centers = []

# Load or initialize data files
@st.cache_data
def load_emergency_contacts():
    """Load emergency contacts from JSON file or create default"""
    default_contacts = {
        "emergency_services": [
            {"name": "Police Emergency", "number": "15", "description": "Police emergency hotline"},
            {"name": "Fire Brigade", "number": "16", "description": "Fire emergency services"},
            {"name": "Medical Emergency", "number": "1122", "description": "Emergency medical services"},
            {"name": "Rescue 1122", "number": "1122", "description": "Emergency rescue services"}
        ],
        "disaster_helplines": [
            {"name": "NDMA Helpline", "number": "051-9205086", "description": "National Disaster Management Authority"},
            {"name": "PDMA Punjab", "number": "042-99203081", "description": "Provincial Disaster Management Authority"},
            {"name": "Red Crescent", "number": "051-9250404", "description": "Pakistan Red Crescent Society"}
        ],
        "safety_guidelines": [
            "Keep emergency numbers saved in your phone",
            "Have a family emergency plan ready",
            "Keep emergency supplies (water, food, flashlight, first aid kit)",
            "Stay informed through official channels",
            "Follow evacuation orders immediately when issued"
        ]
    }
    return default_contacts

def save_reports():
    """Save reports to session state"""
    # In a real deployment, you'd save to a persistent database
    pass

def load_reports():
    """Load existing reports"""
    return st.session_state.reports

# Initialize AI models
@st.cache_resource
def load_summarizer():
    """Load the summarization model"""
    try:
        return pipeline("summarization", model="facebook/bart-large-cnn", max_length=150, min_length=30)
    except Exception as e:
        st.error(f"Error loading summarizer: {e}")
        return None

@st.cache_resource
def load_qa_model():
    """Load the Q&A model"""
    try:
        return pipeline("question-answering", model="deepset/roberta-base-squad2")
    except Exception as e:
        st.error(f"Error loading Q&A model: {e}")
        return None

# Geocoding functions
def geocode_location(location_name):
    """Get coordinates for a location using Nominatim API"""
    try:
        url = f"https://nominatim.openstreetmap.org/search"
        params = {
            'q': location_name,
            'format': 'json',
            'limit': 1
        }
        headers = {'User-Agent': 'DisasterReliefApp/1.0'}
        
        response = requests.get(url, params=params, headers=headers, timeout=5)
        data = response.json()
        
        if data:
            return float(data[0]['lat']), float(data[0]['lon'])
        return None, None
    except Exception as e:
        st.error(f"Geocoding error: {e}")
        return None, None

def find_nearby_places(lat, lon, place_type="hospital"):
    """Find nearby places using Overpass API"""
    try:
        overpass_url = "http://overpass-api.de/api/interpreter"
        
        # Define search tags based on place type
        if place_type == "hospital":
            amenity_tag = "hospital"
        elif place_type == "shelter":
            # Note: Overpass API typically uses 'social_facility' with 'shelter' tag or similar
            # For broader search, 'social_facility' might be used, or 'emergency' facility.
            # Let's keep it simple for now based on the original.
            amenity_tag = "shelter" 
            # If 'shelter' doesn't yield results, consider 'social_facility' or 'bunker'
            # Or a more complex query like: 
            # (node["amenity"="social_facility"]["social_facility"="homeless_shelter"](around:5000,{lat},{lon});)
        elif place_type == "food_bank":
            amenity_tag = "food_bank"
        else:
            amenity_tag = "hospital" # Default to hospital if unknown type
        
        # Overpass query to find nearby places
        overpass_query = f"""
        [out:json][timeout:30]; /* Increased timeout to 30 seconds */
        (
          node["amenity"="{amenity_tag}"](around:5000,{lat},{lon});
          way["amenity"="{amenity_tag}"](around:5000,{lat},{lon});
          relation["amenity"="{amenity_tag}"](around:5000,{lat},{lon});
        );
        out center meta;
        """
        
        # Increased timeout to 30 seconds
        response = requests.get(overpass_url, params={'data': overpass_query}, timeout=30) 
        data = response.json()
        
        places = []
        for element in data.get('elements', [])[:10]:  # Limit to 10 results
            name = element.get('tags', {}).get('name', f'Unnamed {place_type}')
            if element['type'] == 'node':
                place_lat, place_lon = element['lat'], element['lon']
            else:
                place_lat, place_lon = element.get('center', {}).get('lat'), element.get('center', {}).get('lon')
            
            if place_lat and place_lon:
                places.append({
                    'name': name,
                    'lat': place_lat,
                    'lon': place_lon,
                    'type': place_type
                })
        
        return places
    except Exception as e:
        st.error(f"Error finding nearby places: {e}")
        return []

# Chatbot function
def simple_chatbot(question):
    """Simple rule-based chatbot for common queries"""
    question_lower = question.lower()
    
    # Common emergency queries
    if any(word in question_lower for word in ['emergency', 'help', 'urgent']):
        return "🚨 For immediate emergencies, call:\nβ€’ Police: 15\nβ€’ Medical Emergency: 1122\nβ€’ Fire: 16"
    
    elif any(word in question_lower for word in ['hospital', 'medical', 'doctor']):
        return "πŸ₯ To find nearby hospitals:\n1. Use the 'Relief Centers' tab\n2. Enter your location\n3. Select 'Hospital' from the dropdown\n\nFor medical emergencies, call 1122 immediately."
    
    elif any(word in question_lower for word in ['shelter', 'evacuate', 'safe place']):
        return "🏠 To find emergency shelters:\n1. Go to 'Relief Centers' tab\n2. Enter your location\n3. Select 'Shelter' option\n\nIn case of evacuation orders, follow official instructions immediately."
    
    elif any(word in question_lower for word in ['food', 'hunger', 'supplies']):
        return "🍽️ For food assistance:\n1. Check 'Relief Centers' for food banks\n2. Contact local NGOs listed in Emergency Contacts\n3. Call Red Crescent: 051-9250404"
    
    elif any(word in question_lower for word in ['report', 'incident', 'missing']):
        return "πŸ“ To report incidents:\n1. Go to 'Report Incident' tab\n2. Fill out the form with details\n3. Submit your report\n\nFor missing persons, also contact local police: 15"
    
    elif any(word in question_lower for word in ['contact', 'number', 'helpline']):
        return "πŸ“ž Key emergency contacts:\nβ€’ Police: 15\nβ€’ Medical: 1122\nβ€’ NDMA: 051-9205086\nβ€’ Red Crescent: 051-9250404\n\nCheck 'Emergency Contacts' tab for complete list."
    
    else:
        return "πŸ€– I can help you with:\nβ€’ Finding nearby relief centers\nβ€’ Emergency contact numbers\nβ€’ Reporting incidents\nβ€’ Safety guidelines\n\nPlease ask specific questions about these topics or call 1122 for emergencies."

# Main app layout
def main():
    # Header
    st.title("πŸ†˜ DisasterRelief AI Hub")
    st.markdown("### Community-driven disaster assistance platform")
    
    # Sidebar
    st.sidebar.title("Navigation")
    tab_selection = st.sidebar.selectbox(
        "Choose a service:",
        ["πŸ₯ Relief Centers", "πŸ“ Report Incident", "πŸ“ž Emergency Contacts", "πŸ“„ AI Alert Summarizer", "πŸ€– AI Assistant"]
    )
    
    # Main content based on tab selection
    if tab_selection == "πŸ₯ Relief Centers":
        relief_centers_tab()
    elif tab_selection == "πŸ“ Report Incident":
        report_incident_tab()
    elif tab_selection == "πŸ“ž Emergency Contacts":
        emergency_contacts_tab()
    elif tab_selection == "πŸ“„ AI Alert Summarizer":
        ai_summarizer_tab()
    elif tab_selection == "πŸ€– AI Assistant":
        ai_assistant_tab()

def relief_centers_tab():
    st.header("πŸ₯ Find Nearby Relief Centers")
    
    col1, col2 = st.columns([2, 1])
    
    with col1:
        location_input = st.text_input("Enter your location (city, area, or address):", placeholder="e.g., Lahore, Karachi, Islamabad")
    
    with col2:
        place_type = st.selectbox("Type of facility:", ["hospital", "shelter", "food_bank"])
    
    search_button = st.button("πŸ” Search Relief Centers", type="primary")
    
    if search_button and location_input:
        with st.spinner("Searching for relief centers..."):
            # Geocode the location
            lat, lon = geocode_location(location_input)
            
            if lat and lon:
                # Find nearby places
                places = find_nearby_places(lat, lon, place_type)
                
                if places:
                    st.success(f"Found {len(places)} {place_type}(s) near {location_input}")
                    
                    # Create map data
                    map_data = pd.DataFrame(places)
                    map_data['lat'] = map_data['lat'].astype(float)
                    map_data['lon'] = map_data['lon'].astype(float)
                    
                    # Display map
                    st.subheader("πŸ“ Map View")
                    
                    view_state = pdk.ViewState(
                        latitude=lat,
                        longitude=lon,
                        zoom=12,
                        pitch=0
                    )
                    
                    layer = pdk.Layer(
                        'ScatterplotLayer',
                        data=map_data,
                        get_position='[lon, lat]',
                        get_color='[255, 0, 0, 160]',
                        get_radius=200,
                        pickable=True
                    )
                    
                    st.pydeck_chart(pdk.Deck(
                        map_style='mapbox://styles/mapbox/light-v9',
                        initial_view_state=view_state,
                        layers=[layer],
                        tooltip={"text": "{name}\nType: {type}"}
                    ))
                    
                    # Display list
                    st.subheader("πŸ“‹ Relief Centers List")
                    for i, place in enumerate(places, 1):
                        with st.expander(f"{i}. {place['name']}"):
                            st.write(f"**Type:** {place['type'].replace('_', ' ').title()}")
                            st.write(f"**Coordinates:** {place['lat']:.6f}, {place['lon']:.6f}")
                            st.write(f"**Google Maps:** [Open in Maps](https://www.google.com/maps/search/?api=1&query={place['lat']},{place['lon']})")
                
                else:
                    st.warning(f"No {place_type}s found near {location_input}. Try a different location or facility type.")
            
            else:
                st.error("Could not find the specified location. Please check the spelling and try again.")
    
    elif search_button:
        st.warning("Please enter a location to search.")

def report_incident_tab():
    st.header("πŸ“ Report Community Incident")
    
    with st.form("incident_report_form"):
        col1, col2 = st.columns(2)
        
        with col1:
            incident_type = st.selectbox(
                "Incident Type:",
                ["Road Block", "Missing Person", "Medical Help Needed", "Fire Emergency", "Flood", "Other Emergency"]
            )
            
            location = st.text_input("Location:", placeholder="Specific address or landmark")
        
        with col2:
            reporter_name = st.text_input("Your Name (Optional):", placeholder="Anonymous")
            contact_info = st.text_input("Contact Info (Optional):", placeholder="Phone number or email")
        
        description = st.text_area("Description:", placeholder="Provide detailed information about the incident...")
        
        submit_button = st.form_submit_button("πŸ“€ Submit Report", type="primary")
        
        if submit_button:
            if incident_type and location and description:
                # Create report
                report = {
                    "id": len(st.session_state.reports) + 1,
                    "type": incident_type,
                    "location": location,
                    "description": description,
                    "reporter": reporter_name if reporter_name else "Anonymous",
                    "contact": contact_info if contact_info else "Not provided",
                    "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                    "status": "Reported"
                }
                
                st.session_state.reports.insert(0, report)  # Add to beginning
                save_reports()
                
                st.success("βœ… Report submitted successfully! Thank you for helping the community.")
                
                # Show emergency advice based on incident type
                if incident_type == "Medical Help Needed":
                    st.info("🚨 For immediate medical emergencies, call 1122")
                elif incident_type == "Fire Emergency":
                    st.info("🚨 For fire emergencies, call 16 immediately")
                elif incident_type == "Missing Person":
                    st.info("🚨 Also report to local police: 15")
            
            else:
                st.error("Please fill in all required fields.")
    
    # Display recent reports
    st.subheader("πŸ“‹ Recent Community Reports")
    
    if st.session_state.reports:
        for report in st.session_state.reports[:10]:  # Show last 10 reports
            with st.expander(f"{report['type']} - {report['location']} ({report['timestamp']})"):
                st.write(f"**Description:** {report['description']}")
                st.write(f"**Reporter:** {report['reporter']}")
                st.write(f"**Status:** {report['status']}")
                if report['contact'] != "Not provided":
                    st.write(f"**Contact:** {report['contact']}")
    else:
        st.info("No reports submitted yet. Be the first to help your community!")

def emergency_contacts_tab():
    st.header("πŸ“ž Emergency Contacts & Safety Resources")
    
    contacts = load_emergency_contacts()
    
    # Emergency Services
    st.subheader("🚨 Emergency Services")
    
    col1, col2 = st.columns(2)
    
    with col1:
        for contact in contacts["emergency_services"][:2]:
            st.markdown(f"""
            <div style="background-color: #ff4444; color: white; padding: 15px; margin: 10px 0; border-radius: 5px;">
                <h4 style="margin: 0; color: white;">{contact['name']}</h4>
                <h2 style="margin: 5px 0; color: white;">{contact['number']}</h2>
                <p style="margin: 0; color: white;">{contact['description']}</p>
            </div>
            """, unsafe_allow_html=True)
    
    with col2:
        for contact in contacts["emergency_services"][2:]:
            st.markdown(f"""
            <div style="background-color: #ff4444; color: white; padding: 15px; margin: 10px 0; border-radius: 5px;">
                <h4 style="margin: 0; color: white;">{contact['name']}</h4>
                <h2 style="margin: 5px 0; color: white;">{contact['number']}</h2>
                <p style="margin: 0; color: white;">{contact['description']}</p>
            </div>
            """, unsafe_allow_html=True)
    
    # Disaster Helplines
    st.subheader("🏒 Disaster Management Helplines")
    
    for contact in contacts["disaster_helplines"]:
        # Explicitly setting color to ensure visibility on light background
        st.markdown(f"""
        <div style="background-color: #f0f2f6; padding: 15px; margin: 10px 0; border-radius: 5px; border-left: 4px solid #1f77b4; color: #333;">
            <h4 style="margin: 0; color: #333;">{contact['name']}: {contact['number']}</h4>
            <p style="margin: 5px 0; color: #333;">{contact['description']}</p>
        </div>
        """, unsafe_allow_html=True)
    
    # Safety Guidelines
    st.subheader("πŸ›‘οΈ Safety Guidelines")
    
    for i, guideline in enumerate(contacts["safety_guidelines"], 1):
        st.markdown(f"**{i}.** {guideline}")
    
    # Quick Action Section
    st.subheader("⚑ Quick Actions")
    
    col1, col2, col3 = st.columns(3)
    
    with col1:
        if st.button("πŸ“ž Call Emergency (1122)", type="primary"):
            st.info("On mobile devices, this would initiate a call to 1122")
    
    with col2:
        if st.button("πŸ“ Share Location"):
            st.info("Location sharing feature would be activated")
    
    with col3:
        if st.button("🚨 Send Alert"):
            st.info("Emergency alert would be sent to registered contacts")

def ai_summarizer_tab():
    st.header("πŸ“„ AI Alert Summarizer")
    st.markdown("Paste long official disaster alerts below to get a concise AI-powered summary.")
    
    # Text input
    alert_text = st.text_area(
        "Official Alert Text:",
        placeholder="Paste the long official disaster alert here...",
        height=200
    )
    
    col1, col2 = st.columns([1, 3])
    
    with col1:
        summarize_button = st.button("πŸ€– Summarize Alert", type="primary", disabled=not alert_text)
    
    if summarize_button and alert_text:
        with st.spinner("Analyzing and summarizing the alert..."):
            summarizer = load_summarizer()
            
            if summarizer:
                try:
                    # Ensure text is not too long for the model
                    max_input_length = 1000  # Adjust based on model limits
                    if len(alert_text) > max_input_length:
                        alert_text = alert_text[:max_input_length] + "..."
                    
                    # Generate summary
                    summary_result = summarizer(alert_text, max_length=150, min_length=30, do_sample=False)
                    summary = summary_result[0]['summary_text']
                    
                    # Display results
                    st.subheader("πŸ“‹ Summary")
                    st.success("βœ… Alert summarized successfully!")
                    
                    # Format as bullet points
                    sentences = summary.split('. ')
                    st.markdown("**Key Points:**")
                    for i, sentence in enumerate(sentences, 1):
                        if sentence.strip():
                            sentence = sentence.strip()
                            if not sentence.endswith('.'):
                                sentence += '.'
                            st.markdown(f"β€’ {sentence}")
                    
                    # Additional analysis
                    st.subheader("πŸ“Š Alert Analysis")
                    
                    col1, col2, col3 = st.columns(3)
                    
                    with col1:
                        st.metric("Original Length", f"{len(alert_text)} chars")
                    
                    with col2:
                        st.metric("Summary Length", f"{len(summary)} chars")
                    
                    with col3:
                        compression_ratio = round((1 - len(summary)/len(alert_text)) * 100, 1)
                        st.metric("Compression", f"{compression_ratio}%")
                    
                    # Extract urgency level (simple keyword analysis)
                    urgency_keywords = {
                        'high': ['immediate', 'urgent', 'emergency', 'critical', 'evacuate', 'danger'],
                        'medium': ['warning', 'alert', 'caution', 'prepare', 'monitor'],
                        'low': ['advisory', 'information', 'update', 'notice']
                    }
                    
                    text_lower = alert_text.lower()
                    urgency_score = {'high': 0, 'medium': 0, 'low': 0}
                    
                    for level, keywords in urgency_keywords.items():
                        urgency_score[level] = sum(1 for keyword in keywords if keyword in text_lower)
                    
                    urgency_level = max(urgency_score, key=urgency_score.get)
                    urgency_colors = {'high': 'πŸ”΄', 'medium': '🟑', 'low': '🟒'}
                    
                    st.markdown(f"**Urgency Level:** {urgency_colors[urgency_level]} {urgency_level.upper()}")
                
                except Exception as e:
                    st.error(f"Error generating summary: {e}")
                    st.info("Tip: Try with a shorter text or check your internet connection.")
            
            else:
                st.error("AI summarizer is not available. Please try again later.")
    
    # Example alerts
    st.subheader("πŸ’‘ Example Usage")
    
    example_alert = """
    URGENT FLOOD WARNING - DISTRICT LAHORE
    
    The Meteorological Department has issued a severe flood warning for Lahore district effective immediately. Heavy monsoon rains of 150-200mm are expected in the next 24 hours. The Ravi River water level has risen to dangerous levels. Citizens living in low-lying areas including Shahdara, Kot Lakhpat, and areas near Ravi River are advised to evacuate immediately. Emergency shelters have been established at Government Schools in each tehsil. All citizens are advised to avoid unnecessary travel and stay indoors. Emergency services are on high alert. For assistance, contact District Emergency Operations Center at 042-99200100. This is a developing situation and updates will be provided regularly through official channels.
    """
    
    if st.button("Try Example Alert"):
        st.text_area("Example Alert:", value=example_alert, height=150, key="example")

def ai_assistant_tab():
    st.header("πŸ€– AI Assistant")
    st.markdown("Ask me questions about emergency services, relief centers, or safety guidelines!")
    
    # Chat interface
    if 'chat_history' not in st.session_state:
        st.session_state.chat_history = []
    
    # Display chat history
    chat_container = st.container()
    
    with chat_container:
        for i, (question, answer) in enumerate(st.session_state.chat_history):
            # User message
            st.markdown(f"""
            <div style="background-color: #e6f3ff; padding: 10px; margin: 10px 0; border-radius: 10px; border-left: 4px solid #0066cc; color: #333;">
                <strong>You:</strong> {question}
            </div>
            """, unsafe_allow_html=True)
            
            # AI response
            st.markdown(f"""
            <div style="background-color: #f0f8f0; padding: 10px; margin: 10px 0; border-radius: 10px; border-left: 4px solid #009900; color: #333;">
                <strong>AI Assistant:</strong><br>{answer}
            </div>
            """, unsafe_allow_html=True)
    
    # Input form
    with st.form("chat_form", clear_on_submit=True):
        user_question = st.text_input(
            "Ask a question:",
            placeholder="e.g., Where is the nearest hospital in Karachi?"
        )
        
        col1, col2 = st.columns([1, 5])
        
        with col1:
            ask_button = st.form_submit_button("Ask", type="primary")
        
        with col2:
            if st.form_submit_button("Clear Chat"):
                st.session_state.chat_history = []
                st.rerun()
    
    if ask_button and user_question:
        with st.spinner("Thinking..."):
            # Get AI response
            ai_response = simple_chatbot(user_question)
            
            # Add to chat history
            st.session_state.chat_history.append((user_question, ai_response))
            
            # Limit chat history to last 10 exchanges
            if len(st.session_state.chat_history) > 10:
                st.session_state.chat_history = st.session_state.chat_history[-10:]
            
            st.rerun()
    
    # Quick question buttons
    st.subheader("πŸ”— Common Questions")
    
    col1, col2 = st.columns(2)
    
    with col1:
        if st.button("πŸ₯ Find nearest hospital"):
            st.session_state.chat_history.append(
                ("Find nearest hospital", simple_chatbot("Find nearest hospital"))
            )
            st.rerun()
        
        if st.button("πŸ“ž Emergency numbers"):
            st.session_state.chat_history.append(
                ("Emergency numbers", simple_chatbot("Emergency numbers"))
            )
            st.rerun()
    
    with col2:
        if st.button("🏠 Find shelter"):
            st.session_state.chat_history.append(
                ("Find shelter", simple_chatbot("Find shelter"))
            )
            st.rerun()
        
        if st.button("πŸ“ How to report incident"):
            st.session_state.chat_history.append(
                ("How to report incident", simple_chatbot("How to report incident"))
            )
            st.rerun()

# Footer
def show_footer():
    st.markdown("---")
    st.markdown("""
    <div style="text-align: center; color: #666; padding: 20px;">
        <p>πŸ†˜ <strong>DisasterRelief AI Hub</strong> - Helping communities in times of need</p>
        <p>For immediate emergencies, always call official emergency services: Police (15), Medical (1122), Fire (16)</p>
        <p>Built with ❀️ using Streamlit and Hugging Face AI</p>
    </div>
    """, unsafe_allow_html=True)

if __name__ == "__main__":
    main()
    show_footer()