mirix commited on
Commit
494a00c
·
verified ·
1 Parent(s): d423a9d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -240
app.py CHANGED
@@ -1,5 +1,3 @@
1
- ### app_fixed.py ###
2
-
3
  import gradio as gr
4
  import pandas as pd
5
  import numpy as np
@@ -32,63 +30,56 @@ OVERPASS_URL = "https://maps.mail.ru/osm/tools/overpass/api/interpreter"
32
  ICON_URL = "https://raw.githubusercontent.com/basmilius/weather-icons/refs/heads/dev/production/fill/svg/"
33
 
34
  DEFAULT_LAT, DEFAULT_LON = 49.6116, 6.1319
 
 
35
 
36
 
37
  # --- UTILS ---
38
 
39
  def compute_bbox(lat, lon, dist_km):
40
- """Compute bounding box more reliably for any location."""
41
- # Convert km to degrees (rough approximation)
42
- # At equator: 1 degree ≈ 111 km
43
  lat_delta = dist_km / 111.0
44
  lon_delta = dist_km / (111.0 * np.cos(np.radians(lat)))
45
-
46
- south = lat - lat_delta
47
- north = lat + lat_delta
48
  west = lon - lon_delta
49
  east = lon + lon_delta
50
-
51
- # Ensure longitude wraps properly
52
  if west < -180:
53
  west += 360
54
  if east > 180:
55
  east -= 360
56
-
57
- # Ensure latitude stays in valid range
58
- south = max(south, -90)
59
- north = min(north, 90)
60
-
61
  return f"{south},{west},{north},{east}"
62
 
63
 
64
  def get_elevation_from_srtm(lat, lon):
65
- """Get elevation from SRTM if within coverage area."""
66
  if lat is None or lon is None:
67
  return None
68
-
69
- # SRTM coverage: 60°N to 56°S
70
  if -56 <= lat <= 60:
71
  try:
72
  alt = elevation_data.get_elevation(lat, lon)
73
- if alt is not None and alt > 0:
74
  return alt
75
- except Exception as ex:
76
- print(f"SRTM error for {lat},{lon}: {ex}")
77
-
78
  return None
79
 
80
 
81
  def get_peaks_from_overpass(lat, lon, dist_km):
82
- """Query Overpass API for nearby peaks and hills."""
83
  bbox = compute_bbox(lat, lon, dist_km)
 
84
  query = f"""
85
- [out:json];
86
- (
87
- nwr[natural=peak]({bbox});
88
- nwr[natural=hill]({bbox});
89
- );
90
- out body;
91
  """
 
92
  try:
93
  r = requests.get(OVERPASS_URL, params={"data": query}, timeout=30)
94
  r.raise_for_status()
@@ -97,67 +88,57 @@ def get_peaks_from_overpass(lat, lon, dist_km):
97
  print(f"Error fetching peaks: {e}")
98
  return pd.DataFrame()
99
 
100
- peaks = {"name": [], "latitude": [], "longitude": [], "altitude": []}
101
- skipped = 0
102
- processed = 0
103
- max_peaks = 100 # Limit processing to avoid slowdowns
104
-
105
  for e in data.get("elements", []):
106
- # Stop if we've processed enough peaks
107
- if processed >= max_peaks:
108
- break
109
-
110
  lat_e, lon_e = e.get("lat"), e.get("lon")
111
-
112
- # Skip elements without valid coordinates
113
  if lat_e is None or lon_e is None:
114
- skipped += 1
115
  continue
116
-
117
  tags = e.get("tags", {})
118
  alt = None
119
-
120
- # Strategy 1: Try to get elevation from OSM tag first
121
  ele = tags.get("ele")
122
  if ele and str(ele).replace(".", "").replace("-", "").isnumeric():
123
  alt = float(ele)
124
-
125
- # Strategy 2: If no OSM elevation, try SRTM as fallback
126
- if alt is None or alt <= 10:
127
  alt = get_elevation_from_srtm(lat_e, lon_e)
128
-
129
- # Skip peaks if both strategies failed to produce valid elevation
130
- if alt is None or alt <= 10:
131
- skipped += 1
132
  continue
133
-
134
- peaks["latitude"].append(lat_e)
135
- peaks["longitude"].append(lon_e)
136
- peaks["name"].append(tags.get("name", "Unnamed Peak/Hill"))
137
- peaks["altitude"].append(alt)
138
- processed += 1
139
-
140
- if skipped > 0:
141
- print(f"Skipped {skipped} peaks without complete data (coordinates or elevation)")
142
- if processed >= max_peaks:
143
- print(f"Reached limit of {max_peaks} peaks processed")
144
-
145
- if not peaks["latitude"]:
146
  return pd.DataFrame()
147
 
148
- df = pd.DataFrame(peaks)
149
- df["altitude"] = df["altitude"].round(0).astype(int)
150
-
151
  df["distance_m"] = df.apply(
152
- lambda r: distance.distance((r["latitude"], r["longitude"]), (lat, lon)).m, axis=1
 
 
 
153
  )
 
 
 
 
 
 
 
154
  return df
155
 
156
 
157
- # --- WEATHER FETCH (STRING PARAMS VERSION) ---
158
 
159
  def get_weather_for_peaks_iteratively(df_peaks, min_snow_cm, max_results=20, max_requests=100):
160
- """Fetch weather for peaks with all params as strings to avoid iteration errors."""
161
  if df_peaks.empty:
162
  return pd.DataFrame()
163
 
@@ -181,32 +162,26 @@ def get_weather_for_peaks_iteratively(df_peaks, min_snow_cm, max_results=20, max
181
  responses = openmeteo.weather_api(url, params=params)
182
  if not responses:
183
  continue
184
- response = responses[0]
185
-
186
- hourly = response.Hourly()
187
  if hourly is None:
188
  continue
189
 
190
  idx = 0
191
-
192
- temp_c = float(hourly.Variables(0).ValuesAsNumpy()[idx])
193
- is_day = int(hourly.Variables(1).ValuesAsNumpy()[idx])
194
- weather_code = int(hourly.Variables(2).ValuesAsNumpy()[idx])
195
- snow_depth_m = float(hourly.Variables(3).ValuesAsNumpy()[idx])
196
- snow_depth_cm = snow_depth_m * 100
197
 
198
  if snow_depth_cm >= min_snow_cm:
199
  results.append({
200
  **row.to_dict(),
201
- "temp_c": temp_c,
202
- "is_day": is_day,
203
- "weather_code": weather_code,
204
- "snow_depth_m": snow_depth_m,
205
- "snow_depth_cm": int(np.round(snow_depth_cm, 0))
206
  })
207
 
208
  except Exception as e:
209
- print(f"Error fetching weather for {row['name']} at {row['latitude']},{row['longitude']}: {e}")
210
 
211
  requests_made += 1
212
 
@@ -223,168 +198,65 @@ def format_weather_data(df):
223
  code = str(int(row["weather_code"]))
224
  tod = "day" if row["is_day"] == 1 else "night"
225
  info = icons.get(code, {}).get(tod, {})
226
- icon_filename = info.get("icon", "")
227
- description = info.get("description", "Unknown")
228
- return ICON_URL + icon_filename, description, icon_filename
 
 
229
 
230
  df[["weather_icon_url", "weather_desc", "weather_icon_name"]] = df.apply(
231
  icon_mapper, axis=1, result_type="expand"
232
  )
 
233
  df["distance_km"] = (df["distance_m"] / 1000).round(1)
234
  df["temp_c_str"] = df["temp_c"].round(0).astype(int).astype(str) + "°C"
235
  return df
236
 
237
 
238
- def geocode_location(location_text):
239
- try:
240
- loc = geolocator.geocode(location_text, timeout=10)
241
- if loc:
242
- return loc.latitude, loc.longitude, f"Found: {loc.address}"
243
- return None, None, f"Location '{location_text}' not found."
244
- except Exception as e:
245
- return None, None, f"Geocoding error: {e}"
246
-
247
-
248
  # --- CORE LOGIC ---
249
 
250
  def find_snowy_peaks(min_snow_cm, radius_km, lat, lon):
251
  if lat is None or lon is None:
252
- fig = create_empty_map(DEFAULT_LAT, DEFAULT_LON)
253
- fig.update_layout(title_text="Enter valid coordinates.")
254
- return fig, "Please enter coordinates."
255
-
256
- if not (-90 <= lat <= 90 and -180 <= lon <= 180):
257
- fig = create_empty_map(DEFAULT_LAT, DEFAULT_LON)
258
- fig.update_layout(title_text="Invalid coordinates.")
259
- return fig, "Coordinates out of range."
260
 
261
  df_peaks = get_peaks_from_overpass(lat, lon, radius_km)
262
  if df_peaks.empty:
263
- fig = create_map_with_center(lat, lon)
264
- fig.update_layout(title_text=f"No peaks found within {radius_km} km.")
265
- return fig, f"No peaks found within {radius_km} km."
266
 
267
- df_peaks = df_peaks.sort_values("distance_m").reset_index(drop=True)
268
  df_weather = get_weather_for_peaks_iteratively(df_peaks, min_snow_cm)
269
-
270
  if df_weather.empty:
271
- fig = create_map_with_center(lat, lon)
272
- fig.update_layout(title_text=f"No snowy peaks ≥ {min_snow_cm} cm.")
273
- return fig, f"No peaks met the ≥ {min_snow_cm} cm snow requirement."
274
 
275
  df_final = format_weather_data(df_weather)
276
- fig = create_map_with_results(lat, lon, df_final)
277
- fig.update_layout(title_text=f"Found {len(df_final)} snowy peaks!")
278
- msg = f"🎉 Showing {len(df_final)} snowy peaks with ≥ {min_snow_cm} cm of snow."
279
- return fig, msg
280
 
281
 
282
  # --- MAP HELPERS ---
283
 
284
- def create_empty_map(lat, lon):
285
- fig = go.Figure()
286
- fig.update_layout(
287
- map=dict(style="open-street-map", center={"lat": lat, "lon": lon}, zoom=8),
288
- margin={"r": 0, "t": 40, "l": 0, "b": 0},
289
- height=1024,
290
- width=1024,
291
- )
292
- return fig
293
-
294
-
295
  def create_map_with_center(lat, lon):
296
- fig = go.Figure(
297
- go.Scattermap(
298
- lat=[lat],
299
- lon=[lon],
300
- mode="markers",
301
- marker=dict(size=24, color="white", opacity=0.8),
302
- hoverinfo="skip",
303
- )
304
- )
305
- fig.add_trace(
306
- go.Scattermap(
307
- lat=[lat],
308
- lon=[lon],
309
- mode="markers",
310
- marker=dict(size=12, color="red"),
311
- text=["Search Center"],
312
- hoverinfo="text",
313
- )
314
- )
315
- fig.update_layout(
316
- map=dict(style="open-street-map", center={"lat": lat, "lon": lon}, zoom=8),
317
- margin={"r": 0, "t": 40, "l": 0, "b": 0},
318
- height=1024,
319
- width=1024,
320
- )
321
  return fig
322
 
323
 
324
- def create_map_with_results(lat, lon, df_final):
325
  fig = go.Figure()
326
-
327
- # Add white halos for peaks
328
- fig.add_trace(
329
- go.Scattermap(
330
- lat=df_final["latitude"],
331
- lon=df_final["longitude"],
332
- mode="markers",
333
- marker=dict(size=24, color="white", opacity=0.8),
334
- hoverinfo="skip",
335
- )
336
- )
337
-
338
- # Add peak markers with weather info in hover (no HTML icons)
339
- fig.add_trace(
340
- go.Scattermap(
341
- lat=df_final["latitude"],
342
- lon=df_final["longitude"],
343
- mode="markers",
344
- marker=dict(size=12, color="blue"),
345
- customdata=df_final[
346
- ["name", "altitude", "distance_km", "snow_depth_cm", "weather_desc",
347
- "temp_c_str"]
348
- ],
349
- hovertemplate=(
350
- "<b>%{customdata[0]}</b><br>"
351
- "Altitude: %{customdata[1]} m<br>"
352
- "Distance: %{customdata[2]} km<br>"
353
- "<b>❄️ Snow: %{customdata[3]} cm</b><br>"
354
- "Weather: %{customdata[4]}<br>"
355
- "🌡 Temp: %{customdata[5]}<extra></extra>"
356
- ),
357
- )
358
- )
359
-
360
- # Add search center with halo
361
- fig.add_trace(
362
- go.Scattermap(
363
- lat=[lat],
364
- lon=[lon],
365
- mode="markers",
366
- marker=dict(size=24, color="white", opacity=0.8),
367
- hoverinfo="skip",
368
- )
369
- )
370
- fig.add_trace(
371
- go.Scattermap(
372
- lat=[lat],
373
- lon=[lon],
374
- mode="markers",
375
- marker=dict(size=12, color="red"),
376
- text=["Search Center"],
377
- hoverinfo="text",
378
- )
379
- )
380
-
381
- fig.update_layout(
382
- map=dict(style="open-street-map", center={"lat": lat, "lon": lon}, zoom=9),
383
- margin={"r": 0, "t": 40, "l": 0, "b": 0},
384
- height=1024,
385
- width=1024,
386
- showlegend=False,
387
- )
388
  return fig
389
 
390
 
@@ -392,32 +264,19 @@ def create_map_with_results(lat, lon, df_final):
392
 
393
  with gr.Blocks(theme=gr.themes.Soft(), title="Snow Finder") as demo:
394
  gr.Markdown("# ☃️ Snow Finder for Families")
395
- gr.Markdown("Find nearby snowy peaks perfect for sledding and snowmen!")
396
-
397
- with gr.Row():
398
- with gr.Column(scale=1):
399
- location_search = gr.Textbox(label="Search Location")
400
- search_location_btn = gr.Button("🔍 Find Location")
401
-
402
- lat_input = gr.Number(value=DEFAULT_LAT, label="Latitude", precision=4)
403
- lon_input = gr.Number(value=DEFAULT_LON, label="Longitude", precision=4)
404
- snow_slider = gr.Radio(choices=[1, 2, 3, 4, 5, 6], value=1, label="Min Snow (cm)")
405
- radius_slider = gr.Radio(choices=[10, 20, 30, 40, 50, 60], value=30, label="Radius (km)")
406
- search_button = gr.Button("❄️ Find Snow!", variant="primary")
407
- status_output = gr.Textbox(lines=4, interactive=False)
408
-
409
- with gr.Column(scale=2):
410
- init_fig = create_map_with_center(DEFAULT_LAT, DEFAULT_LON)
411
- init_fig.update_layout(title_text="Luxembourg City – Click 'Find Snow!' to start")
412
- map_plot = gr.Plot(init_fig, label="Map")
413
-
414
- search_location_btn.click(
415
- fn=geocode_location, inputs=[location_search], outputs=[lat_input, lon_input, status_output]
416
- )
417
  search_button.click(
418
  fn=find_snowy_peaks,
419
  inputs=[snow_slider, radius_slider, lat_input, lon_input],
420
- outputs=[map_plot, status_output],
421
  )
422
 
423
  if __name__ == "__main__":
 
 
 
1
  import gradio as gr
2
  import pandas as pd
3
  import numpy as np
 
30
  ICON_URL = "https://raw.githubusercontent.com/basmilius/weather-icons/refs/heads/dev/production/fill/svg/"
31
 
32
  DEFAULT_LAT, DEFAULT_LON = 49.6116, 6.1319
33
+ MIN_ALTITUDE_M = 300
34
+ MAX_PEAKS = 100
35
 
36
 
37
  # --- UTILS ---
38
 
39
  def compute_bbox(lat, lon, dist_km):
 
 
 
40
  lat_delta = dist_km / 111.0
41
  lon_delta = dist_km / (111.0 * np.cos(np.radians(lat)))
42
+
43
+ south = max(lat - lat_delta, -90)
44
+ north = min(lat + lat_delta, 90)
45
  west = lon - lon_delta
46
  east = lon + lon_delta
47
+
 
48
  if west < -180:
49
  west += 360
50
  if east > 180:
51
  east -= 360
52
+
 
 
 
 
53
  return f"{south},{west},{north},{east}"
54
 
55
 
56
  def get_elevation_from_srtm(lat, lon):
 
57
  if lat is None or lon is None:
58
  return None
59
+
 
60
  if -56 <= lat <= 60:
61
  try:
62
  alt = elevation_data.get_elevation(lat, lon)
63
+ if alt and alt > 0:
64
  return alt
65
+ except Exception:
66
+ pass
67
+
68
  return None
69
 
70
 
71
  def get_peaks_from_overpass(lat, lon, dist_km):
 
72
  bbox = compute_bbox(lat, lon, dist_km)
73
+
74
  query = f"""
75
+ [out:json];
76
+ (
77
+ nwr[natural=peak]({bbox});
78
+ nwr[natural=hill]({bbox});
79
+ );
80
+ out body;
81
  """
82
+
83
  try:
84
  r = requests.get(OVERPASS_URL, params={"data": query}, timeout=30)
85
  r.raise_for_status()
 
88
  print(f"Error fetching peaks: {e}")
89
  return pd.DataFrame()
90
 
91
+ rows = []
92
+
 
 
 
93
  for e in data.get("elements", []):
 
 
 
 
94
  lat_e, lon_e = e.get("lat"), e.get("lon")
 
 
95
  if lat_e is None or lon_e is None:
 
96
  continue
97
+
98
  tags = e.get("tags", {})
99
  alt = None
100
+
 
101
  ele = tags.get("ele")
102
  if ele and str(ele).replace(".", "").replace("-", "").isnumeric():
103
  alt = float(ele)
104
+
105
+ if alt is None or alt <= 0:
 
106
  alt = get_elevation_from_srtm(lat_e, lon_e)
107
+
108
+ if alt is None or alt < MIN_ALTITUDE_M:
 
 
109
  continue
110
+
111
+ rows.append({
112
+ "name": tags.get("name", "Unnamed Peak/Hill"),
113
+ "latitude": lat_e,
114
+ "longitude": lon_e,
115
+ "altitude": int(round(alt, 0)),
116
+ })
117
+
118
+ if not rows:
 
 
 
 
119
  return pd.DataFrame()
120
 
121
+ df = pd.DataFrame(rows)
122
+
 
123
  df["distance_m"] = df.apply(
124
+ lambda r: distance.distance(
125
+ (r["latitude"], r["longitude"]), (lat, lon)
126
+ ).m,
127
+ axis=1
128
  )
129
+
130
+ df = (
131
+ df.sort_values("distance_m")
132
+ .head(MAX_PEAKS)
133
+ .reset_index(drop=True)
134
+ )
135
+
136
  return df
137
 
138
 
139
+ # --- WEATHER FETCH ---
140
 
141
  def get_weather_for_peaks_iteratively(df_peaks, min_snow_cm, max_results=20, max_requests=100):
 
142
  if df_peaks.empty:
143
  return pd.DataFrame()
144
 
 
162
  responses = openmeteo.weather_api(url, params=params)
163
  if not responses:
164
  continue
165
+
166
+ hourly = responses[0].Hourly()
 
167
  if hourly is None:
168
  continue
169
 
170
  idx = 0
171
+ snow_depth_cm = float(hourly.Variables(3).ValuesAsNumpy()[idx]) * 100
 
 
 
 
 
172
 
173
  if snow_depth_cm >= min_snow_cm:
174
  results.append({
175
  **row.to_dict(),
176
+ "temp_c": float(hourly.Variables(0).ValuesAsNumpy()[idx]),
177
+ "is_day": int(hourly.Variables(1).ValuesAsNumpy()[idx]),
178
+ "weather_code": int(hourly.Variables(2).ValuesAsNumpy()[idx]),
179
+ "snow_depth_m": snow_depth_cm / 100,
180
+ "snow_depth_cm": int(round(snow_depth_cm, 0)),
181
  })
182
 
183
  except Exception as e:
184
+ print(f"Weather error for {row['name']}: {e}")
185
 
186
  requests_made += 1
187
 
 
198
  code = str(int(row["weather_code"]))
199
  tod = "day" if row["is_day"] == 1 else "night"
200
  info = icons.get(code, {}).get(tod, {})
201
+ return (
202
+ ICON_URL + info.get("icon", ""),
203
+ info.get("description", "Unknown"),
204
+ info.get("icon", "")
205
+ )
206
 
207
  df[["weather_icon_url", "weather_desc", "weather_icon_name"]] = df.apply(
208
  icon_mapper, axis=1, result_type="expand"
209
  )
210
+
211
  df["distance_km"] = (df["distance_m"] / 1000).round(1)
212
  df["temp_c_str"] = df["temp_c"].round(0).astype(int).astype(str) + "°C"
213
  return df
214
 
215
 
 
 
 
 
 
 
 
 
 
 
216
  # --- CORE LOGIC ---
217
 
218
  def find_snowy_peaks(min_snow_cm, radius_km, lat, lon):
219
  if lat is None or lon is None:
220
+ return create_map_with_center(DEFAULT_LAT, DEFAULT_LON), "Invalid coordinates."
 
 
 
 
 
 
 
221
 
222
  df_peaks = get_peaks_from_overpass(lat, lon, radius_km)
223
  if df_peaks.empty:
224
+ return create_map_with_center(lat, lon), "No peaks found."
 
 
225
 
 
226
  df_weather = get_weather_for_peaks_iteratively(df_peaks, min_snow_cm)
 
227
  if df_weather.empty:
228
+ return create_map_with_center(lat, lon), "No snowy peaks found."
 
 
229
 
230
  df_final = format_weather_data(df_weather)
231
+ return create_map_with_results(lat, lon, df_final), f"Showing {len(df_final)} snowy peaks."
 
 
 
232
 
233
 
234
  # --- MAP HELPERS ---
235
 
 
 
 
 
 
 
 
 
 
 
 
236
  def create_map_with_center(lat, lon):
237
+ fig = go.Figure(go.Scattermap(lat=[lat], lon=[lon], mode="markers"))
238
+ fig.update_layout(map=dict(style="open-street-map", center={"lat": lat, "lon": lon}, zoom=8))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
  return fig
240
 
241
 
242
+ def create_map_with_results(lat, lon, df):
243
  fig = go.Figure()
244
+ fig.add_trace(go.Scattermap(
245
+ lat=df["latitude"],
246
+ lon=df["longitude"],
247
+ mode="markers",
248
+ marker=dict(size=12, color="blue"),
249
+ customdata=df[["name", "altitude", "distance_km", "snow_depth_cm", "weather_desc", "temp_c_str"]],
250
+ hovertemplate=(
251
+ "<b>%{customdata[0]}</b><br>"
252
+ "Altitude: %{customdata[1]} m<br>"
253
+ "Distance: %{customdata[2]} km<br>"
254
+ "❄️ Snow: %{customdata[3]} cm<br>"
255
+ "Weather: %{customdata[4]}<br>"
256
+ "🌡 %{customdata[5]}<extra></extra>"
257
+ ),
258
+ ))
259
+ fig.update_layout(map=dict(style="open-street-map", center={"lat": lat, "lon": lon}, zoom=9))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
260
  return fig
261
 
262
 
 
264
 
265
  with gr.Blocks(theme=gr.themes.Soft(), title="Snow Finder") as demo:
266
  gr.Markdown("# ☃️ Snow Finder for Families")
267
+
268
+ lat_input = gr.Number(value=DEFAULT_LAT, label="Latitude")
269
+ lon_input = gr.Number(value=DEFAULT_LON, label="Longitude")
270
+ snow_slider = gr.Radio([1, 2, 3, 4, 5, 6], value=1, label="Min Snow (cm)")
271
+ radius_slider = gr.Radio([10, 20, 30, 40, 50, 60], value=30, label="Radius (km)")
272
+ search_button = gr.Button("❄️ Find Snow!")
273
+ map_plot = gr.Plot()
274
+ status = gr.Textbox()
275
+
 
 
 
 
 
 
 
 
 
 
 
 
 
276
  search_button.click(
277
  fn=find_snowy_peaks,
278
  inputs=[snow_slider, radius_slider, lat_input, lon_input],
279
+ outputs=[map_plot, status],
280
  )
281
 
282
  if __name__ == "__main__":