sairika commited on
Commit
2600c96
Β·
verified Β·
1 Parent(s): 4bb1a1c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -18
app.py CHANGED
@@ -71,22 +71,32 @@ def get_location_coords(location):
71
  if "chittagong" not in location.lower() and "chattogram" not in location.lower():
72
  search_location = f"{location}, Chittagong, Bangladesh"
73
 
 
 
74
  response = requests.get(
75
  "https://nominatim.openstreetmap.org/search",
76
  params={
77
  "q": search_location,
78
  "format": "json",
79
- "limit": 1
 
80
  },
81
- headers={"User-Agent": "SafeHer-App-Chittagong"},
82
- timeout=10
83
  )
 
 
 
84
  if response.status_code == 200 and response.json():
85
  data = response.json()[0]
86
- return float(data["lat"]), float(data["lon"])
87
- return None
 
 
 
 
88
  except Exception as e:
89
- print(f"Geocoding error: {e}")
90
  return None
91
 
92
  def assess_area_safety(area_name, current_hour):
@@ -119,19 +129,40 @@ def assess_area_safety(area_name, current_hour):
119
 
120
  def create_interactive_map(start_loc, end_loc, route_info=""):
121
  """Create interactive Leaflet map with route for Chittagong"""
 
 
122
  start_coords = get_location_coords(start_loc)
123
  end_coords = get_location_coords(end_loc)
124
 
125
  if not start_coords or not end_coords:
126
- return f"""<div style='padding: 20px; background: #fff3cd; border-left: 4px solid #ffc107; border-radius: 5px;'>
127
- <h3>⚠️ Could not map exact locations</h3>
128
- <p>Try using specific landmarks like: "Agrabad", "GEC Circle", "Khulshi", "New Market"</p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  <a href='https://www.google.com/maps/dir/?api=1&origin={start_loc},Chittagong&destination={end_loc},Chittagong'
130
- target='_blank' style='color: #007bff; text-decoration: underline;'>
131
- πŸ“ Open in Google Maps
132
  </a>
133
  </div>"""
134
 
 
 
135
  center_lat = (start_coords[0] + end_coords[0]) / 2
136
  center_lon = (start_coords[1] + end_coords[1]) / 2
137
 
@@ -146,6 +177,7 @@ def create_interactive_map(start_loc, end_loc, route_info=""):
146
  <html>
147
  <head>
148
  <meta charset="utf-8">
 
149
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"/>
150
  <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
151
  <style>
@@ -160,7 +192,7 @@ def create_interactive_map(start_loc, end_loc, route_info=""):
160
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
161
  }}
162
  .info-box h3 {{ margin: 0 0 10px 0; color: #333; }}
163
- .info-box p {{ margin: 5px 0; color: #666; }}
164
  .safety-badge {{
165
  display: inline-block;
166
  padding: 5px 12px;
@@ -174,7 +206,7 @@ def create_interactive_map(start_loc, end_loc, route_info=""):
174
  </head>
175
  <body>
176
  <div class="info-box">
177
- <h3>πŸ—ΊοΈ Route: {start_loc} β†’ {end_loc}</h3>
178
  <p><strong>πŸ“ Location:</strong> Chittagong, Bangladesh</p>
179
  <p><strong>πŸ• Current Time:</strong> {datetime.now().strftime('%I:%M %p, %B %d, %Y')}</p>
180
  <p><strong>πŸ›‘οΈ Safety Status:</strong>
@@ -188,6 +220,7 @@ def create_interactive_map(start_loc, end_loc, route_info=""):
188
  </div>
189
  <div id="map"></div>
190
  <script>
 
191
  var map = L.map('map').setView([{center_lat}, {center_lon}], 13);
192
 
193
  L.tileLayer('https://{{s}}.tile.openstreetmap.org/{{z}}/{{x}}/{{y}}.png', {{
@@ -195,6 +228,8 @@ def create_interactive_map(start_loc, end_loc, route_info=""):
195
  maxZoom: 19
196
  }}).addTo(map);
197
 
 
 
198
  var startIcon = L.divIcon({{
199
  html: '<div style="background: #28a745; color: white; padding: 8px 12px; border-radius: 20px; font-weight: bold; box-shadow: 0 2px 8px rgba(0,0,0,0.3); white-space: nowrap;">πŸ“ START</div>',
200
  iconSize: [80, 35],
@@ -209,14 +244,16 @@ def create_interactive_map(start_loc, end_loc, route_info=""):
209
  className: ''
210
  }});
211
 
212
- L.marker([{start_coords[0]}, {start_coords[1]}], {{icon: startIcon}})
213
  .addTo(map)
214
  .bindPopup("<b>Start Location:</b><br>{start_loc}");
215
 
216
- L.marker([{end_coords[0]}, {end_coords[1]}], {{icon: endIcon}})
217
  .addTo(map)
218
  .bindPopup("<b>Destination:</b><br>{end_loc}");
219
 
 
 
220
  var routeLine = L.polyline([
221
  [{start_coords[0]}, {start_coords[1]}],
222
  [{end_coords[0]}, {end_coords[1]}]
@@ -227,7 +264,16 @@ def create_interactive_map(start_loc, end_loc, route_info=""):
227
  dashArray: '10, 10'
228
  }}).addTo(map);
229
 
 
 
230
  map.fitBounds(routeLine.getBounds(), {{padding: [50, 50]}});
 
 
 
 
 
 
 
231
  </script>
232
  </body>
233
  </html>
@@ -305,11 +351,15 @@ def enhanced_chat(message, history, api_key):
305
 
306
  response = call_groq(messages, api_key.strip())
307
 
308
- # Extract locations for map
309
  map_html = None
 
 
310
  route_patterns = [
311
- r'(?:from|start|starting)\s+([^to]+?)\s+(?:to|destination|ending|till)\s+(.+?)(?:\.|$|,|\?)',
312
- r'(?:route|travel|go)\s+(?:from\s+)?([a-zA-Z\s]+?)\s+to\s+([a-zA-Z\s]+?)(?:\.|$|,|\?)'
 
 
313
  ]
314
 
315
  for pattern in route_patterns:
@@ -317,9 +367,21 @@ def enhanced_chat(message, history, api_key):
317
  if route_match:
318
  start_loc = route_match.group(1).strip()
319
  end_loc = route_match.group(2).strip()
 
 
 
 
320
  map_html = create_interactive_map(start_loc, end_loc, response[:300])
321
  break
322
 
 
 
 
 
 
 
 
 
323
  return history + [[message, response]], map_html
324
 
325
  def show_legal_info():
 
71
  if "chittagong" not in location.lower() and "chattogram" not in location.lower():
72
  search_location = f"{location}, Chittagong, Bangladesh"
73
 
74
+ print(f"DEBUG: Searching for coordinates of: {search_location}")
75
+
76
  response = requests.get(
77
  "https://nominatim.openstreetmap.org/search",
78
  params={
79
  "q": search_location,
80
  "format": "json",
81
+ "limit": 1,
82
+ "countrycodes": "bd"
83
  },
84
+ headers={"User-Agent": "SafeHer-App-Chittagong/1.0"},
85
+ timeout=15
86
  )
87
+
88
+ print(f"DEBUG: Geocoding response status: {response.status_code}")
89
+
90
  if response.status_code == 200 and response.json():
91
  data = response.json()[0]
92
+ lat, lon = float(data["lat"]), float(data["lon"])
93
+ print(f"DEBUG: Found coordinates - Lat: {lat}, Lon: {lon}")
94
+ return lat, lon
95
+ else:
96
+ print(f"DEBUG: No results found for {search_location}")
97
+ return None
98
  except Exception as e:
99
+ print(f"DEBUG: Geocoding error: {e}")
100
  return None
101
 
102
  def assess_area_safety(area_name, current_hour):
 
129
 
130
  def create_interactive_map(start_loc, end_loc, route_info=""):
131
  """Create interactive Leaflet map with route for Chittagong"""
132
+ print(f"DEBUG: Creating map for {start_loc} to {end_loc}")
133
+
134
  start_coords = get_location_coords(start_loc)
135
  end_coords = get_location_coords(end_loc)
136
 
137
  if not start_coords or not end_coords:
138
+ error_msg = ""
139
+ if not start_coords:
140
+ error_msg += f"❌ Could not find: {start_loc}<br>"
141
+ if not end_coords:
142
+ error_msg += f"❌ Could not find: {end_loc}<br>"
143
+
144
+ return f"""<div style='padding: 20px; background: #fff3cd; border-left: 4px solid #ffc107; border-radius: 8px;'>
145
+ <h3>⚠️ Could not map locations</h3>
146
+ {error_msg}
147
+ <p style='margin-top: 15px;'><strong>Try these specific locations:</strong></p>
148
+ <ul>
149
+ <li>Agrabad</li>
150
+ <li>GEC Circle</li>
151
+ <li>Khulshi</li>
152
+ <li>New Market</li>
153
+ <li>Panchlaish</li>
154
+ <li>CDA Avenue</li>
155
+ <li>Nasirabad</li>
156
+ <li>Halishahar</li>
157
+ </ul>
158
  <a href='https://www.google.com/maps/dir/?api=1&origin={start_loc},Chittagong&destination={end_loc},Chittagong'
159
+ target='_blank' style='display: inline-block; margin-top: 10px; padding: 10px 20px; background: #007bff; color: white; text-decoration: none; border-radius: 5px;'>
160
+ πŸ“ Open in Google Maps Instead
161
  </a>
162
  </div>"""
163
 
164
+ print(f"DEBUG: Successfully got coordinates for both locations")
165
+
166
  center_lat = (start_coords[0] + end_coords[0]) / 2
167
  center_lon = (start_coords[1] + end_coords[1]) / 2
168
 
 
177
  <html>
178
  <head>
179
  <meta charset="utf-8">
180
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
181
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"/>
182
  <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
183
  <style>
 
192
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
193
  }}
194
  .info-box h3 {{ margin: 0 0 10px 0; color: #333; }}
195
+ .info-box p {{ margin: 5px 0; color: #666; font-size: 14px; }}
196
  .safety-badge {{
197
  display: inline-block;
198
  padding: 5px 12px;
 
206
  </head>
207
  <body>
208
  <div class="info-box">
209
+ <h3>πŸ—ΊοΈ Route Map: {start_loc} β†’ {end_loc}</h3>
210
  <p><strong>πŸ“ Location:</strong> Chittagong, Bangladesh</p>
211
  <p><strong>πŸ• Current Time:</strong> {datetime.now().strftime('%I:%M %p, %B %d, %Y')}</p>
212
  <p><strong>πŸ›‘οΈ Safety Status:</strong>
 
220
  </div>
221
  <div id="map"></div>
222
  <script>
223
+ console.log('Initializing map...');
224
  var map = L.map('map').setView([{center_lat}, {center_lon}], 13);
225
 
226
  L.tileLayer('https://{{s}}.tile.openstreetmap.org/{{z}}/{{x}}/{{y}}.png', {{
 
228
  maxZoom: 19
229
  }}).addTo(map);
230
 
231
+ console.log('Map tiles loaded');
232
+
233
  var startIcon = L.divIcon({{
234
  html: '<div style="background: #28a745; color: white; padding: 8px 12px; border-radius: 20px; font-weight: bold; box-shadow: 0 2px 8px rgba(0,0,0,0.3); white-space: nowrap;">πŸ“ START</div>',
235
  iconSize: [80, 35],
 
244
  className: ''
245
  }});
246
 
247
+ var startMarker = L.marker([{start_coords[0]}, {start_coords[1]}], {{icon: startIcon}})
248
  .addTo(map)
249
  .bindPopup("<b>Start Location:</b><br>{start_loc}");
250
 
251
+ var endMarker = L.marker([{end_coords[0]}, {end_coords[1]}], {{icon: endIcon}})
252
  .addTo(map)
253
  .bindPopup("<b>Destination:</b><br>{end_loc}");
254
 
255
+ console.log('Markers added');
256
+
257
  var routeLine = L.polyline([
258
  [{start_coords[0]}, {start_coords[1]}],
259
  [{end_coords[0]}, {end_coords[1]}]
 
264
  dashArray: '10, 10'
265
  }}).addTo(map);
266
 
267
+ console.log('Route line added');
268
+
269
  map.fitBounds(routeLine.getBounds(), {{padding: [50, 50]}});
270
+
271
+ // Open popups after a short delay
272
+ setTimeout(function() {{
273
+ startMarker.openPopup();
274
+ }}, 500);
275
+
276
+ console.log('Map initialization complete');
277
  </script>
278
  </body>
279
  </html>
 
351
 
352
  response = call_groq(messages, api_key.strip())
353
 
354
+ # Extract locations for map - IMPROVED DETECTION
355
  map_html = None
356
+
357
+ # More comprehensive route patterns
358
  route_patterns = [
359
+ r'(?:from|start|starting|leave|depart)\s+([a-zA-Z\s,]+?)\s+(?:to|destination|ending|till|reach|arrive)\s+([a-zA-Z\s,]+?)(?:\.|$|,|\?|now|right)',
360
+ r'(?:route|way|path|travel|go|going)\s+(?:from\s+)?([a-zA-Z\s,]+?)\s+to\s+([a-zA-Z\s,]+?)(?:\.|$|,|\?|now|right)',
361
+ r'([a-zA-Z\s,]+?)\s+(?:to|till)\s+([a-zA-Z\s,]+?)\s+(?:route|safe|safety|now|right)',
362
+ r'safe.*?(?:from\s+)?([a-zA-Z\s,]+?)\s+(?:to|till)\s+([a-zA-Z\s,]+)',
363
  ]
364
 
365
  for pattern in route_patterns:
 
367
  if route_match:
368
  start_loc = route_match.group(1).strip()
369
  end_loc = route_match.group(2).strip()
370
+ # Clean up locations
371
+ start_loc = re.sub(r'\s+', ' ', start_loc)
372
+ end_loc = re.sub(r'\s+', ' ', end_loc)
373
+ print(f"DEBUG: Detected route - Start: {start_loc}, End: {end_loc}")
374
  map_html = create_interactive_map(start_loc, end_loc, response[:300])
375
  break
376
 
377
+ # If no route detected but keywords suggest mapping
378
+ if not map_html and any(word in keywords for word in ["route", "map", "from", "to", "safe way"]):
379
+ # Try to extract any two location-like words
380
+ locations = re.findall(r'\b([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)\b', message)
381
+ if len(locations) >= 2:
382
+ print(f"DEBUG: Fallback detection - Locations: {locations}")
383
+ map_html = create_interactive_map(locations[0], locations[1], response[:300])
384
+
385
  return history + [[message, response]], map_html
386
 
387
  def show_legal_info():