bluenevus commited on
Commit
af52866
·
1 Parent(s): 2c76d0c

Update app.py via AI Editor

Browse files
Files changed (1) hide show
  1. app.py +81 -16
app.py CHANGED
@@ -51,8 +51,7 @@ BASE_URL = "http://dataservice.accuweather.com"
51
  INDEX_IDS = {
52
  "Health": 10,
53
  "Environmental": 5,
54
- "Pollen": 30,
55
- "AirQuality": 65
56
  }
57
 
58
  def get_location_key(lat, lon):
@@ -168,6 +167,40 @@ def get_indices_1day(location_key, index_id):
168
  logger.error(f"Error in get_indices_1day {index_id}: {e}")
169
  return None
170
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
  def create_current_weather_card(current):
172
  if not current:
173
  return dbc.Card([
@@ -292,12 +325,11 @@ def create_hourly_12hour_card(hourly_data):
292
  def create_environmental_indices_card(indices_dict):
293
  items = []
294
  index_display_names = {
295
- "Health": "Health API",
296
- "Environmental": "Environmental API",
297
- "Pollen": "Pollen",
298
- "AirQuality": "International Air Quality"
299
  }
300
- for key in ["Health", "Environmental", "Pollen", "AirQuality"]:
301
  data = indices_dict.get(key)
302
  display_name = index_display_names[key]
303
  if data and isinstance(data, list) and len(data) > 0:
@@ -325,6 +357,32 @@ def create_environmental_indices_card(indices_dict):
325
  ])
326
  ], className="mb-4")
327
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
328
  app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
329
  server = app.server
330
 
@@ -332,17 +390,13 @@ app.layout = dbc.Container([
332
  dcc.Store(id="location-store", storage_type="session"),
333
  dcc.Store(id="session-store", storage_type="session"),
334
  dcc.Interval(id="location-interval", interval=1000, max_intervals=1),
335
- dbc.Row([
336
- dbc.Col([
337
- html.H1("Weather Dashboard", className="text-center mb-4"),
338
- ], width=12)
339
- ]),
340
  dbc.Row([
341
  dbc.Col([
342
  dcc.Loading(
343
  id="loading",
344
  type="default",
345
  children=[
 
346
  html.Div(id="current-weather-output"),
347
  html.Div(id="environmental-indices-output")
348
  ],
@@ -398,6 +452,7 @@ def set_session_cookie(response):
398
 
399
  @app.callback(
400
  [
 
401
  Output("current-weather-output", "children"),
402
  Output("environmental-indices-output", "children"),
403
  Output("forecast-output", "children"),
@@ -412,10 +467,10 @@ def update_weather(location, session_data):
412
  if not location or 'error' in location:
413
  error_message = location.get('error', 'Waiting for location data...') if location else 'Waiting for location data...'
414
  logger.warning(f"Session {session_id} waiting for location: {error_message}")
415
- return [dbc.Spinner(color="primary"), "", ""]
416
 
417
  lat, lon = location["latitude"], location["longitude"]
418
- results = {"current": "", "indices": "", "hourly12": "", "forecast": ""}
419
  def fetch_weather_data():
420
  try:
421
  location_key = get_data_from_session(session_id, "location_key")
@@ -428,6 +483,7 @@ def update_weather(location, session_data):
428
  current = get_current_conditions(location_key)
429
  forecast_5day = get_forecast_5day(location_key)
430
  hourly_12 = get_hourly_forecast_12hour(location_key)
 
431
 
432
  indices_dict = {}
433
  for name, idx in INDEX_IDS.items():
@@ -436,13 +492,16 @@ def update_weather(location, session_data):
436
  if current is None or forecast_5day is None:
437
  raise ValueError("Failed to fetch weather data")
438
 
 
439
  results["current"] = create_current_weather_card(current)
440
  results["indices"] = create_environmental_indices_card(indices_dict)
441
  results["hourly12"] = create_hourly_12hour_card(hourly_12)
442
  results["forecast"] = create_forecast_5day_card(forecast_5day)
 
443
  save_session_data(session_id, "weather_results", results)
444
  except Exception as e:
445
  logger.error(f"Session {session_id} error: {str(e)}")
 
446
  results["current"] = ""
447
  results["indices"] = ""
448
  results["hourly12"] = ""
@@ -451,6 +510,7 @@ def update_weather(location, session_data):
451
  html.P(f"Error fetching weather data: {str(e)}", className="text-danger")
452
  ])
453
  ], className="mb-4")
 
454
 
455
  with lock:
456
  fetch_weather_data()
@@ -458,12 +518,17 @@ def update_weather(location, session_data):
458
  weather_results = get_data_from_session(session_id, "weather_results")
459
  if weather_results:
460
  return [
 
461
  weather_results.get("current", ""),
462
  weather_results.get("indices", ""),
463
- html.Div([weather_results.get("hourly12", ""), weather_results.get("forecast", "")])
 
 
 
 
464
  ]
465
  else:
466
- return [dbc.Spinner(color="primary"), "", ""]
467
 
468
  if __name__ == '__main__':
469
  print("Starting the Dash application...")
 
51
  INDEX_IDS = {
52
  "Health": 10,
53
  "Environmental": 5,
54
+ "Pollen": 30
 
55
  }
56
 
57
  def get_location_key(lat, lon):
 
167
  logger.error(f"Error in get_indices_1day {index_id}: {e}")
168
  return None
169
 
170
+ def get_minutecast_forecast(lat, lon):
171
+ url = f"{BASE_URL}/forecasts/v1/minute"
172
+ params = {
173
+ "apikey": API_KEY,
174
+ "q": f"{lat},{lon}",
175
+ "details": "true"
176
+ }
177
+ try:
178
+ response = requests.get(url, params=params)
179
+ response.raise_for_status()
180
+ data = response.json()
181
+ return data
182
+ except requests.RequestException as e:
183
+ logger.error(f"Error in get_minutecast_forecast: {e}")
184
+ return None
185
+
186
+ def create_summary_card(current):
187
+ if not current:
188
+ return dbc.Card([
189
+ dbc.CardBody([
190
+ html.H4("Summary", className="card-title"),
191
+ html.P("No summary data available.")
192
+ ])
193
+ ], className="mb-4")
194
+ uv_index = current.get("UVIndex", "N/A")
195
+ uv_index_text = current.get("UVIndexText", "N/A")
196
+ return dbc.Card([
197
+ dbc.CardBody([
198
+ html.H4("Summary", className="card-title"),
199
+ html.P(f"UV Index: {uv_index}"),
200
+ html.P(f"UV Index Text: {uv_index_text}")
201
+ ])
202
+ ], className="mb-4")
203
+
204
  def create_current_weather_card(current):
205
  if not current:
206
  return dbc.Card([
 
325
  def create_environmental_indices_card(indices_dict):
326
  items = []
327
  index_display_names = {
328
+ "Health": "Health",
329
+ "Environmental": "Environment",
330
+ "Pollen": "Pollen"
 
331
  }
332
+ for key in ["Health", "Environmental", "Pollen"]:
333
  data = indices_dict.get(key)
334
  display_name = index_display_names[key]
335
  if data and isinstance(data, list) and len(data) > 0:
 
357
  ])
358
  ], className="mb-4")
359
 
360
+ def create_minutecast_card(minutecast_data):
361
+ if not minutecast_data or not isinstance(minutecast_data, dict):
362
+ return dbc.Card([
363
+ dbc.CardBody([
364
+ html.H4("MinuteCast® Forecast", className="card-title"),
365
+ html.P("No MinuteCast® data available.")
366
+ ])
367
+ ], className="mb-4")
368
+ summary = minutecast_data.get("Summary", None)
369
+ phrase = summary.get("Phrase", "N/A") if summary else "N/A"
370
+ precipitation = summary.get("PrecipitationSummary", {}) if summary else {}
371
+ precip_type = precipitation.get("PrecipitationType", "N/A")
372
+ start_time = summary.get("StartTime", None)
373
+ end_time = summary.get("EndTime", None)
374
+ start_str = datetime.strptime(start_time, "%Y-%m-%dT%H:%M:%SZ").strftime("%I:%M %p") if start_time else "N/A"
375
+ end_str = datetime.strptime(end_time, "%Y-%m-%dT%H:%M:%SZ").strftime("%I:%M %p") if end_time else "N/A"
376
+ return dbc.Card([
377
+ dbc.CardBody([
378
+ html.H4("MinuteCast® Forecast", className="card-title"),
379
+ html.P(f"Summary: {phrase}"),
380
+ html.P(f"Precipitation Type: {precip_type}"),
381
+ html.P(f"Start: {start_str}"),
382
+ html.P(f"End: {end_str}")
383
+ ])
384
+ ], className="mb-4")
385
+
386
  app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
387
  server = app.server
388
 
 
390
  dcc.Store(id="location-store", storage_type="session"),
391
  dcc.Store(id="session-store", storage_type="session"),
392
  dcc.Interval(id="location-interval", interval=1000, max_intervals=1),
 
 
 
 
 
393
  dbc.Row([
394
  dbc.Col([
395
  dcc.Loading(
396
  id="loading",
397
  type="default",
398
  children=[
399
+ html.Div(id="summary-output"),
400
  html.Div(id="current-weather-output"),
401
  html.Div(id="environmental-indices-output")
402
  ],
 
452
 
453
  @app.callback(
454
  [
455
+ Output("summary-output", "children"),
456
  Output("current-weather-output", "children"),
457
  Output("environmental-indices-output", "children"),
458
  Output("forecast-output", "children"),
 
467
  if not location or 'error' in location:
468
  error_message = location.get('error', 'Waiting for location data...') if location else 'Waiting for location data...'
469
  logger.warning(f"Session {session_id} waiting for location: {error_message}")
470
+ return [dbc.Spinner(color="primary"), "", "", ""]
471
 
472
  lat, lon = location["latitude"], location["longitude"]
473
+ results = {"summary": "", "current": "", "indices": "", "hourly12": "", "forecast": "", "minutecast": ""}
474
  def fetch_weather_data():
475
  try:
476
  location_key = get_data_from_session(session_id, "location_key")
 
483
  current = get_current_conditions(location_key)
484
  forecast_5day = get_forecast_5day(location_key)
485
  hourly_12 = get_hourly_forecast_12hour(location_key)
486
+ minutecast = get_minutecast_forecast(lat, lon)
487
 
488
  indices_dict = {}
489
  for name, idx in INDEX_IDS.items():
 
492
  if current is None or forecast_5day is None:
493
  raise ValueError("Failed to fetch weather data")
494
 
495
+ results["summary"] = create_summary_card(current)
496
  results["current"] = create_current_weather_card(current)
497
  results["indices"] = create_environmental_indices_card(indices_dict)
498
  results["hourly12"] = create_hourly_12hour_card(hourly_12)
499
  results["forecast"] = create_forecast_5day_card(forecast_5day)
500
+ results["minutecast"] = create_minutecast_card(minutecast)
501
  save_session_data(session_id, "weather_results", results)
502
  except Exception as e:
503
  logger.error(f"Session {session_id} error: {str(e)}")
504
+ results["summary"] = ""
505
  results["current"] = ""
506
  results["indices"] = ""
507
  results["hourly12"] = ""
 
510
  html.P(f"Error fetching weather data: {str(e)}", className="text-danger")
511
  ])
512
  ], className="mb-4")
513
+ results["minutecast"] = ""
514
 
515
  with lock:
516
  fetch_weather_data()
 
518
  weather_results = get_data_from_session(session_id, "weather_results")
519
  if weather_results:
520
  return [
521
+ weather_results.get("summary", ""),
522
  weather_results.get("current", ""),
523
  weather_results.get("indices", ""),
524
+ html.Div([
525
+ weather_results.get("minutecast", ""),
526
+ weather_results.get("hourly12", ""),
527
+ weather_results.get("forecast", "")
528
+ ])
529
  ]
530
  else:
531
+ return [dbc.Spinner(color="primary"), "", "", ""]
532
 
533
  if __name__ == '__main__':
534
  print("Starting the Dash application...")