lalaru commited on
Commit
f5fa264
Β·
verified Β·
1 Parent(s): e31587c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +189 -278
app.py CHANGED
@@ -1,19 +1,27 @@
1
- # # app.py
 
2
  # import streamlit as st
3
  # import requests
4
  # from datetime import datetime
5
  # from deep_translator import GoogleTranslator
6
  # from geopy.geocoders import Nominatim
7
- # from streamlit_lottie import st_lottie
8
  # from timezonefinder import TimezoneFinder
9
  # import pytz
10
  # from streamlit_js_eval import get_geolocation
11
 
12
-
13
- # # Set your Groq API Key
 
14
  # GROQ_API_KEY = "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"
15
 
 
 
 
 
 
 
16
  # # Rescue numbers dictionary
 
17
  # rescue_contacts = {
18
  # "Pakistan": {
19
  # "Ambulance": "115",
@@ -35,30 +43,30 @@
35
  # }
36
  # }
37
 
38
- # def get_local_time(lat, lon):
 
 
 
39
  # tf = TimezoneFinder()
40
- # timezone_str = tf.timezone_at(lat=lat, lng=lon)
41
-
42
- # if timezone_str:
43
  # try:
44
- # tz = pytz.timezone(timezone_str)
45
- # local_dt = datetime.now(tz)
46
- # print(f"[βœ”] Detected Timezone: {timezone_str}")
47
- # return local_dt
48
- # except Exception as e:
49
- # print(f"[⚠] Error loading timezone: {e}")
50
- # else:
51
- # print("[⚠] Timezone not found. Falling back to UTC.")
52
-
53
- # # Fallback
54
- # return datetime.utcnow().replace(tzinfo=pytz.utc)
55
 
 
56
  # # Session setup
 
57
  # if "history" not in st.session_state:
58
  # st.session_state.history = []
 
 
59
 
60
- # # Page setup
61
- # st.set_page_config(page_title="AI Disaster Assistant", layout="wide")
 
62
  # st.markdown("""
63
  # <style>
64
  # body { background-color: #0d1117; color: white; }
@@ -67,16 +75,32 @@
67
  # .chat-bubble { background-color: #f0f0f0; color: #000; padding: 0.5rem; margin-bottom: 0.5rem; border-radius: 10px; }
68
  # .answer-box { background-color: #d6f5f5; padding: 1rem; border-radius: 12px; color: #000; }
69
  # .contact-box { background-color: #ffeecc; padding: 1rem; border-radius: 10px; color: #000; }
 
 
70
  # </style>
71
  # """, unsafe_allow_html=True)
72
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  # st.markdown("""
74
  # <h1 style='text-align: center; background-color: #008080; color: white; padding: 1rem; border-radius: 12px;'>
75
- # 🌍 AI Disaster Response Assistant
76
  # </h1>
77
  # """, unsafe_allow_html=True)
78
 
79
- # # 🌐 Language Selection
 
 
80
  # language_options = {
81
  # "English": "en",
82
  # "Urdu": "ur",
@@ -88,36 +112,13 @@
88
  # preferred_language = st.selectbox("🌐 Select your preferred language for responses:", list(language_options.keys()))
89
  # target_lang_code = language_options[preferred_language]
90
 
91
- # # πŸ“ Get Location
92
- # # location_data = geocoder.ip('me')
93
- # # user_location = "Unknown"
94
- # # city = ""
95
- # # country = ""
96
- # # local_time = datetime.utcnow()
97
-
98
- # # if location_data and location_data.ok:
99
- # # lat = location_data.latlng[0]
100
- # # lon = location_data.latlng[1]
101
- # # st.success(f"πŸ“ GPS Location: {lat:.4f}, {lon:.4f}")
102
- # # try:
103
- # # geolocator = Nominatim(user_agent="geoapiExercises")
104
- # # location = geolocator.reverse((lat, lon), language='en')
105
- # # city = location.raw['address'].get('city', '') or location.raw['address'].get('town', '')
106
- # # country = location.raw['address'].get('country', '')
107
- # # user_location = f"{city}, {country}"
108
- # # st.markdown(f"πŸ“Œ You are in *{user_location}*")
109
-
110
- # # local_time = get_local_time(lat, lon)
111
-
112
- # # except Exception as e:
113
- # # st.warning("🌐 Could not resolve full address or local time from GPS.")
114
-
115
  # location_data = get_geolocation()
116
-
117
  # user_location = "Unknown"
118
  # city = ""
119
  # country = ""
120
- # local_time = datetime.now()
121
 
122
  # if location_data and location_data.get("coords"):
123
  # lat = location_data["coords"]["latitude"]
@@ -130,32 +131,63 @@
130
  # country = location.raw['address'].get('country', '')
131
  # user_location = f"{city}, {country}"
132
  # st.markdown(f"πŸ“Œ You are in *{user_location}*")
 
 
 
133
 
134
- # local_time = get_local_time(lat, lon)
135
-
136
- # except Exception as e:
137
- # st.warning("🌐 Could not resolve full address or local time from GPS.")
138
-
139
-
140
- # # 🚨 Display rescue numbers
141
  # if country in rescue_contacts:
142
  # st.markdown("### 🚨 Local Emergency Numbers")
143
  # contacts = rescue_contacts[country]
144
  # for service, number in contacts.items():
145
  # st.markdown(f"<div class='contact-box'>πŸ“ž <strong>{service}</strong>: {number}</div>", unsafe_allow_html=True)
146
 
 
 
 
147
  # col1, col2 = st.columns([2, 1])
148
 
149
  # with col1:
150
  # st.markdown("### 🧠 Ask your question (any language):")
151
- # user_input = st.text_area(" ", placeholder="e.g. Ψ²Ω„Ψ²Ω„Ϋ’ Ϊ©Ϋ’ Ψ―ΩˆΨ±Ψ§Ω† Ω…Ψ¬ΪΎ کیا Ϊ©Ψ±Ω†Ψ§ Ϊ†Ψ§ΫŒΫ’ΨŸ or What to do in a flood?", height=120)
152
 
153
  # if st.button("πŸ” Get Help"):
154
- # if user_input.strip() != "":
155
  # try:
156
  # translated_input = GoogleTranslator(source='auto', target='en').translate(user_input)
157
- # location_context = f"The user is currently in {user_location}. Provide disaster-specific advice and include local rescue contact details if relevant. "
158
- # prompt = f"{location_context}Answer this disaster-related question: {translated_input}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159
 
160
  # headers = {
161
  # "Authorization": f"Bearer {GROQ_API_KEY}",
@@ -173,7 +205,9 @@
173
  # translated_answer = GoogleTranslator(source='en', target=target_lang_code).translate(answer_en)
174
  # st.markdown(f"<div class='answer-box'>{translated_answer}</div>", unsafe_allow_html=True)
175
 
176
- # timestamp = local_time.strftime("%I:%M %p")
 
 
177
  # st.session_state.history.append({"time": timestamp, "question": user_input})
178
  # else:
179
  # st.error("❌ Error: " + response.text)
@@ -198,231 +232,108 @@
198
 
199
 
200
  import streamlit as st
201
- import requests
202
- from datetime import datetime
203
- from deep_translator import GoogleTranslator
204
- from geopy.geocoders import Nominatim
205
  from timezonefinder import TimezoneFinder
 
206
  import pytz
207
- from streamlit_js_eval import get_geolocation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
208
 
209
- # ---------------------------
210
- # API Key
211
- # ---------------------------
212
- GROQ_API_KEY = "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"
213
-
214
- # ---------------------------
215
- # Page Config
216
- # ---------------------------
217
- st.set_page_config(page_title="AI Disaster Assistant", layout="wide", initial_sidebar_state="expanded")
218
-
219
- # ---------------------------
220
- # Rescue numbers dictionary
221
- # ---------------------------
222
- rescue_contacts = {
223
- "Pakistan": {
224
- "Ambulance": "115",
225
- "Fire Brigade": "16",
226
- "Rescue Service": "1122",
227
- "Police": "15"
228
- },
229
- "India": {
230
- "Ambulance": "102",
231
- "Fire Brigade": "101",
232
- "Disaster Helpline": "108",
233
- "Police": "100"
234
- },
235
- "USA": {
236
- "Emergency Services": "911"
237
- },
238
- "United Kingdom": {
239
- "Emergency Services": "999"
240
- }
241
- }
242
-
243
- # ---------------------------
244
- # Timezone Helper
245
- # ---------------------------
246
- def get_timezone(lat, lon):
247
- tf = TimezoneFinder()
248
- tz_name = tf.timezone_at(lat=lat, lng=lon)
249
- if tz_name:
250
- try:
251
- return pytz.timezone(tz_name)
252
- except Exception:
253
- return pytz.timezone("Asia/Karachi") # fallback to Pakistan
254
- return pytz.timezone("Asia/Karachi")
255
-
256
- # ---------------------------
257
- # Session setup
258
- # ---------------------------
259
- if "history" not in st.session_state:
260
- st.session_state.history = []
261
- if "tz" not in st.session_state:
262
- st.session_state.tz = pytz.timezone("Asia/Karachi") # default Lahore
263
-
264
- # ---------------------------
265
- # CSS Styling
266
- # ---------------------------
267
- st.markdown("""
268
- <style>
269
- body { background-color: #0d1117; color: white; }
270
- h1, h2, h3, h4, h5 { color: white; }
271
- input, textarea, .stTextInput>div>div>input { background-color: #161b22 !important; color: white !important; }
272
- .chat-bubble { background-color: #f0f0f0; color: #000; padding: 0.5rem; margin-bottom: 0.5rem; border-radius: 10px; }
273
- .answer-box { background-color: #d6f5f5; padding: 1rem; border-radius: 12px; color: #000; }
274
- .contact-box { background-color: #ffeecc; padding: 1rem; border-radius: 10px; color: #000; }
275
- [data-testid="stSidebar"] { background-color: #161b22; }
276
- .sidebar .sidebar-content { background-color: #161b22; }
277
- </style>
278
- """, unsafe_allow_html=True)
279
-
280
- # ---------------------------
281
- # Sidebar Navigation
282
- # ---------------------------
283
- st.sidebar.markdown("# 🌍 AI Disaster Response Assistant")
284
- page = st.sidebar.radio("Navigation", ["Chat Assistant", "Image Analysis"])
285
-
286
- if page == "Image Analysis":
287
- st.switch_page("pages/image_analysis.py")
288
-
289
- # ---------------------------
290
- # Main Page (Chat Assistant)
291
- # ---------------------------
292
- st.markdown("""
293
- <h1 style='text-align: center; background-color: #008080; color: white; padding: 1rem; border-radius: 12px;'>
294
- πŸ’¬ AI Disaster Chat Assistant
295
- </h1>
296
- """, unsafe_allow_html=True)
297
-
298
- # ---------------------------
299
- # Language Selection
300
- # ---------------------------
301
- language_options = {
302
- "English": "en",
303
- "Urdu": "ur",
304
- "Hindi": "hi",
305
- "Japanese": "ja",
306
- "Turkish": "tr",
307
- "Italian": "it"
308
- }
309
- preferred_language = st.selectbox("🌐 Select your preferred language for responses:", list(language_options.keys()))
310
- target_lang_code = language_options[preferred_language]
311
-
312
- # ---------------------------
313
- # Get Location & Timezone
314
- # ---------------------------
315
- location_data = get_geolocation()
316
- user_location = "Unknown"
317
- city = ""
318
- country = ""
319
-
320
- if location_data and location_data.get("coords"):
321
- lat = location_data["coords"]["latitude"]
322
- lon = location_data["coords"]["longitude"]
323
- st.success(f"πŸ“ GPS Location: {lat:.4f}, {lon:.4f}")
324
  try:
 
325
  geolocator = Nominatim(user_agent="geoapiExercises")
326
  location = geolocator.reverse((lat, lon), language='en')
327
- city = location.raw['address'].get('city', '') or location.raw['address'].get('town', '')
328
- country = location.raw['address'].get('country', '')
329
- user_location = f"{city}, {country}"
330
- st.markdown(f"πŸ“Œ You are in *{user_location}*")
331
- st.session_state.tz = get_timezone(lat, lon)
332
- except Exception:
333
- st.warning("🌐 Could not resolve full address or timezone from GPS.")
334
-
335
- # ---------------------------
336
- # Display rescue numbers
337
- # ---------------------------
338
- if country in rescue_contacts:
339
- st.markdown("### 🚨 Local Emergency Numbers")
340
- contacts = rescue_contacts[country]
341
- for service, number in contacts.items():
342
- st.markdown(f"<div class='contact-box'>πŸ“ž <strong>{service}</strong>: {number}</div>", unsafe_allow_html=True)
343
-
344
- # ---------------------------
345
- # Chat UI
346
- # ---------------------------
347
- col1, col2 = st.columns([2, 1])
348
-
349
- with col1:
350
- st.markdown("### 🧠 Ask your question (any language):")
351
- user_input = st.text_area(" ", placeholder="e.g. Ψ²Ω„Ψ²Ω„Ϋ’ Ϊ©Ϋ’ Ψ―ΩˆΨ±Ψ§Ω† Ω…Ψ¬ΪΎΫ’ کیا Ϊ©Ψ±Ω†Ψ§ Ϊ†Ψ§ΫΫŒΫ’ΨŸ or What to do in a flood?", height=120)
352
-
353
- if st.button("πŸ” Get Help"):
354
- if user_input.strip():
355
- try:
356
- translated_input = GoogleTranslator(source='auto', target='en').translate(user_input)
357
- # location_context = f"The user is currently in {user_location}. Provide disaster-specific advice and include local rescue contact details if relevant. "
358
- # Fetch country-specific rescue numbers
359
- # rescue_info = ""
360
- # if country in rescue_contacts:
361
- # rescue_info = "Local emergency numbers:\n" + "\n".join([f"{k}: {v}" for k, v in rescue_contacts[country].items()])
 
 
362
 
363
- # location_context = f"The user is currently in {user_location}. {rescue_info} Provide disaster-specific advice relevant to this location. If possible, suggest actions based on this specific region."
364
- # # rescue_info = "Local emergency numbers:\n" + "\n".join([f"{k}: {v}" for k, v in rescue_contacts[country].items()])
365
 
366
- # # location_context = f"The user is currently in {user_location}. {rescue_info} Provide disaster-specific advice relevant to this location. If possible, suggest actions based on this specific region."
 
367
 
368
-
369
- # prompt = f"{location_context}Answer this disaster-related question: {translated_input}"
370
- rescue_info = ""
371
- if country in rescue_contacts:
372
- contacts = rescue_contacts[country]
373
- rescue_info = "Local Emergency Numbers:\n" + "\n".join([f"{service}: {number}" for service, number in contacts.items()])
374
 
375
-
376
- else:
377
- rescue_info = "No specific emergency contacts found for this region."
378
-
379
- # Create a location-aware prompt for the LLM
380
- location_context = (
381
- f"The user is currently in {user_location}. "
382
- f"{rescue_info}\n"
383
- "Provide safety measures specifically for this location in the context of the disaster. "
384
- "DO NOT mention US-based emergency numbers unless the user's location is in the US."
385
- )
386
- prompt = f"{location_context} Answer this disaster-related question: {translated_input}"
387
-
388
-
389
- headers = {
390
- "Authorization": f"Bearer {GROQ_API_KEY}",
391
- "Content-Type": "application/json"
392
- }
393
- data = {
394
- "model": "llama3-70b-8192",
395
- "messages": [{"role": "user", "content": prompt}]
396
- }
397
-
398
- response = requests.post("https://api.groq.com/openai/v1/chat/completions", headers=headers, json=data)
399
-
400
- if response.status_code == 200:
401
- answer_en = response.json()['choices'][0]['message']['content']
402
- translated_answer = GoogleTranslator(source='en', target=target_lang_code).translate(answer_en)
403
- st.markdown(f"<div class='answer-box'>{translated_answer}</div>", unsafe_allow_html=True)
404
-
405
- # Get current local time with timezone
406
- now = datetime.now(st.session_state.tz)
407
- timestamp = now.strftime("%I:%M %p")
408
- st.session_state.history.append({"time": timestamp, "question": user_input})
409
- else:
410
- st.error("❌ Error: " + response.text)
411
- except Exception as e:
412
- st.error(f"⚠ Exception occurred: {e}")
413
-
414
- with col2:
415
- st.markdown("### πŸ“œ Chat History")
416
- if st.session_state.history:
417
- for entry in reversed(st.session_state.history):
418
- st.markdown(f"""
419
- <div class='chat-bubble'>
420
- πŸ•’ {entry['time']}<br><strong>{entry['question']}</strong>
421
- </div>
422
- """, unsafe_allow_html=True)
423
- else:
424
- st.info("No questions asked yet.")
425
 
426
- if st.button("🧹 Clear History"):
427
- st.session_state.history = []
428
- st.success("Chat history cleared.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # # # app.py
2
+
3
  # import streamlit as st
4
  # import requests
5
  # from datetime import datetime
6
  # from deep_translator import GoogleTranslator
7
  # from geopy.geocoders import Nominatim
 
8
  # from timezonefinder import TimezoneFinder
9
  # import pytz
10
  # from streamlit_js_eval import get_geolocation
11
 
12
+ # # ---------------------------
13
+ # # API Key
14
+ # # ---------------------------
15
  # GROQ_API_KEY = "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"
16
 
17
+ # # ---------------------------
18
+ # # Page Config
19
+ # # ---------------------------
20
+ # st.set_page_config(page_title="AI Disaster Assistant", layout="wide", initial_sidebar_state="expanded")
21
+
22
+ # # ---------------------------
23
  # # Rescue numbers dictionary
24
+ # # ---------------------------
25
  # rescue_contacts = {
26
  # "Pakistan": {
27
  # "Ambulance": "115",
 
43
  # }
44
  # }
45
 
46
+ # # ---------------------------
47
+ # # Timezone Helper
48
+ # # ---------------------------
49
+ # def get_timezone(lat, lon):
50
  # tf = TimezoneFinder()
51
+ # tz_name = tf.timezone_at(lat=lat, lng=lon)
52
+ # if tz_name:
 
53
  # try:
54
+ # return pytz.timezone(tz_name)
55
+ # except Exception:
56
+ # return pytz.timezone("Asia/Karachi") # fallback to Pakistan
57
+ # return pytz.timezone("Asia/Karachi")
 
 
 
 
 
 
 
58
 
59
+ # # ---------------------------
60
  # # Session setup
61
+ # # ---------------------------
62
  # if "history" not in st.session_state:
63
  # st.session_state.history = []
64
+ # if "tz" not in st.session_state:
65
+ # st.session_state.tz = pytz.timezone("Asia/Karachi") # default Lahore
66
 
67
+ # # ---------------------------
68
+ # # CSS Styling
69
+ # # ---------------------------
70
  # st.markdown("""
71
  # <style>
72
  # body { background-color: #0d1117; color: white; }
 
75
  # .chat-bubble { background-color: #f0f0f0; color: #000; padding: 0.5rem; margin-bottom: 0.5rem; border-radius: 10px; }
76
  # .answer-box { background-color: #d6f5f5; padding: 1rem; border-radius: 12px; color: #000; }
77
  # .contact-box { background-color: #ffeecc; padding: 1rem; border-radius: 10px; color: #000; }
78
+ # [data-testid="stSidebar"] { background-color: #161b22; }
79
+ # .sidebar .sidebar-content { background-color: #161b22; }
80
  # </style>
81
  # """, unsafe_allow_html=True)
82
 
83
+ # # ---------------------------
84
+ # # Sidebar Navigation
85
+ # # ---------------------------
86
+ # st.sidebar.markdown("# 🌍 AI Disaster Response Assistant")
87
+ # page = st.sidebar.radio("Navigation", ["Chat Assistant", "Image Analysis"])
88
+
89
+ # if page == "Image Analysis":
90
+ # st.switch_page("pages/image_analysis.py")
91
+
92
+ # # ---------------------------
93
+ # # Main Page (Chat Assistant)
94
+ # # ---------------------------
95
  # st.markdown("""
96
  # <h1 style='text-align: center; background-color: #008080; color: white; padding: 1rem; border-radius: 12px;'>
97
+ # πŸ’¬ AI Disaster Chat Assistant
98
  # </h1>
99
  # """, unsafe_allow_html=True)
100
 
101
+ # # ---------------------------
102
+ # # Language Selection
103
+ # # ---------------------------
104
  # language_options = {
105
  # "English": "en",
106
  # "Urdu": "ur",
 
112
  # preferred_language = st.selectbox("🌐 Select your preferred language for responses:", list(language_options.keys()))
113
  # target_lang_code = language_options[preferred_language]
114
 
115
+ # # ---------------------------
116
+ # # Get Location & Timezone
117
+ # # ---------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  # location_data = get_geolocation()
 
119
  # user_location = "Unknown"
120
  # city = ""
121
  # country = ""
 
122
 
123
  # if location_data and location_data.get("coords"):
124
  # lat = location_data["coords"]["latitude"]
 
131
  # country = location.raw['address'].get('country', '')
132
  # user_location = f"{city}, {country}"
133
  # st.markdown(f"πŸ“Œ You are in *{user_location}*")
134
+ # st.session_state.tz = get_timezone(lat, lon)
135
+ # except Exception:
136
+ # st.warning("🌐 Could not resolve full address or timezone from GPS.")
137
 
138
+ # # ---------------------------
139
+ # # Display rescue numbers
140
+ # # ---------------------------
 
 
 
 
141
  # if country in rescue_contacts:
142
  # st.markdown("### 🚨 Local Emergency Numbers")
143
  # contacts = rescue_contacts[country]
144
  # for service, number in contacts.items():
145
  # st.markdown(f"<div class='contact-box'>πŸ“ž <strong>{service}</strong>: {number}</div>", unsafe_allow_html=True)
146
 
147
+ # # ---------------------------
148
+ # # Chat UI
149
+ # # ---------------------------
150
  # col1, col2 = st.columns([2, 1])
151
 
152
  # with col1:
153
  # st.markdown("### 🧠 Ask your question (any language):")
154
+ # user_input = st.text_area(" ", placeholder="e.g. Ψ²Ω„Ψ²Ω„Ϋ’ Ϊ©Ϋ’ Ψ―ΩˆΨ±Ψ§Ω† Ω…Ψ¬ΪΎΫ’ کیا Ϊ©Ψ±Ω†Ψ§ Ϊ†Ψ§ΫΫŒΫ’ΨŸ or What to do in a flood?", height=120)
155
 
156
  # if st.button("πŸ” Get Help"):
157
+ # if user_input.strip():
158
  # try:
159
  # translated_input = GoogleTranslator(source='auto', target='en').translate(user_input)
160
+ # # location_context = f"The user is currently in {user_location}. Provide disaster-specific advice and include local rescue contact details if relevant. "
161
+ # # Fetch country-specific rescue numbers
162
+ # # rescue_info = ""
163
+ # # if country in rescue_contacts:
164
+ # # rescue_info = "Local emergency numbers:\n" + "\n".join([f"{k}: {v}" for k, v in rescue_contacts[country].items()])
165
+
166
+ # # location_context = f"The user is currently in {user_location}. {rescue_info} Provide disaster-specific advice relevant to this location. If possible, suggest actions based on this specific region."
167
+ # # # rescue_info = "Local emergency numbers:\n" + "\n".join([f"{k}: {v}" for k, v in rescue_contacts[country].items()])
168
+
169
+ # # # location_context = f"The user is currently in {user_location}. {rescue_info} Provide disaster-specific advice relevant to this location. If possible, suggest actions based on this specific region."
170
+
171
+
172
+ # # prompt = f"{location_context}Answer this disaster-related question: {translated_input}"
173
+ # rescue_info = ""
174
+ # if country in rescue_contacts:
175
+ # contacts = rescue_contacts[country]
176
+ # rescue_info = "Local Emergency Numbers:\n" + "\n".join([f"{service}: {number}" for service, number in contacts.items()])
177
+
178
+
179
+ # else:
180
+ # rescue_info = "No specific emergency contacts found for this region."
181
+
182
+ # # Create a location-aware prompt for the LLM
183
+ # location_context = (
184
+ # f"The user is currently in {user_location}. "
185
+ # f"{rescue_info}\n"
186
+ # "Provide safety measures specifically for this location in the context of the disaster. "
187
+ # "DO NOT mention US-based emergency numbers unless the user's location is in the US."
188
+ # )
189
+ # prompt = f"{location_context} Answer this disaster-related question: {translated_input}"
190
+
191
 
192
  # headers = {
193
  # "Authorization": f"Bearer {GROQ_API_KEY}",
 
205
  # translated_answer = GoogleTranslator(source='en', target=target_lang_code).translate(answer_en)
206
  # st.markdown(f"<div class='answer-box'>{translated_answer}</div>", unsafe_allow_html=True)
207
 
208
+ # # Get current local time with timezone
209
+ # now = datetime.now(st.session_state.tz)
210
+ # timestamp = now.strftime("%I:%M %p")
211
  # st.session_state.history.append({"time": timestamp, "question": user_input})
212
  # else:
213
  # st.error("❌ Error: " + response.text)
 
232
 
233
 
234
  import streamlit as st
235
+ import openai
236
+ from googletrans import Translator
237
+ from streamlit_js_eval import get_geolocation
 
238
  from timezonefinder import TimezoneFinder
239
+ from datetime import datetime
240
  import pytz
241
+ from geopy.geocoders import Nominatim
242
+
243
+ st.set_page_config(page_title="AI Disaster Assistant 🌍", layout="centered")
244
+
245
+ # Session state setup
246
+ if 'tz' not in st.session_state:
247
+ st.session_state.tz = None
248
+
249
+ st.title("🌐 AI Disaster Safety Assistant")
250
+ st.markdown("Your emergency translator and safety guide, wherever you are.")
251
+
252
+ # Get user's geolocation
253
+ loc = get_geolocation()
254
+
255
+ if loc:
256
+ lat = loc['coords']['latitude']
257
+ lon = loc['coords']['longitude']
258
+ st.success(f"βœ… GPS Coordinates detected: Latitude {lat}, Longitude {lon}")
259
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
260
  try:
261
+ # Reverse geocoding
262
  geolocator = Nominatim(user_agent="geoapiExercises")
263
  location = geolocator.reverse((lat, lon), language='en')
264
+ if location:
265
+ address = location.raw.get('address', {})
266
+ city = (address.get('city') or address.get('town') or
267
+ address.get('village') or address.get('municipality') or '')
268
+ country = address.get('country', '')
269
+
270
+ if city:
271
+ user_location = f"{city}, {country}"
272
+ elif country:
273
+ user_location = f"{country}"
274
+ else:
275
+ user_location = "Unknown Location"
276
+
277
+ st.markdown(f"πŸ“Œ You are in **{user_location}**")
278
+
279
+ # Timezone calculation
280
+ tf = TimezoneFinder()
281
+ timezone_str = tf.timezone_at(lng=lon, lat=lat)
282
+ if timezone_str:
283
+ tz = pytz.timezone(timezone_str)
284
+ local_time = datetime.now(tz).strftime('%Y-%m-%d %H:%M:%S')
285
+ st.session_state.tz = timezone_str
286
+ st.markdown(f"πŸ•’ Local time: `{local_time}`")
287
+ else:
288
+ st.warning("⚠️ Timezone could not be determined.")
289
+ else:
290
+ st.warning("⚠️ Could not find location details for the given coordinates.")
291
+ except Exception as e:
292
+ st.warning(f"🌐 Error during location lookup: {e}")
293
+ else:
294
+ st.warning("πŸ“ Since I couldn't determine your exact location, translation and timezone might be less accurate.")
295
+
296
+ # Language selector
297
+ language = st.selectbox(
298
+ "🌍 Select your language",
299
+ ("English", "Urdu", "Spanish", "French", "Arabic", "Chinese")
300
+ )
301
 
302
+ # Translator setup
303
+ translator = Translator()
304
 
305
+ # Input prompt
306
+ user_input = st.text_area("πŸ’¬ Describe your emergency or ask for help:", "")
307
 
308
+ if st.button("🚨 Get Safety Instructions"):
309
+ if user_input:
310
+ prompt = f"Give safety tips and emergency measures based on this situation: {user_input}. Be concise and helpful."
 
 
 
311
 
312
+ openai.api_key = st.secrets.get("GROQ_API_KEY", "your-api-key")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
313
 
314
+ try:
315
+ from openai import OpenAI
316
+ client = OpenAI()
317
+ completion = client.chat.completions.create(
318
+ model="llama3-70b-8192",
319
+ messages=[
320
+ {"role": "system", "content": "You are a helpful assistant providing safety tips."},
321
+ {"role": "user", "content": prompt}
322
+ ],
323
+ temperature=0.7
324
+ )
325
+ reply = completion.choices[0].message.content
326
+
327
+ # Translate if needed
328
+ if language != "English":
329
+ translated = translator.translate(reply, dest=language.lower())
330
+ st.markdown("### πŸ›‘οΈ Safety Tips (Translated):")
331
+ st.write(translated.text)
332
+ else:
333
+ st.markdown("### πŸ›‘οΈ Safety Tips:")
334
+ st.write(reply)
335
+
336
+ except Exception as e:
337
+ st.error(f"❌ Error generating response: {e}")
338
+ else:
339
+ st.warning("Please describe your emergency situation first.")