Dingyi6 commited on
Commit
43d4df8
·
1 Parent(s): 7ddcd31

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -33
app.py CHANGED
@@ -59,37 +59,6 @@ def get_location(lat, lon):
59
  location = geolocator.reverse(f"{lat},{lon}")
60
  return location.address
61
 
62
- def check(weather_data, lat, lon):
63
- # Get current local Time
64
- timezone = tf.timezone_at(lng=lon, lat=lat)
65
- current_time = datetime.now(pytz.timezone(timezone))
66
-
67
- def convert_to_local_time(utc_time):
68
- dt = datetime.strptime(utc_time, "%Y-%m-%dT%H:%M:%SZ")
69
- local_time = dt.astimezone(pytz.timezone(timezone))
70
- return local_time.strftime("%Y-%m-%d %H")
71
-
72
- # # Check if it's on time locally
73
- # if(weather_data == None or (current_time.minute == 0 and current_time.second == 0)):
74
- weather_url = f"https://api.tomorrow.io/v4/weather/forecast?location={lat},{lon}&apikey=Purg6j6hjn9LdzMVwRvToPbJVhnlSjAP"
75
- response = requests.get(weather_url)
76
- if response.status_code != 200:
77
- raise Exception(f"Error fetching {weather_url}: {response.status_code}")
78
- api_data = response.json()
79
- hourly_data = api_data['timelines']['hourly']
80
- weather_data = pd.DataFrame([{**{'time': item['time']}, **item['values']} for item in hourly_data])
81
- weather_data.fillna(0, inplace=True)
82
-
83
- # Using convert_to_local_time to process the column 'time' data into local datetime string
84
- weather_data['time'] = weather_data['time'].apply(convert_to_local_time)
85
- weather_data['datetime'] = weather_data['time'].copy()
86
- weather_data.set_index('datetime', inplace=True)
87
-
88
- print_with_line_number("Weather dataframe:")
89
- # print(weather_data.shape)
90
- # print(weather_data.head(5))
91
-
92
- return weather_data
93
 
94
  def nav_controls(prefix: str) -> List[NavSetArg]:
95
  return [
@@ -183,10 +152,45 @@ app_ui = ui.page_fluid(
183
 
184
  # re-run when a user using the application
185
  def server(input, output, session):
186
- global weather_data, remap_flag, address_line, weather_fig, m, unisession
187
  weather_data = None
188
  remap_flag = False
189
  address_line = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
 
191
  m = ui.modal(
192
  "Please wait for progress...",
@@ -446,6 +450,11 @@ def server(input, output, session):
446
  update_plot()
447
  remap_flag = True
448
 
 
 
 
 
 
449
  # return ui.p(f"Latitude: {lat}", ui.br(), f"Longitude: {lon}")
450
 
451
  def update_plot():
@@ -478,7 +487,7 @@ def server(input, output, session):
478
  @output
479
  @render.data_frame
480
  async def weather_frame():
481
- return weather_data
482
 
483
  @session.download(
484
  filename=lambda: f"data-{date.today().isoformat()}-{np.random.randint(100,999)}.csv"
 
59
  location = geolocator.reverse(f"{lat},{lon}")
60
  return location.address
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
  def nav_controls(prefix: str) -> List[NavSetArg]:
64
  return [
 
152
 
153
  # re-run when a user using the application
154
  def server(input, output, session):
155
+ global weather_data, remap_flag, address_line, weather_fig, m
156
  weather_data = None
157
  remap_flag = False
158
  address_line = None
159
+ weatherframe = reactive.Value(pd.DataFrame())
160
+
161
+ def check(weather_data, lat, lon):
162
+ # Get current local Time
163
+ timezone = tf.timezone_at(lng=lon, lat=lat)
164
+ current_time = datetime.now(pytz.timezone(timezone))
165
+
166
+ def convert_to_local_time(utc_time):
167
+ dt = datetime.strptime(utc_time, "%Y-%m-%dT%H:%M:%SZ")
168
+ local_time = dt.astimezone(pytz.timezone(timezone))
169
+ return local_time.strftime("%Y-%m-%d %H")
170
+
171
+ # # Check if it's on time locally
172
+ # if(weather_data == None or (current_time.minute == 0 and current_time.second == 0)):
173
+ weather_url = f"https://api.tomorrow.io/v4/weather/forecast?location={lat},{lon}&apikey=Purg6j6hjn9LdzMVwRvToPbJVhnlSjAP"
174
+ response = requests.get(weather_url)
175
+ if response.status_code != 200:
176
+ raise Exception(f"Error fetching {weather_url}: {response.status_code}")
177
+ api_data = response.json()
178
+ hourly_data = api_data['timelines']['hourly']
179
+ weather_data = pd.DataFrame([{**{'time': item['time']}, **item['values']} for item in hourly_data])
180
+ weather_data.fillna(0, inplace=True)
181
+
182
+ # Using convert_to_local_time to process the column 'time' data into local datetime string
183
+ weather_data['time'] = weather_data['time'].apply(convert_to_local_time)
184
+ weather_data['datetime'] = weather_data['time'].copy()
185
+ weather_data.set_index('datetime', inplace=True)
186
+
187
+ print_with_line_number("Weather dataframe:")
188
+ # print(weather_data.shape)
189
+ # print(weather_data.head(5))
190
+ weatherframe.set(weather_data)
191
+
192
+ return weather_data
193
+
194
 
195
  m = ui.modal(
196
  "Please wait for progress...",
 
450
  update_plot()
451
  remap_flag = True
452
 
453
+ new_location = get_location(center[0], center[1])
454
+ ui.update_text(id="address",
455
+ label="Data for",
456
+ value=new_location)
457
+
458
  # return ui.p(f"Latitude: {lat}", ui.br(), f"Longitude: {lon}")
459
 
460
  def update_plot():
 
487
  @output
488
  @render.data_frame
489
  async def weather_frame():
490
+ return weatherframe.get()
491
 
492
  @session.download(
493
  filename=lambda: f"data-{date.today().isoformat()}-{np.random.randint(100,999)}.csv"