iffazainab commited on
Commit
fbf5b03
·
verified ·
1 Parent(s): 0bb78d3

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +183 -0
app.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import requests
3
+ from datetime import datetime
4
+ from deep_translator import GoogleTranslator
5
+ from geopy.geocoders import Nominatim
6
+ from streamlit_lottie import st_lottie
7
+ from timezonefinder import TimezoneFinder
8
+ import pytz
9
+ from streamlit_js_eval import get_geolocation
10
+
11
+ # ---------------------------
12
+ # API Key
13
+ # ---------------------------
14
+ GROQ_API_KEY = "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"
15
+
16
+ # ---------------------------
17
+ # Rescue numbers dictionary
18
+ # ---------------------------
19
+ rescue_contacts = {
20
+ "Pakistan": {
21
+ "Ambulance": "115",
22
+ "Fire Brigade": "16",
23
+ "Rescue Service": "1122",
24
+ "Police": "15"
25
+ },
26
+ "India": {
27
+ "Ambulance": "102",
28
+ "Fire Brigade": "101",
29
+ "Disaster Helpline": "108",
30
+ "Police": "100"
31
+ },
32
+ "USA": {
33
+ "Emergency Services": "911"
34
+ },
35
+ "United Kingdom": {
36
+ "Emergency Services": "999"
37
+ }
38
+ }
39
+
40
+ # ---------------------------
41
+ # Timezone Helper
42
+ # ---------------------------
43
+ def get_timezone(lat, lon):
44
+ tf = TimezoneFinder()
45
+ tz_name = tf.timezone_at(lat=lat, lng=lon)
46
+ if tz_name:
47
+ try:
48
+ return pytz.timezone(tz_name)
49
+ except Exception:
50
+ return pytz.timezone("Asia/Karachi") # fallback to Pakistan
51
+ return pytz.timezone("Asia/Karachi")
52
+
53
+ # ---------------------------
54
+ # Session setup
55
+ # ---------------------------
56
+ if "history" not in st.session_state:
57
+ st.session_state.history = []
58
+ if "tz" not in st.session_state:
59
+ st.session_state.tz = pytz.timezone("Asia/Karachi") # default Lahore
60
+
61
+ # ---------------------------
62
+ # Page setup
63
+ # ---------------------------
64
+ st.set_page_config(page_title="AI Disaster Assistant", layout="wide")
65
+ st.markdown("""
66
+ <style>
67
+ body { background-color: #0d1117; color: white; }
68
+ h1, h2, h3, h4, h5 { color: white; }
69
+ input, textarea, .stTextInput>div>div>input { background-color: #161b22 !important; color: white !important; }
70
+ .chat-bubble { background-color: #f0f0f0; color: #000; padding: 0.5rem; margin-bottom: 0.5rem; border-radius: 10px; }
71
+ .answer-box { background-color: #d6f5f5; padding: 1rem; border-radius: 12px; color: #000; }
72
+ .contact-box { background-color: #ffeecc; padding: 1rem; border-radius: 10px; color: #000; }
73
+ </style>
74
+ """, unsafe_allow_html=True)
75
+
76
+ st.markdown("""
77
+ <h1 style='text-align: center; background-color: #008080; color: white; padding: 1rem; border-radius: 12px;'>
78
+ 🌍 AI Disaster Response Assistant
79
+ </h1>
80
+ """, unsafe_allow_html=True)
81
+
82
+ # ---------------------------
83
+ # Language Selection
84
+ # ---------------------------
85
+ language_options = {
86
+ "English": "en",
87
+ "Urdu": "ur",
88
+ "Hindi": "hi",
89
+ "Japanese": "ja",
90
+ "Turkish": "tr",
91
+ "Italian": "it"
92
+ }
93
+ preferred_language = st.selectbox("🌐 Select your preferred language for responses:", list(language_options.keys()))
94
+ target_lang_code = language_options[preferred_language]
95
+
96
+ # ---------------------------
97
+ # Get Location & Timezone
98
+ # ---------------------------
99
+ location_data = get_geolocation()
100
+ user_location = "Unknown"
101
+ city = ""
102
+ country = ""
103
+
104
+ if location_data and location_data.get("coords"):
105
+ lat = location_data["coords"]["latitude"]
106
+ lon = location_data["coords"]["longitude"]
107
+ st.success(f"📍 GPS Location: {lat:.4f}, {lon:.4f}")
108
+ try:
109
+ geolocator = Nominatim(user_agent="geoapiExercises")
110
+ location = geolocator.reverse((lat, lon), language='en')
111
+ city = location.raw['address'].get('city', '') or location.raw['address'].get('town', '')
112
+ country = location.raw['address'].get('country', '')
113
+ user_location = f"{city}, {country}"
114
+ st.markdown(f"📌 You are in *{user_location}*")
115
+ st.session_state.tz = get_timezone(lat, lon)
116
+ except Exception:
117
+ st.warning("🌐 Could not resolve full address or timezone from GPS.")
118
+
119
+ # ---------------------------
120
+ # Display rescue numbers
121
+ # ---------------------------
122
+ if country in rescue_contacts:
123
+ st.markdown("### 🚨 Local Emergency Numbers")
124
+ contacts = rescue_contacts[country]
125
+ for service, number in contacts.items():
126
+ st.markdown(f"<div class='contact-box'>📞 <strong>{service}</strong>: {number}</div>", unsafe_allow_html=True)
127
+
128
+ # ---------------------------
129
+ # Chat UI
130
+ # ---------------------------
131
+ col1, col2 = st.columns([2, 1])
132
+
133
+ with col1:
134
+ st.markdown("### 🧠 Ask your question (any language):")
135
+ user_input = st.text_area(" ", placeholder="e.g. زلزلے کے دوران مجھے کیا کرنا چاہیے؟ or What to do in a flood?", height=120)
136
+
137
+ if st.button("🔍 Get Help"):
138
+ if user_input.strip():
139
+ try:
140
+ translated_input = GoogleTranslator(source='auto', target='en').translate(user_input)
141
+ location_context = f"The user is currently in {user_location}. Provide disaster-specific advice and include local rescue contact details if relevant. "
142
+ prompt = f"{location_context}Answer this disaster-related question: {translated_input}"
143
+
144
+ headers = {
145
+ "Authorization": f"Bearer {GROQ_API_KEY}",
146
+ "Content-Type": "application/json"
147
+ }
148
+ data = {
149
+ "model": "llama3-70b-8192",
150
+ "messages": [{"role": "user", "content": prompt}]
151
+ }
152
+
153
+ response = requests.post("https://api.groq.com/openai/v1/chat/completions", headers=headers, json=data)
154
+
155
+ if response.status_code == 200:
156
+ answer_en = response.json()['choices'][0]['message']['content']
157
+ translated_answer = GoogleTranslator(source='en', target=target_lang_code).translate(answer_en)
158
+ st.markdown(f"<div class='answer-box'>{translated_answer}</div>", unsafe_allow_html=True)
159
+
160
+ # Get current local time with timezone
161
+ now = datetime.now(st.session_state.tz)
162
+ timestamp = now.strftime("%I:%M %p")
163
+ st.session_state.history.append({"time": timestamp, "question": user_input})
164
+ else:
165
+ st.error("❌ Error: " + response.text)
166
+ except Exception as e:
167
+ st.error(f"⚠ Exception occurred: {e}")
168
+
169
+ with col2:
170
+ st.markdown("### 📜 Chat History")
171
+ if st.session_state.history:
172
+ for entry in reversed(st.session_state.history):
173
+ st.markdown(f"""
174
+ <div class='chat-bubble'>
175
+ 🕒 {entry['time']}<br><strong>{entry['question']}</strong>
176
+ </div>
177
+ """, unsafe_allow_html=True)
178
+ else:
179
+ st.info("No questions asked yet.")
180
+
181
+ if st.button("🧹 Clear History"):
182
+ st.session_state.history = []
183
+ st.success("Chat history cleared.")