mirix commited on
Commit
bc1f905
·
verified ·
1 Parent(s): 9f4801c

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -171
app.py CHANGED
@@ -1,11 +1,10 @@
1
  import os
2
  import json
3
  import pathlib
4
- import mimetypes
5
  import gpxpy
6
  import pandas as pd
7
  import gradio as gr
8
- from datetime import datetime, timedelta
9
 
10
  import pytz
11
  from sunrisesunset import SunriseSunset
@@ -28,7 +27,7 @@ from apscheduler.schedulers.background import BackgroundScheduler
28
 
29
  ### Default variables ###
30
 
31
- # Met no weather forecast API
32
  url = 'https://api.met.no/weatherapi/locationforecast/2.0/complete'
33
  headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36'}
34
 
@@ -48,28 +47,11 @@ css = '''
48
  box-shadow: 0 0 0 12px DarkGoldenrod;
49
  }
50
  '''
51
- # Default coordinates
52
- params = {'lat': 49.6108, 'lon': 6.1326, 'altitude': 310}
53
- lat=params['lat']
54
- lon=params['lon']
55
- altitude=params['altitude']
56
 
57
  # Default GPX if none is uploaded
58
- #directory = os.path.dirname(os.path.abspath(__file__))
59
  gpx_file = os.path.join(os.getcwd(), 'default_gpx.gpx')
60
  gpx_path = pathlib.Path(gpx_file)
61
 
62
- '''
63
- # Default dates
64
- #forecast_days = 3
65
- today = datetime.today()
66
- day_read = today.strftime('%A %-d %B')
67
- day_print = '<h2>' + day_read + '</h2>'
68
- dates_read = [(today + timedelta(days=x)).strftime('%A %-d %B %Y') for x in range(forecast_days)]
69
- dates_filt = [(today + timedelta(days=x)).strftime('%Y-%m-%d') for x in range(forecast_days)]
70
- dates_dict = dict(zip(dates_read, dates_filt))
71
- dates_list = list(dates_dict.keys())
72
- '''
73
 
74
  ### Functions ###
75
 
@@ -91,62 +73,9 @@ def rain_intensity(precipt):
91
  rain = ''
92
  return rain
93
 
94
- # Generate dates for which the forecast is available
95
- # (today plus 10 days ahead)
96
-
97
- '''
98
- def gen_dates():
99
-
100
- global dates_dict
101
- global dates_list
102
- global day_read
103
- global today
104
-
105
- today = datetime.today()
106
- day_read = today.strftime('%A %-d %B')
107
- dates_read = [(today + timedelta(days=x)).strftime('%A %-d %B %Y') for x in range(forecast_days)]
108
- dates_filt = [(today + timedelta(days=x)).strftime('%Y-%m-%d') for x in range(forecast_days)]
109
- dates_dict = dict(zip(dates_read, dates_filt))
110
- dates_list = list(dates_dict.keys())
111
- return dates_dict
112
- '''
113
-
114
- def gen_dates():
115
-
116
- global dates_filt
117
- global dates_dict
118
- global dates_list
119
- global day_read
120
- global today
121
-
122
- today = datetime.today()
123
- day_read = today.strftime('%A %-d %B')
124
-
125
- resp = requests.get(url=url, headers=headers, params=params)
126
- data = resp.json()
127
-
128
- dates_aval = []
129
- for d in data['properties']['timeseries']:
130
- if 'next_1_hours' in d['data']:
131
- date = datetime.strptime(d['time'], '%Y-%m-%dT%H:%M:%SZ')
132
- dates_aval.append(date.date())
133
-
134
- dates_aval = sorted(set(dates_aval))
135
-
136
- if len(dates_aval) > 3:
137
- dates_aval = dates_aval[:3]
138
-
139
- dates_read = [x.strftime('%A %-d %B %Y') for x in dates_aval]
140
- dates_filt = [x.strftime('%Y-%m-%d') for x in dates_aval]
141
-
142
-
143
- dates_dict = dict(zip(dates_read, dates_filt))
144
- dates_list = list(dates_dict.keys())
145
-
146
- return dates_dict
147
-
148
  def gen_dates_list():
149
 
 
150
  global dates_filt
151
  global dates_dict
152
  global dates_list
@@ -155,6 +84,7 @@ def gen_dates_list():
155
 
156
  today = datetime.today()
157
  day_read = today.strftime('%A %-d %B')
 
158
 
159
  resp = requests.get(url=url, headers=headers, params=params)
160
  data = resp.json()
@@ -179,52 +109,6 @@ def gen_dates_list():
179
 
180
  return dates_list
181
 
182
- def gen_dropdown():
183
-
184
- global dates_filt
185
- global dates_dict
186
- global dates_list
187
- global day_read
188
- global today
189
-
190
- today = datetime.today()
191
- day_read = today.strftime('%A %-d %B')
192
-
193
- resp = requests.get(url=url, headers=headers, params=params)
194
- data = resp.json()
195
-
196
- dates_aval = []
197
- for d in data['properties']['timeseries']:
198
- if 'next_1_hours' in d['data']:
199
- date = datetime.strptime(d['time'], '%Y-%m-%dT%H:%M:%SZ')
200
- dates_aval.append(date.date())
201
-
202
- dates_aval = sorted(set(dates_aval))
203
-
204
- if len(dates_aval) > 3:
205
- dates_aval = dates_aval[:3]
206
-
207
- dates_read = [x.strftime('%A %-d %B %Y') for x in dates_aval]
208
- dates_filt = [x.strftime('%Y-%m-%d') for x in dates_aval]
209
-
210
-
211
- dates_dict = dict(zip(dates_read, dates_filt))
212
- dates_list = list(dates_dict.keys())
213
-
214
- dates = gr.Dropdown(choices=dates_list, label='2. Pick up the date of your hike', value=dates_list[0], interactive=True, elem_classes='required-dropdown')
215
-
216
- return dates
217
-
218
- # Default dates
219
- #forecast_days = 3
220
- today = datetime.today()
221
- day_read = today.strftime('%A %-d %B')
222
- day_print = '<h2>' + day_read + '</h2>'
223
- dates_dict = gen_dates()
224
- dates_list = list(dates_dict.keys())
225
- dates_read = list(dates_dict.keys())
226
- dates_filt = list(dates_dict.values())
227
-
228
  def sunrise_sunset(lat, lon, day):
229
 
230
  tz = tf.timezone_at(lng=lon, lat=lat)
@@ -246,17 +130,11 @@ def sunrise_sunset(lat, lon, day):
246
 
247
  return sunrise, sunset
248
 
249
- sunrise, sunset = sunrise_sunset(lat, lon, today)
250
-
251
  # Download the JSON and filter it per date
252
  def json_parser(date):
253
 
254
  global dfs
255
- #global dates_dict
256
- #global dates_list
257
 
258
- #dates_dict = gen_dates()
259
- #dates_list = list(dates_dict.keys())
260
  resp = requests.get(url=url, headers=headers, params=params)
261
  data = resp.json()
262
 
@@ -264,12 +142,9 @@ def json_parser(date):
264
 
265
  dict_weather = {'Time': [], 'Weather': [], 'Weather outline': [], 'Temp (°C)': [], 'Rain (mm/h)': [], 'Rain level': [], 'Wind (m/s)': [], 'Wind level': [] }
266
 
267
-
268
- #av_dates = []
269
  for d in data['properties']['timeseries']:
270
  date = datetime.strptime(d['time'], '%Y-%m-%dT%H:%M:%SZ')
271
  date_read = date.strftime('%Y-%m-%d')
272
- #av_dates.append(date.date())
273
 
274
  if date_read == day:
275
  dict_weather['Time'].append(date.strftime('%H'))
@@ -292,37 +167,28 @@ def json_parser(date):
292
  df['Weather outline'] = df['Weather outline'].str.capitalize().str.replace(' night','').str.replace(' day','')
293
  df[['Rain (mm/h)', 'Wind (m/s)']] = df[['Rain (mm/h)', 'Wind (m/s)']].round(1).replace({0:''}).astype(str)
294
 
295
- #df.to_csv('weather.csv', index=False)
296
-
297
  dfs = df.style.set_properties(**{'border': '0px'})
298
 
299
  return dfs
300
 
301
- dfs = json_parser(dates_filt[0])
302
-
303
  # Extract coordinates and location from GPX file
304
- # gpx_name = '1. Click the upload GPX button to begin'
305
  def coor_gpx(gpx):
306
 
307
- global gpx_name
308
- global params
309
- global lat
310
- global lon
311
- global altitude
312
- global location
313
- global dates_dict
314
- global dates_list
315
- global day_read
316
-
317
- dates_dict = gen_dates()
318
- dates_list = list(dates_dict.keys())
319
- day_read = dates_list[0]
320
- date_filt = datetime.strptime(day_read, '%A %d %B %Y')
321
- date_filt = date_filt.strftime('%Y-%m-%d')
322
- day_print = '<h2>' + day_read + '</h2>'
323
 
324
- #if mimetypes.guess_type(gpx.name)[0] in ['application/gpx+xml', 'application/xml']:
325
- try:
326
  with open(gpx.name) as f:
327
  gpx_parsed = gpxpy.parse(f)
328
  # Convert to a dataframe one point at a time.
@@ -336,7 +202,6 @@ def coor_gpx(gpx):
336
  'altitude': p.elevation,
337
  })
338
  df_gpx = pd.DataFrame.from_records(points)
339
- #df_gpx = pd.read_xml(gpx.name, xpath=".//doc:trkseg/doc:trkpt", namespaces={"doc": "http://www.topografix.com/GPX/1/1"})
340
  params = df_gpx.iloc[-1].to_dict()
341
  lat = params['lat']
342
  lon = params['lon']
@@ -346,7 +211,6 @@ def coor_gpx(gpx):
346
  else:
347
  params['altitude'] = int(round(params['altitude'], 0))
348
 
349
- #params['altitude'] = int(round(params['altitude'], 0))
350
  altitude = params['altitude']
351
 
352
  location = geolocator.reverse('{}, {}'.format(lat, lon), zoom=14)
@@ -354,26 +218,26 @@ def coor_gpx(gpx):
354
  gpx_name = 'You have uploaded <b style="color: #004170;">' + os.path.basename(gpx.name) + '</b>'
355
  location = '<p style="color: #004170">' + str(location) + '</p>'
356
 
 
 
 
 
 
 
357
  sunrise, sunset = sunrise_sunset(lat, lon, datetime.strptime(day_read, '%A %d %B %Y'))
358
 
359
  dates = gr.Dropdown(choices=dates_list, label='2. Next, pick up the date of your hike', value=dates_list[0], interactive=True, elem_classes='required-dropdown')
360
 
361
  dfs = json_parser(date_filt)
362
 
363
- return gpx_name, location, dates, day_print, sunrise, sunset, dfs
364
-
365
  except:
366
- sunrise, sunset = sunrise_sunset(lat, lon, today)
367
- dfs = json_parser(dates_filt[0])
368
  gpx_name = '<b style="color: firebrick;">ERROR: Not a valid GPX file. Upload another file.</b>'
369
- return gpx_name, location, dates_list, day_print, sunrise, sunset, dfs
370
- #else:
371
- # sunrise, sunset = sunrise_sunset(lat, lon, today)
372
- # dfs = json_parser(dates_filt[0])
373
- # gpx_name = '<b style="color: firebrick;">ERROR: Not a valid GPX file. Upload another file.</b>'
374
- # return gpx_name, location, dates_list, day_print, sunrise, sunset, dfs
375
 
376
- coor_gpx(gpx_path)
377
 
378
  # Choose a date from the dropdown menu
379
  def date_chooser(day):
@@ -385,8 +249,7 @@ def date_chooser(day):
385
  global dates_dict
386
  global dates_list
387
 
388
- dates_dict = gen_dates()
389
- dates_list = list(dates_dict.keys())
390
 
391
  day_read = day
392
  day_print = '<h2>' + day_read + '</h2>'
@@ -404,6 +267,11 @@ def date_chooser(day):
404
 
405
  return day_print, sunrise, sunset, dfs, dates
406
 
 
 
 
 
 
407
  ### Gradio app ###
408
  with gr.Blocks(theme='ParityError/Interstellar', css=css, fill_height=True) as demo:
409
  with gr.Column():
@@ -425,19 +293,16 @@ with gr.Blocks(theme='ParityError/Interstellar', css=css, fill_height=True) as d
425
  )
426
  gr.HTML('<center>Freedom Luxembourg<br><a style="color: DarkGoldenrod; font-style: italic; text-decoration: none" href="https://www.freeletz.lu/freeletz/" target="_blank">freeletz.lu</a></center>')
427
  gr.HTML('<center>Powered by the <a style="color: #004170; text-decoration: none" href="https://api.met.no/weatherapi/locationforecast/2.0/documentation" target="_blank">Norwegian Meteorological Institute</a> API</center>')
428
- #demo.load(fn=date_chooser, inputs=dates, outputs=[choosen_date, sunrise, sunset, table, dates])
429
  upload_gpx.upload(fn=coor_gpx, inputs=upload_gpx, outputs=[file_name, loc, dates, choosen_date, sunrise, sunset, table])
430
- demo.load(gen_dropdown, None, dates)
431
  dates.input(fn=date_chooser, inputs=dates, outputs=[choosen_date, sunrise, sunset, table, dates])
432
 
433
-
434
  def restart_app():
435
  demo.close()
436
  port = int(os.environ.get('PORT', 7860))
437
  demo.launch(server_name="0.0.0.0", server_port=port)
438
 
439
  scheduler = BackgroundScheduler({'apscheduler.timezone': 'Europe/Luxembourg'})
440
- scheduler.add_job(func=restart_app, trigger='cron', hour='00', minute='01')
441
  scheduler.start()
442
 
443
  port = int(os.environ.get('PORT', 7860))
 
1
  import os
2
  import json
3
  import pathlib
 
4
  import gpxpy
5
  import pandas as pd
6
  import gradio as gr
7
+ from datetime import datetime
8
 
9
  import pytz
10
  from sunrisesunset import SunriseSunset
 
27
 
28
  ### Default variables ###
29
 
30
+ # Met No weather forecast API
31
  url = 'https://api.met.no/weatherapi/locationforecast/2.0/complete'
32
  headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36'}
33
 
 
47
  box-shadow: 0 0 0 12px DarkGoldenrod;
48
  }
49
  '''
 
 
 
 
 
50
 
51
  # Default GPX if none is uploaded
 
52
  gpx_file = os.path.join(os.getcwd(), 'default_gpx.gpx')
53
  gpx_path = pathlib.Path(gpx_file)
54
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
  ### Functions ###
57
 
 
73
  rain = ''
74
  return rain
75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  def gen_dates_list():
77
 
78
+ global day_print
79
  global dates_filt
80
  global dates_dict
81
  global dates_list
 
84
 
85
  today = datetime.today()
86
  day_read = today.strftime('%A %-d %B')
87
+ day_print = '<h2>' + day_read + '</h2>'
88
 
89
  resp = requests.get(url=url, headers=headers, params=params)
90
  data = resp.json()
 
109
 
110
  return dates_list
111
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
  def sunrise_sunset(lat, lon, day):
113
 
114
  tz = tf.timezone_at(lng=lon, lat=lat)
 
130
 
131
  return sunrise, sunset
132
 
 
 
133
  # Download the JSON and filter it per date
134
  def json_parser(date):
135
 
136
  global dfs
 
 
137
 
 
 
138
  resp = requests.get(url=url, headers=headers, params=params)
139
  data = resp.json()
140
 
 
142
 
143
  dict_weather = {'Time': [], 'Weather': [], 'Weather outline': [], 'Temp (°C)': [], 'Rain (mm/h)': [], 'Rain level': [], 'Wind (m/s)': [], 'Wind level': [] }
144
 
 
 
145
  for d in data['properties']['timeseries']:
146
  date = datetime.strptime(d['time'], '%Y-%m-%dT%H:%M:%SZ')
147
  date_read = date.strftime('%Y-%m-%d')
 
148
 
149
  if date_read == day:
150
  dict_weather['Time'].append(date.strftime('%H'))
 
167
  df['Weather outline'] = df['Weather outline'].str.capitalize().str.replace(' night','').str.replace(' day','')
168
  df[['Rain (mm/h)', 'Wind (m/s)']] = df[['Rain (mm/h)', 'Wind (m/s)']].round(1).replace({0:''}).astype(str)
169
 
 
 
170
  dfs = df.style.set_properties(**{'border': '0px'})
171
 
172
  return dfs
173
 
 
 
174
  # Extract coordinates and location from GPX file
 
175
  def coor_gpx(gpx):
176
 
177
+ def parse_gpx(gpx):
178
+
179
+ global gpx_name
180
+ global params
181
+ global lat
182
+ global lon
183
+ global altitude
184
+ global location
185
+ global dates_dict
186
+ global dates_list
187
+ global day_read
188
+ global dates
189
+ global sunrise
190
+ global sunset
 
 
191
 
 
 
192
  with open(gpx.name) as f:
193
  gpx_parsed = gpxpy.parse(f)
194
  # Convert to a dataframe one point at a time.
 
202
  'altitude': p.elevation,
203
  })
204
  df_gpx = pd.DataFrame.from_records(points)
 
205
  params = df_gpx.iloc[-1].to_dict()
206
  lat = params['lat']
207
  lon = params['lon']
 
211
  else:
212
  params['altitude'] = int(round(params['altitude'], 0))
213
 
 
214
  altitude = params['altitude']
215
 
216
  location = geolocator.reverse('{}, {}'.format(lat, lon), zoom=14)
 
218
  gpx_name = 'You have uploaded <b style="color: #004170;">' + os.path.basename(gpx.name) + '</b>'
219
  location = '<p style="color: #004170">' + str(location) + '</p>'
220
 
221
+ dates_list = gen_dates_list()
222
+ day_read = dates_list[0]
223
+ date_filt = datetime.strptime(day_read, '%A %d %B %Y')
224
+ date_filt = date_filt.strftime('%Y-%m-%d')
225
+ day_print = '<h2>' + day_read + '</h2>'
226
+
227
  sunrise, sunset = sunrise_sunset(lat, lon, datetime.strptime(day_read, '%A %d %B %Y'))
228
 
229
  dates = gr.Dropdown(choices=dates_list, label='2. Next, pick up the date of your hike', value=dates_list[0], interactive=True, elem_classes='required-dropdown')
230
 
231
  dfs = json_parser(date_filt)
232
 
233
+ try:
234
+ parse_gpx(gpx)
235
  except:
236
+ parse_gpx(gpx_path)
237
+ global gpx_name
238
  gpx_name = '<b style="color: firebrick;">ERROR: Not a valid GPX file. Upload another file.</b>'
 
 
 
 
 
 
239
 
240
+ return gpx_name, location, dates, day_print, sunrise, sunset, dfs
241
 
242
  # Choose a date from the dropdown menu
243
  def date_chooser(day):
 
249
  global dates_dict
250
  global dates_list
251
 
252
+ dates_list = gen_dates_list()
 
253
 
254
  day_read = day
255
  day_print = '<h2>' + day_read + '</h2>'
 
267
 
268
  return day_print, sunrise, sunset, dfs, dates
269
 
270
+ # Call functions with default values
271
+ coor_gpx(gpx_path)
272
+ sunrise, sunset = sunrise_sunset(lat, lon, today)
273
+ dfs = json_parser(dates_filt[0])
274
+
275
  ### Gradio app ###
276
  with gr.Blocks(theme='ParityError/Interstellar', css=css, fill_height=True) as demo:
277
  with gr.Column():
 
293
  )
294
  gr.HTML('<center>Freedom Luxembourg<br><a style="color: DarkGoldenrod; font-style: italic; text-decoration: none" href="https://www.freeletz.lu/freeletz/" target="_blank">freeletz.lu</a></center>')
295
  gr.HTML('<center>Powered by the <a style="color: #004170; text-decoration: none" href="https://api.met.no/weatherapi/locationforecast/2.0/documentation" target="_blank">Norwegian Meteorological Institute</a> API</center>')
 
296
  upload_gpx.upload(fn=coor_gpx, inputs=upload_gpx, outputs=[file_name, loc, dates, choosen_date, sunrise, sunset, table])
 
297
  dates.input(fn=date_chooser, inputs=dates, outputs=[choosen_date, sunrise, sunset, table, dates])
298
 
 
299
  def restart_app():
300
  demo.close()
301
  port = int(os.environ.get('PORT', 7860))
302
  demo.launch(server_name="0.0.0.0", server_port=port)
303
 
304
  scheduler = BackgroundScheduler({'apscheduler.timezone': 'Europe/Luxembourg'})
305
+ scheduler.add_job(func=restart_app, trigger='cron', hour='05', minute='55')
306
  scheduler.start()
307
 
308
  port = int(os.environ.get('PORT', 7860))