Dingyi6 commited on
Commit
ca7f30f
·
1 Parent(s): a655728

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +487 -132
app.py CHANGED
@@ -1,155 +1,510 @@
1
- from pathlib import Path
2
- from typing import List, Dict, Tuple
3
- import matplotlib.colors as mpl_colors
4
-
 
 
5
  import pandas as pd
6
- import seaborn as sns
7
- import shinyswatch
8
-
9
- import shiny.experimental as x
10
- from shiny import App, Inputs, Outputs, Session, reactive, render, req, ui
11
-
12
- sns.set_theme()
13
-
14
- www_dir = Path(__file__).parent.resolve() / "www"
15
-
16
- df = pd.read_csv(Path(__file__).parent / "penguins.csv", na_values="NA")
17
- numeric_cols: List[str] = df.select_dtypes(include=["float64"]).columns.tolist()
18
- species: List[str] = df["Species"].unique().tolist()
19
- species.sort()
20
-
21
- app_ui = x.ui.page_fillable(
22
- shinyswatch.theme.minty(),
23
- ui.layout_sidebar(
24
- ui.panel_sidebar(
25
- # Artwork by @allison_horst
26
- ui.input_selectize(
27
- "xvar",
28
- "X variable",
29
- numeric_cols,
30
- selected="Bill Length (mm)",
31
- ),
32
- ui.input_selectize(
33
- "yvar",
34
- "Y variable",
35
- numeric_cols,
36
- selected="Bill Depth (mm)",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  ),
38
- ui.input_checkbox_group(
39
- "species", "Filter by species", species, selected=species
 
 
 
 
40
  ),
41
- ui.hr(),
42
- ui.input_switch("by_species", "Show species", value=True),
43
- ui.input_switch("show_margins", "Show marginal plots", value=True),
44
- width=2,
45
  ),
46
- ui.panel_main(
47
- ui.output_ui("value_boxes"),
48
- x.ui.output_plot("scatter", fill=True),
49
- ui.help_text(
50
- "Artwork by ",
51
- ui.a("@allison_horst", href="https://twitter.com/allison_horst"),
52
- class_="text-end",
 
 
 
 
 
 
 
 
 
 
53
  ),
54
- ),
55
- ),
 
56
  )
57
 
 
 
 
 
 
 
58
 
59
- def server(input: Inputs, output: Outputs, session: Session):
60
- @reactive.Calc
61
- def filtered_df() -> pd.DataFrame:
62
- """Returns a Pandas data frame that includes only the desired rows"""
 
 
 
63
 
64
- # This calculation "req"uires that at least one species is selected
65
- req(len(input.species()) > 0)
66
 
67
- # Filter the rows so we only include the desired species
68
- return df[df["Species"].isin(input.species())]
 
 
 
69
 
70
- @output
71
- @render.plot
72
- def scatter():
73
- """Generates a plot for Shiny to display to the user"""
74
-
75
- # The plotting function to use depends on whether margins are desired
76
- plotfunc = sns.jointplot if input.show_margins() else sns.scatterplot
77
-
78
- plotfunc(
79
- data=filtered_df(),
80
- x=input.xvar(),
81
- y=input.yvar(),
82
- palette=palette,
83
- hue="Species" if input.by_species() else None,
84
- hue_order=species,
85
- legend=False,
86
  )
87
 
88
- @output
89
- @render.ui
90
- def value_boxes():
91
- df = filtered_df()
92
-
93
- def penguin_value_box(title: str, count: int, bgcol: str, showcase_img: str):
94
- return x.ui.value_box(
95
- title,
96
- count,
97
- {"class_": "pt-1 pb-0"},
98
- showcase=x.ui.as_fill_item(
99
- ui.tags.img(
100
- {"style": "object-fit:contain;"},
101
- src=showcase_img,
102
- )
103
- ),
104
- theme_color=None,
105
- style=f"background-color: {bgcol};",
106
- )
107
 
108
- if not input.by_species():
109
- return penguin_value_box(
110
- "Penguins",
111
- len(df.index),
112
- bg_palette["default"],
113
- # Artwork by @allison_horst
114
- showcase_img="penguins.png",
115
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
 
117
- value_boxes = [
118
- penguin_value_box(
119
- name,
120
- len(df[df["Species"] == name]),
121
- bg_palette[name],
122
- # Artwork by @allison_horst
123
- showcase_img=f"{name}.png",
 
 
 
 
 
 
124
  )
125
- for name in species
126
- # Only include boxes for _selected_ species
127
- if name in input.species()
128
- ]
129
 
130
- return x.ui.layout_column_wrap(1 / len(value_boxes), *value_boxes)
 
131
 
 
 
 
 
 
132
 
133
- # "darkorange", "purple", "cyan4"
134
- colors = [[255, 140, 0], [160, 32, 240], [0, 139, 139]]
135
- colors = [(r / 255.0, g / 255.0, b / 255.0) for r, g, b in colors]
 
 
 
 
 
 
 
 
 
 
 
 
136
 
137
- palette: Dict[str, Tuple[float, float, float]] = {
138
- "Adelie": colors[0],
139
- "Chinstrap": colors[1],
140
- "Gentoo": colors[2],
141
- "default": sns.color_palette()[0], # type: ignore
142
- }
 
 
 
 
 
 
143
 
144
- bg_palette = {}
145
- # Use `sns.set_style("whitegrid")` to help find approx alpha value
146
- for name, col in palette.items():
147
- # Adjusted n_colors until `axe` accessibility did not complain about color contrast
148
- bg_palette[name] = mpl_colors.to_hex(sns.light_palette(col, n_colors=7)[1]) # type: ignore
 
 
 
 
 
 
 
 
 
149
 
 
 
 
 
150
 
151
- app = App(
152
- app_ui,
153
- server,
154
- static_assets=str(www_dir),
155
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ from typing import Optional
4
+ from shiny import App, render, ui, reactive, req
5
+ import ipyleaflet as L
6
+ from htmltools import css
7
  import pandas as pd
8
+ import numpy as np
9
+ from shinywidgets import output_widget, reactive_read, register_widget
10
+ from geopy.geocoders import Nominatim
11
+ import json
12
+ import requests
13
+ import traceback
14
+ import io
15
+ import asyncio
16
+ import plotly.graph_objects as go
17
+ from datetime import datetime, date
18
+ import pytz
19
+ from typing import List
20
+ from shiny.types import NavSetArg
21
+ from utils import print_with_line_number, datafields
22
+ from timezonefinder import TimezoneFinder
23
+
24
+ # Add the parent directory to the Python path
25
+ parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
26
+ sys.path.append(parent_dir)
27
+
28
+ tf = TimezoneFinder()
29
+ CHOICES = ["cloudBase", "cloudCeiling", "dewPoint", "evapotranspiration", "freezingRainIntensity", "humidity", "iceAccumulation", "pressureSurfaceLevel", "rainAccumulation", "rainIntensity", "sleetAccumulation", "sleetIntensity", "snowAccumulation", "snowDepth", "snowIntensity", "temperature", "temperatureApparent", "uvHealthConcern", "uvIndex", "visibility", "windDirection", "windGust", "windSpeed"]
30
+
31
+ def getGPS():
32
+ GPSurl = 'https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyAnHc2yRD53vlzHrj7qQ6OLFiX-iGsqFyM'
33
+ data = {'homeMobileCountryCode': 310, 'homeMobileNetworkCode': 410, 'considerIp': 'True'}
34
+ response = requests.post(GPSurl, data=json.dumps(data))
35
+ result = json.loads(response.content)
36
+ return result
37
+
38
+ def handle_draw(action, geo_json, data_holder):
39
+ if geo_json['type'] == 'Feature':
40
+ # Check if the drawn shape is a polygon
41
+ if geo_json['geometry']['type'] == 'Polygon':
42
+ # Get the coordinates of the polygon's vertices
43
+ coordinates = geo_json['geometry']['coordinates'][0]
44
+
45
+ # Extract latitude and longitude values from each vertex
46
+ # For GeoJSON, coordinates are represented as [longitude, latitude]
47
+ # (note the reverse order compared to traditional [latitude, longitude])
48
+ data_holder = [(lat, lon) for lon, lat in coordinates]
49
+
50
+ print(data_holder)
51
+
52
+ # # Function to handle the polygon data received from the frontend
53
+ # def handle_polygon(data):
54
+ # # Process and display the data as needed
55
+ # return data
56
+
57
+ def get_location(lat, lon):
58
+ geolocator = Nominatim(user_agent="when-to-fly")
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 [
96
+ # ui.nav("When to Fly",
97
+ # ),
98
+ ui.nav("Custome Garphics",
99
+ ui.panel_title("Customize your weather data"),
100
+ ui.div(
101
+ ui.input_slider("zoom", "Map zoom level", value=12, min=1, max=18),
102
+ ui.input_numeric("lat", "Latitude", value=38.53667742),
103
+ ui.input_numeric("long", "Longitude", value=-121.75387309),
104
+ ui.help_text("Click to select location"),
105
+ ui.output_ui("map_bounds"),
106
+ style=css(
107
+ display="flex", justify_content="center", align_items="center", gap="2rem"
108
+ ),
109
+ ),
110
+ output_widget("map"),
111
+ ui.layout_sidebar(
112
+ ui.panel_sidebar(
113
+ ui.input_selectize("items", "Select up to 4 items you want to show in your graph", choices=CHOICES, multiple = True),
114
+ ui.input_action_button("do_plot", "Plot", class_="btn-success"),
115
+ ),
116
+ ui.panel_main(
117
+ ui.div(
118
+ ui.strong("cloudCover(%)"),
119
+ ui.span(": The fraction of the sky obscured by clouds when observed from a particular location. The part with a red shadow in the figure indicates that the value is greater than or equal to 25%, and it is "),
120
+ ui.strong("not recommended"),
121
+ " to travel at this time."
122
+ ),
123
+ ui.div(
124
+ ui.strong("precipitationProbability(%)"),
125
+ ui.span(": Probability of precipitation represents the chance of >0.0254 cm (0.01 in.) of liquid equivalent precipitation at a radius surrounding a point location over a specific period of time.")
126
+ ),
127
+ ui.div(
128
+ ui.a("See all data field details.", href="https://docs.google.com/document/d/1fmiUYToF2YElzNvPT3_Zo8dBc9kzGgWJZGj14yWx2Bo/edit?usp=sharing")
129
+ ),
130
+ ui.output_ui("info_html")
131
+ )
132
+ ),
133
+ output_widget("plot_weather"),
134
+ ),
135
+ ui.nav("Download data",
136
+ ui.input_text(id="address", label="Data for", value="", width='100%'),
137
+ ui.output_data_frame("weather_frame"),
138
+ ui.download_button("download_weather", "Download Data as csv", class_="btn-success"),
139
+ ),
140
+ ui.nav("Legal Area",
141
+ ),
142
+ ui.nav_spacer(),
143
+ ui.nav_menu(
144
+ "Other links",
145
+ ui.nav_control(
146
+ ui.a(
147
+ "shiny for Python",
148
+ href="https://rstudio.com",
149
+ target="_blank",
150
+ )
151
  ),
152
+ ui.nav_control(
153
+ ui.a(
154
+ "tomorrow.io(weather data)",
155
+ href="https://rstudio.com",
156
+ target="_blank",
157
+ )
158
  ),
159
+ align="right",
 
 
 
160
  ),
161
+ ]
162
+
163
+ app_ui = ui.page_fluid(
164
+ ui.page_navbar(
165
+ *nav_controls("page_navbar"),
166
+ title="My Views",
167
+ bg="#006400",
168
+ inverse=True,
169
+ id="navbar_id",
170
+ footer=ui.div(
171
+ {"style": "width:80%;margin: 0 auto"},
172
+ ui.tags.style(
173
+ """
174
+ h4 {
175
+ margin-top: 3em;
176
+ }
177
+ """
178
  ),
179
+ # ui.navset_pill_card(*nav_controls("navset_pill_card()")),
180
+ )
181
+ )
182
  )
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...",
193
+ easy_close=False,
194
+ size="s",
195
+ footer=None,
196
+ fade=True
197
+ )
198
 
 
 
199
 
200
+ def plot_weather(fig, weather_data, items) -> go.Figure:
201
+ # if map_initialized:
202
+ # print_with_line_number("Show plotting modal")
203
+ # ui.modal_show(m)
204
+ time = weather_data['time'].values
205
 
206
+ fig.update_layout(
207
+ xaxis_title='Datetime',
 
 
 
 
 
 
 
 
 
 
 
 
 
 
208
  )
209
 
210
+ cloud_coverage = weather_data["cloudCover"].copy()
211
+ cloud_coverage[cloud_coverage < 0.25] = 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
 
213
+ fig.add_trace(go.Scatter(
214
+ x = time,
215
+ y = cloud_coverage,
216
+ name = "cloudCover",
217
+ fill='tozeroy',
218
+ marker_color ='indianred',
219
+ opacity = 0.3
220
+ ))
221
+
222
+ fig.update_layout(**{"yaxis": {"title":"cloudCover(%)", "side":"left"}}, overwrite=False)
223
+
224
+
225
+ fig.add_trace(go.Bar(
226
+ x = time,
227
+ y = weather_data["precipitationProbability"].values,
228
+ name = "precipitationProbability",
229
+ yaxis = "y2",
230
+ marker_color ='rgb(158,202,225)',
231
+ marker_line_color = 'rgb(8,48,107)',
232
+ marker_line_width = 1.5,
233
+ opacity = 0.6
234
+ ))
235
+
236
+ fig.update_layout(**{"yaxis2":
237
+ {
238
+ "title":"precipitationProbability(%)",
239
+ "anchor": "free",
240
+ "overlaying": "y",
241
+ "side": "right",
242
+ "autoshift": True,
243
+ }}
244
+ , overwrite=False)
245
+
246
+ count = 3
247
+ pos = ["right", "left"]
248
+ for item in items:
249
+
250
+ y_axis_key = f"yaxis{count}"
251
+ yname = f"y{count}"
252
 
253
+ fig.add_trace(go.Scatter(
254
+ x = time,
255
+ y = weather_data[item].values,
256
+ name = item,
257
+ yaxis = yname
258
+ ))
259
+
260
+ y_axis_params = dict(
261
+ title = datafields[item],
262
+ anchor="free",
263
+ overlaying="y", # 将overlaying属性设置为None,避免y轴之间重叠
264
+ side = pos[count % 2],
265
+ autoshift=True,
266
  )
267
+
268
+ fig.update_layout(**{y_axis_key: y_axis_params}, overwrite=False)
269
+ count += 1
 
270
 
271
+ # Adjust legend position to the top # Set a default height
272
+ fig.update_layout(legend=dict(y=1.1, yanchor="top", orientation="h"), height=800)
273
 
274
+ # print_with_line_number(fig)
275
+
276
+ # if map_initialized:
277
+ # print_with_line_number("Remove plotting modal")
278
+ # ui.modal_remove()
279
 
280
+ return fig
281
+
282
+
283
+ try:
284
+ print_with_line_number("Show initializing modal")
285
+ ui.modal_show(m)
286
+ map_initialized = False
287
+
288
+ # Initialize and display when the session starts (1)
289
+ map = L.Map(center=(38.53667742, -121.75387309), zoom=12, scroll_wheel_zoom=True)
290
+ map.add_layer(L.TileLayer(url='https://mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={z}', name='Natural Map'))
291
+ with reactive.isolate():
292
+ marker = L.Marker(location=(input.lat() or 38.53667742 , input.long() or -121.75387309), name='Marker')
293
+ control = L.LayersControl(position='topright')
294
+ map.add_control(control)
295
 
296
+ @reactive.isolate()
297
+ def update_text_inputs(lat: Optional[float], long: Optional[float]) -> None:
298
+ req(lat is not None, long is not None)
299
+ lat = round(lat, 8)
300
+ long = round(long, 8)
301
+ if lat != input.lat():
302
+ input.lat.freeze()
303
+ ui.update_text("lat", value=lat)
304
+ if long != input.long():
305
+ input.long.freeze()
306
+ ui.update_text("long", value=long)
307
+ map.center = (lat, long)
308
 
309
+ @reactive.isolate()
310
+ def update_marker(lat: Optional[float], long: Optional[float]) -> None:
311
+ req(lat is not None, long is not None)
312
+ lat = round(lat, 8)
313
+ long = round(long, 8)
314
+ if marker.location != (lat, long):
315
+ marker.location = (lat, long)
316
+ if marker not in map.layers:
317
+ map.add_layer(marker)
318
+ map.center = marker.location
319
+
320
+ @reactive.Effect
321
+ def sync_inputs_to_marker():
322
+ update_marker(input.lat(), input.long())
323
 
324
+ def on_map_interaction(**kwargs):
325
+ if kwargs.get("type") == "click":
326
+ lat, long = kwargs.get("coordinates")
327
+ update_text_inputs(lat, long)
328
 
329
+
330
+ # Get the user's current geoinformation
331
+ current_gps = getGPS()
332
+ update_text_inputs(current_gps['location']['lat'], current_gps['location']['lng'])
333
+
334
+ # ui.update_numeric("lat", value=current_gps['location']['lat'])
335
+ # ui.update_numeric("long", value=current_gps['location']['lng'])
336
+ # print("Input: ", input.lat(), input.long())
337
+
338
+ print_with_line_number(current_gps)
339
+ current_location = get_location(current_gps['location']['lat'], current_gps['location']['lng'])
340
+ print_with_line_number(current_location)
341
+ ui.update_text(id="address",
342
+ label="Data for",
343
+ value=current_location)
344
+
345
+
346
+ map.on_interaction(on_map_interaction)
347
+ # Add a distance scale
348
+ map.add_control(L.leaflet.ScaleControl(position="bottomleft"))
349
+ register_widget("map", map)
350
+
351
+
352
+ # Fetch weather data
353
+ # await check(weather_data, current_gps['location']['lat'], current_gps['location']['lng'])
354
+ print_with_line_number(weather_data)
355
+ weather_data = check(weather_data, current_gps['location']['lat'], current_gps['location']['lng'])
356
+ # choices = weather_data.columns.tolist()
357
+ # print(choices)
358
+ print_with_line_number("Finish fetching hourly data!")
359
+
360
+ # In your server function, create the initial fig
361
+ weather_fig = go.Figure()
362
+
363
+ # Call plot_weather to initialize the plot
364
+ plot_weather(weather_fig, weather_data, [])
365
+ register_widget("plot_weather", weather_fig)
366
+
367
+ print_with_line_number("Finish plotting selected data!")
368
+
369
+ map_initialized = True
370
+
371
+ print_with_line_number("Remove initializing modal")
372
+ ui.modal_remove()
373
+
374
+ except Exception as e:
375
+ ui.modal_remove()
376
+ error_modal = ui.modal(
377
+ str(e),
378
+ title="An Error occured, Please refresh",
379
+ easy_close=True,
380
+ size="xl",
381
+ footer=None,
382
+ fade=True
383
+ )
384
+ # print_with_line_number("Show error modal")
385
+ ui.modal_show(error_modal)
386
+ traceback.print_exc()
387
+
388
+ @reactive.Calc
389
+ def location():
390
+ """Returns tuple of (lat,long) floats--or throws silent error if no lat/long is
391
+ selected"""
392
+
393
+ # Require lat/long to be populated before we can proceed
394
+ req(input.lat() is not None, input.long() is not None)
395
+
396
+ try:
397
+ long = input.long()
398
+ # Wrap longitudes so they're within [-180, 180]
399
+ long = (long + 180) % 360 - 180
400
+ return (input.lat(), long)
401
+ except ValueError:
402
+ raise ValueError("Invalid latitude/longitude specification")
403
+
404
+ # When the slider changes, update the map's zoom attribute (2)
405
+ @reactive.Effect
406
+ def _():
407
+ if not map_initialized:
408
+ return
409
+ map.zoom = input.zoom()
410
+
411
+ # When zooming directly on the map, update the slider's value (2 and 3)
412
+ @reactive.Effect
413
+ def _():
414
+ if not map_initialized:
415
+ return
416
+ ui.update_slider("zoom", value=reactive_read(map, "zoom"))
417
+
418
+
419
+ @reactive.Effect
420
+ def _():
421
+ print("Current navbar page: ", input.navbar_id())
422
+
423
+ # Everytime the map's bounds change, update the output message (3)
424
+ # rerun when a user do some reactive changes.
425
+ @reactive.Effect
426
+ async def map_bounds():
427
+ if not map_initialized:
428
+ return
429
+ global weather_data, remap_flag
430
+ print("Change bounds")
431
+ center = location()
432
+
433
+ # center = reactive_read(map, "center")
434
+ # if len(center) == 0:
435
+ # return
436
+ # lat = round(center[0], 4)
437
+ # lon = (center[1] + 180) % 360 - 180
438
+ # lon = round(lon, 4)
439
+
440
+ # print_with_line_number("Some weather data")
441
+ # print(center, lat, lon)
442
+ if (remap_flag):
443
+ # print_with_line_number("remap weather_data")
444
+ weather_data = check(weather_data, center[0], center[1])
445
+ # print_with_line_number("Updating hourly data!")
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():
452
+ global weather_fig, weather_data
453
+ # Assuming you have updated the weather_data with new data
454
+ # For example: weather_data = updated_weather_data()
455
+ # Call plot_weather to update the plot with the new weather_data
456
+ weather_fig = go.Figure()
457
+ plot_weather(weather_fig, weather_data, input.items())
458
+ register_widget("plot_weather", weather_fig)
459
+
460
+
461
+ @reactive.Effect
462
+ @reactive.event(input.items)
463
+ def _():
464
+ global remap_flag
465
+ remap_flag = False
466
+ transfer = list(input.items())
467
+ if (len(transfer) > 4 ):
468
+ transfer.pop()
469
+ ui.notification_show("At most four options can be selected!", type="warning")
470
+ ui.update_selectize(
471
+ "items",
472
+ choices = CHOICES,
473
+ selected=transfer,
474
+ server=True,
475
+ )
476
+ # print(input.items())
477
+
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"
485
+ )
486
+ async def download_weather():
487
+ # This version uses a function to generate the filename. It also yields data
488
+ # multiple times.
489
+ await asyncio.sleep(0.25)
490
+ # Create a BytesIO buffer
491
+ with io.BytesIO() as buf:
492
+ # Write the DataFrame to the buffer as CSV
493
+ weather_data.to_csv(buf, index=False)
494
+ buf.seek(0) # Move the buffer's position to the beginning
495
+
496
+ # Return the buffer's content as a downloadable file
497
+ yield buf.getvalue()
498
+
499
+ # Use reactive.event() to invalidate the plot only when the button is pressed
500
+ # (not when the slider is changed)
501
+ @reactive.Effect
502
+ @reactive.event(input.do_plot, ignore_none=True, ignore_init=True)
503
+ def _():
504
+ global remap_flag
505
+ # print_with_line_number("In revisving")
506
+ update_plot()
507
+ remap_flag = True
508
+
509
+
510
+ app = App(app_ui, server)