nakas commited on
Commit
23ad193
·
verified ·
1 Parent(s): d7422eb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -54
app.py CHANGED
@@ -1,11 +1,10 @@
1
  """
2
- Radar Data Downloader with Full Station Selector via Gradio
3
- ============================================================
4
 
5
- This script downloads the latest radar data file from public AWS S3 buckets.
6
- It now dynamically fetches the complete list of radar sites via an API (here,
7
- we use NOAA’s public radar stations endpoint as an example) so you can select from
8
- all available radar sites.
9
 
10
  Required packages:
11
  pip install gradio boto3 requests
@@ -13,7 +12,6 @@ Required packages:
13
 
14
  import datetime
15
  import io
16
- import json
17
 
18
  import boto3
19
  from botocore import UNSIGNED
@@ -25,11 +23,8 @@ import requests
25
  def get_full_station_list():
26
  """
27
  Fetches a full list of radar stations from a public API endpoint.
28
-
29
- For example, NOAA's NWS API offers radar station data at:
30
- https://api.weather.gov/radar/stations
31
-
32
- Note: This endpoint and its structure may change. Adjust the code accordingly.
33
  Returns a sorted list of station identifiers.
34
  """
35
  api_url = "https://api.weather.gov/radar/stations"
@@ -37,28 +32,20 @@ def get_full_station_list():
37
  response = requests.get(api_url, timeout=10)
38
  response.raise_for_status()
39
  data = response.json()
40
- except Exception as e:
41
- print(f"Error fetching station list from API: {e}")
42
- # Fallback to the static file from GitHub if API fails.
43
- return get_station_list_from_github()
44
-
45
- # The API returns a JSON object with a "features" key,
46
- # where each feature is a station. We assume that the station identifier is in properties["stationIdentifier"]
47
- stations = []
48
- try:
49
  features = data.get("features", [])
 
50
  for feature in features:
51
  props = feature.get("properties", {})
52
  station_id = props.get("stationIdentifier")
53
  if station_id:
54
  stations.append(station_id.upper())
 
 
 
55
  except Exception as e:
56
- print(f"Error processing API data: {e}")
57
- return get_station_list_from_github()
58
-
59
- # Remove duplicates and sort.
60
- stations = sorted(list(set(stations)))
61
- return stations
62
 
63
 
64
  def get_station_list_from_github():
@@ -85,25 +72,40 @@ def get_station_list_from_github():
85
  return stations
86
 
87
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  def fetch_latest_radar_data(radar_type, station, date_str):
89
  """
90
  Downloads the latest radar data file from the appropriate AWS S3 bucket.
91
 
92
  Parameters:
93
  radar_type (str): Either "Level 2" or "Level 3".
94
- station (str): Radar station identifier (e.g. "KTLX").
95
  date_str (str): Date string in "YYYY-MM-DD" format. If blank, uses current UTC date.
96
 
97
  Returns:
98
  str: A summary of the downloaded file (S3 key, size, last modified, and hex preview).
99
  """
100
- if not date_str.strip():
101
- date_obj = datetime.datetime.utcnow()
102
- else:
103
- try:
 
 
 
104
  date_obj = datetime.datetime.strptime(date_str, "%Y-%m-%d")
105
- except ValueError:
106
- return "Error: Date must be in YYYY-MM-DD format."
107
 
108
  year = date_obj.strftime("%Y")
109
  month = date_obj.strftime("%m")
@@ -154,26 +156,44 @@ def fetch_latest_radar_data(radar_type, station, date_str):
154
  return summary
155
 
156
 
157
- # Get full station list dynamically.
158
- # Try API first, fall back to GitHub file if needed.
159
- station_list = get_full_station_list()
160
-
161
- # Create the Gradio interface.
162
- interface = gr.Interface(
163
- fn=fetch_latest_radar_data,
164
- inputs=[
165
- gr.Radio(choices=["Level 2", "Level 3"], label="Radar Data Type"),
166
- gr.Dropdown(choices=station_list, label="Select Radar Station"),
167
- gr.Textbox(value=datetime.datetime.utcnow().strftime("%Y-%m-%d"), label="Date (YYYY-MM-DD)")
168
- ],
169
- outputs="text",
170
- title="Radar Data Downloader",
171
- description=(
172
- "This tool downloads the latest radar data file from public AWS S3 buckets "
173
- "used by Supercell Wx. Choose a radar data type (Level 2 or Level 3), select a "
174
- "radar station from the full list, and enter a date (UTC)."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
  )
176
- )
177
 
178
  if __name__ == "__main__":
179
- interface.launch()
 
 
1
  """
2
+ Radar Data Downloader with Two-Step Workflow via Gradio Blocks
3
+ ===============================================================
4
 
5
+ Step 1: Click "Fetch Stations" to dynamically retrieve the full list of radar sites.
6
+ Step 2: In the "Download Data" tab, select a radar type, choose a station (from the updated list),
7
+ enter a date (YYYY-MM-DD), and click "Download Data" to fetch the latest radar file.
 
8
 
9
  Required packages:
10
  pip install gradio boto3 requests
 
12
 
13
  import datetime
14
  import io
 
15
 
16
  import boto3
17
  from botocore import UNSIGNED
 
23
  def get_full_station_list():
24
  """
25
  Fetches a full list of radar stations from a public API endpoint.
26
+ For example, we use NOAA’s public radar station API endpoint as an example.
27
+ (If the API fails, falls back to fetching the static JSON file from GitHub.)
 
 
 
28
  Returns a sorted list of station identifiers.
29
  """
30
  api_url = "https://api.weather.gov/radar/stations"
 
32
  response = requests.get(api_url, timeout=10)
33
  response.raise_for_status()
34
  data = response.json()
 
 
 
 
 
 
 
 
 
35
  features = data.get("features", [])
36
+ stations = []
37
  for feature in features:
38
  props = feature.get("properties", {})
39
  station_id = props.get("stationIdentifier")
40
  if station_id:
41
  stations.append(station_id.upper())
42
+ stations = sorted(list(set(stations)))
43
+ if stations:
44
+ return stations
45
  except Exception as e:
46
+ print(f"Error fetching station list from API: {e}")
47
+ # Fallback to static JSON from GitHub
48
+ return get_station_list_from_github()
 
 
 
49
 
50
 
51
  def get_station_list_from_github():
 
72
  return stations
73
 
74
 
75
+ def update_station_list():
76
+ """
77
+ Retrieves the full station list and returns an update for the dropdown component.
78
+ """
79
+ stations = get_full_station_list()
80
+ if stations:
81
+ # Update with the full list and set the default to the first station.
82
+ return gr.Dropdown.update(choices=stations, value=stations[0])
83
+ else:
84
+ return gr.Dropdown.update(choices=[], value=None)
85
+
86
+
87
  def fetch_latest_radar_data(radar_type, station, date_str):
88
  """
89
  Downloads the latest radar data file from the appropriate AWS S3 bucket.
90
 
91
  Parameters:
92
  radar_type (str): Either "Level 2" or "Level 3".
93
+ station (str): Radar station identifier (e.g. "KTLX"). Must be non-empty.
94
  date_str (str): Date string in "YYYY-MM-DD" format. If blank, uses current UTC date.
95
 
96
  Returns:
97
  str: A summary of the downloaded file (S3 key, size, last modified, and hex preview).
98
  """
99
+ if not station:
100
+ return "Error: No station selected. Please fetch stations first."
101
+
102
+ try:
103
+ if not date_str.strip():
104
+ date_obj = datetime.datetime.utcnow()
105
+ else:
106
  date_obj = datetime.datetime.strptime(date_str, "%Y-%m-%d")
107
+ except ValueError:
108
+ return "Error: Date must be in YYYY-MM-DD format."
109
 
110
  year = date_obj.strftime("%Y")
111
  month = date_obj.strftime("%m")
 
156
  return summary
157
 
158
 
159
+ # Build the Gradio Blocks interface.
160
+ with gr.Blocks() as demo:
161
+ gr.Markdown("# Radar Data Downloader")
162
+ gr.Markdown(
163
+ "Step 1: **Fetch Stations** to retrieve the full list of radar sites.<br>"
164
+ "Step 2: **Download Data** by selecting a radar type, station, and date."
165
+ )
166
+
167
+ with gr.Tab("Fetch Stations"):
168
+ with gr.Row():
169
+ fetch_btn = gr.Button("Fetch Stations")
170
+ # This dropdown will show the fetched station list.
171
+ station_dropdown_fetch = gr.Dropdown(choices=[], label="Available Radar Stations")
172
+ # Clicking fetch_btn will update the dropdown.
173
+ fetch_btn.click(fn=update_station_list, inputs=[], outputs=station_dropdown_fetch)
174
+
175
+ with gr.Tab("Download Data"):
176
+ with gr.Row():
177
+ radar_type = gr.Radio(choices=["Level 2", "Level 3"], label="Radar Data Type")
178
+ # The download dropdown; initially empty. It can be updated by a separate sync button.
179
+ station_dropdown_download = gr.Dropdown(choices=[], label="Select Radar Station")
180
+ date_input = gr.Textbox(value=datetime.datetime.utcnow().strftime("%Y-%m-%d"),
181
+ label="Date (YYYY-MM-DD)")
182
+ download_btn = gr.Button("Download Data")
183
+ download_output = gr.Textbox(label="Download Output", interactive=False)
184
+ # When download_btn is clicked, call fetch_latest_radar_data.
185
+ download_btn.click(fn=fetch_latest_radar_data,
186
+ inputs=[radar_type, station_dropdown_download, date_input],
187
+ outputs=download_output)
188
+
189
+ # Optional: a button to sync the station list to the download dropdown.
190
+ sync_btn = gr.Button("Sync Station List to Download Tab")
191
+ sync_btn.click(fn=update_station_list, inputs=[], outputs=station_dropdown_download)
192
+
193
+ gr.Markdown(
194
+ "Note: First click **Fetch Stations** (or **Sync Station List to Download Tab**) to populate the radar site list before downloading data."
195
  )
 
196
 
197
  if __name__ == "__main__":
198
+ # For Spaces you might want to use share=True
199
+ demo.launch()