lalaru commited on
Commit
6df6c6d
·
verified ·
1 Parent(s): b25f3e9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +262 -60
app.py CHANGED
@@ -1,19 +1,224 @@
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 +240,30 @@ rescue_contacts = {
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 +272,32 @@ st.markdown("""
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 +309,13 @@ language_options = {
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,28 +328,30 @@ if location_data and location_data.get("coords"):
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. "
@@ -173,7 +373,9 @@ with col1:
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)
@@ -194,4 +396,4 @@ with col2:
194
 
195
  if st.button("🧹 Clear History"):
196
  st.session_state.history = []
197
- st.success("Chat history cleared.")
 
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",
20
+ # "Fire Brigade": "16",
21
+ # "Rescue Service": "1122",
22
+ # "Police": "15"
23
+ # },
24
+ # "India": {
25
+ # "Ambulance": "102",
26
+ # "Fire Brigade": "101",
27
+ # "Disaster Helpline": "108",
28
+ # "Police": "100"
29
+ # },
30
+ # "USA": {
31
+ # "Emergency Services": "911"
32
+ # },
33
+ # "United Kingdom": {
34
+ # "Emergency Services": "999"
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; }
65
+ # h1, h2, h3, h4, h5 { color: white; }
66
+ # input, textarea, .stTextInput>div>div>input { background-color: #161b22 !important; color: white !important; }
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",
83
+ # "Hindi": "hi",
84
+ # "Japanese": "ja",
85
+ # "Turkish": "tr",
86
+ # "Italian": "it"
87
+ # }
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"]
124
+ # lon = location_data["coords"]["longitude"]
125
+ # st.success(f"📍 GPS Location: {lat:.4f}, {lon:.4f}")
126
+ # try:
127
+ # geolocator = Nominatim(user_agent="geoapiExercises")
128
+ # location = geolocator.reverse((lat, lon), language='en')
129
+ # city = location.raw['address'].get('city', '') or location.raw['address'].get('town', '')
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}",
162
+ # "Content-Type": "application/json"
163
+ # }
164
+ # data = {
165
+ # "model": "llama3-70b-8192",
166
+ # "messages": [{"role": "user", "content": prompt}]
167
+ # }
168
+
169
+ # response = requests.post("https://api.groq.com/openai/v1/chat/completions", headers=headers, json=data)
170
+
171
+ # if response.status_code == 200:
172
+ # answer_en = response.json()['choices'][0]['message']['content']
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)
180
+ # except Exception as e:
181
+ # st.error(f"⚠ Exception occurred: {e}")
182
+
183
+ # with col2:
184
+ # st.markdown("### 📜 Chat History")
185
+ # if st.session_state.history:
186
+ # for entry in reversed(st.session_state.history):
187
+ # st.markdown(f"""
188
+ # <div class='chat-bubble'>
189
+ # 🕒 {entry['time']}<br><strong>{entry['question']}</strong>
190
+ # </div>
191
+ # """, unsafe_allow_html=True)
192
+ # else:
193
+ # st.info("No questions asked yet.")
194
+
195
+ # if st.button("🧹 Clear History"):
196
+ # st.session_state.history = []
197
+ # st.success("Chat history cleared.")
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",
 
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; }
 
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",
 
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"]
 
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. "
 
373
  translated_answer = GoogleTranslator(source='en', target=target_lang_code).translate(answer_en)
374
  st.markdown(f"<div class='answer-box'>{translated_answer}</div>", unsafe_allow_html=True)
375
 
376
+ # Get current local time with timezone
377
+ now = datetime.now(st.session_state.tz)
378
+ timestamp = now.strftime("%I:%M %p")
379
  st.session_state.history.append({"time": timestamp, "question": user_input})
380
  else:
381
  st.error("❌ Error: " + response.text)
 
396
 
397
  if st.button("🧹 Clear History"):
398
  st.session_state.history = []
399
+ st.success("Chat history cleared.")