nakas commited on
Commit
29413a1
·
verified ·
1 Parent(s): 6fca2bd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -58
app.py CHANGED
@@ -17,44 +17,43 @@ def get_raw_data(station_id):
17
  'Accept': 'application/json'
18
  }
19
 
20
- # Base URL for NWS API
21
- base_url = "https://api.weather.gov"
 
 
 
 
 
 
 
 
22
 
23
  try:
24
- # First get the station metadata
25
- station_url = f"{base_url}/stations/{station_id}"
26
- print(f"\nFetching station metadata from: {station_url}")
27
-
28
- station_response = requests.get(station_url, headers=headers)
29
- station_response.raise_for_status()
30
-
31
- # Get observations with expanded parameters
32
- obs_url = f"{base_url}/stations/{station_id}/observations"
33
- params = {
34
- 'limit': 720,
35
- 'start': (datetime.utcnow() - timedelta(hours=720)).isoformat() + 'Z'
36
- }
37
 
38
- print(f"\nFetching observations from: {obs_url}")
39
- print(f"Parameters: {params}")
 
40
 
41
- obs_response = requests.get(obs_url, headers=headers, params=params)
42
- obs_response.raise_for_status()
43
-
44
- data = obs_response.json()
45
 
46
  if 'features' in data:
47
- print(f"\nFound {len(data['features'])} observations")
48
-
49
- # Print sample of available fields
50
  if len(data['features']) > 0:
51
- print("\nFirst observation fields:")
52
- properties = data['features'][0]['properties']
53
- for key, value in properties.items():
54
- print(f"{key}: {value}")
 
 
 
 
55
 
56
  return data
57
-
58
  except Exception as e:
59
  print(f"Error fetching data: {e}")
60
  print("Full error details:")
@@ -64,39 +63,43 @@ def get_raw_data(station_id):
64
 
65
  def parse_raw_data(data):
66
  """
67
- Parse the raw data from WRH timeseries into a DataFrame
68
  """
69
- if not data or 'data' not in data:
70
  return None
71
 
72
- # Convert list of dictionaries to DataFrame
73
- df = pd.DataFrame(data['data'])
74
-
75
- # Print the columns we found
76
- print("\nColumns in raw data:")
77
- print(df.columns.tolist())
78
-
79
- # Convert timestamp
80
- df['timestamp'] = pd.to_datetime(df['Date/Time'])
81
-
82
- # Convert numeric columns
83
- numeric_columns = ['Temp.', 'Wind Speed', 'Snow Depth']
84
- for col in numeric_columns:
85
- if col in df.columns:
86
- df[col] = pd.to_numeric(df[col].str.split().str[0], errors='coerce')
87
-
88
- # Rename columns to match our expected format
89
- column_mapping = {
90
- 'Temp.': 'temperature',
91
- 'Wind Speed': 'wind_speed',
92
- 'Wind Direction': 'wind_direction',
93
- 'Snow Depth': 'snow_depth'
94
- }
95
- df = df.rename(columns=column_mapping)
 
 
 
 
96
 
97
- print("\nProcessed DataFrame columns:")
98
  print(df.columns.tolist())
99
- print("\nSample of processed data:")
100
  print(df.head())
101
 
102
  return df
@@ -290,4 +293,4 @@ with gr.Blocks() as demo:
290
  # Launch the app
291
  demo.launch()
292
 
293
- #
 
17
  'Accept': 'application/json'
18
  }
19
 
20
+ # Calculate correct date range for last 3 days
21
+ end_time = datetime.utcnow()
22
+ start_time = end_time - timedelta(hours=72) # Last 3 days
23
+
24
+ params = {
25
+ 'start': start_time.isoformat() + 'Z',
26
+ 'end': end_time.isoformat() + 'Z'
27
+ }
28
+
29
+ url = f"https://api.weather.gov/stations/{station_id}/observations"
30
 
31
  try:
32
+ print("\nFetching observations...")
33
+ print(f"URL: {url}")
34
+ print(f"Time range: {start_time} to {end_time}")
35
+ response = requests.get(url, headers=headers, params=params)
36
+ print(f"Response status: {response.status_code}")
 
 
 
 
 
 
 
 
37
 
38
+ if response.status_code != 200:
39
+ print(f"Response content: {response.text}")
40
+ response.raise_for_status()
41
 
42
+ data = response.json()
 
 
 
43
 
44
  if 'features' in data:
45
+ print(f"\nNumber of observations: {len(data['features'])}")
 
 
46
  if len(data['features']) > 0:
47
+ print("\nFirst observation properties:")
48
+ print(json.dumps(data['features'][0]['properties'], indent=2))
49
+
50
+ print("\nAll available property keys:")
51
+ keys = set()
52
+ for feature in data['features']:
53
+ keys.update(feature['properties'].keys())
54
+ print(sorted(list(keys)))
55
 
56
  return data
 
57
  except Exception as e:
58
  print(f"Error fetching data: {e}")
59
  print("Full error details:")
 
63
 
64
  def parse_raw_data(data):
65
  """
66
+ Parse the raw JSON data into a DataFrame
67
  """
68
+ if not data or 'features' not in data:
69
  return None
70
 
71
+ records = []
72
+ for feature in data['features']:
73
+ props = feature['properties']
74
+
75
+ # Extract all properties starting with 'snow'
76
+ snow_fields = {k: v for k, v in props.items() if 'snow' in k.lower()}
77
+ if snow_fields:
78
+ print("\nFound snow-related fields:")
79
+ for k, v in snow_fields.items():
80
+ print(f"{k}: {v}")
81
+
82
+ record = {
83
+ 'timestamp': props['timestamp'],
84
+ 'temperature': props.get('temperature', {}).get('value'),
85
+ 'wind_speed': props.get('windSpeed', {}).get('value'),
86
+ 'wind_direction': props.get('windDirection', {}).get('value')
87
+ }
88
+
89
+ # Add all snow-related fields to the record
90
+ for k, v in snow_fields.items():
91
+ if isinstance(v, dict) and 'value' in v:
92
+ record[k] = v['value']
93
+ else:
94
+ record[k] = v
95
+
96
+ records.append(record)
97
+
98
+ df = pd.DataFrame(records)
99
 
100
+ print("\nDataFrame columns:")
101
  print(df.columns.tolist())
102
+ print("\nSample of raw data:")
103
  print(df.head())
104
 
105
  return df
 
293
  # Launch the app
294
  demo.launch()
295
 
296
+ # requirements.txt