aromidvar1355 commited on
Commit
1214797
·
verified ·
1 Parent(s): c51b0e8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +122 -5
app.py CHANGED
@@ -25,7 +25,13 @@ st.sidebar.title("🌍 Environmental Data Dashboard")
25
  data_source = st.sidebar.selectbox(
26
  "Select Data Source",
27
  ["Weather Data", "Marine", "Solunar & Tide Data", "Fish Categories Data"]
28
- )
 
 
 
 
 
 
29
 
30
  # --- API CALLING FUNCTIONS ---
31
  def fetch_openweather_data(lat, lon, datetime_input):
@@ -35,7 +41,22 @@ def fetch_openweather_data(lat, lon, datetime_input):
35
  try:
36
  response = requests.get(url) # Make the API call
37
  response.raise_for_status() # Raise an error for bad responses
38
- data = response.json() # Parse JSON response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  return data
40
  except requests.exceptions.HTTPError as http_err:
41
  st.error(f"HTTP error occurred: {http_err}")
@@ -49,7 +70,25 @@ def fetch_openweather_forecast(lat, lon):
49
  try:
50
  response = requests.get(url)
51
  response.raise_for_status() # Raise HTTPError for bad responses
52
- return response.json()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  except requests.exceptions.RequestException as e:
54
  st.error(f"Error fetching OpenWeather forecast data: {e}")
55
  return None
@@ -64,7 +103,23 @@ def fetch_stormglass_data(lat, lng, start_datetime, end_datetime, selected_param
64
  try:
65
  response = requests.get(url, headers=headers)
66
  response.raise_for_status()
67
- return response.json()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  except requests.exceptions.RequestException as e:
69
  st.error(f"Error fetching Stormglass data: {e}")
70
  return None
@@ -84,6 +139,17 @@ def fetch_solunar_tide_data(lat, lon, datetime_input):
84
 
85
  tide_data = tide_response.json() if tide_response.status_code == 200 else None
86
  astronomy_data = astronomy_response.json() if astronomy_response.status_code == 200 else None
 
 
 
 
 
 
 
 
 
 
 
87
 
88
  return {
89
  'tide': tide_data,
@@ -92,7 +158,44 @@ def fetch_solunar_tide_data(lat, lon, datetime_input):
92
 
93
  except Exception as e:
94
  st.error(f"Error fetching Solunar and Tide data: {e}")
95
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
  # --- MAIN APPLICATION LOGIC ---
98
  def main():
@@ -176,6 +279,20 @@ def main():
176
  ).add_to(m)
177
 
178
  folium_static(m)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
 
180
  with col2:
181
  if st.button("Get Weather Forecast"):
 
25
  data_source = st.sidebar.selectbox(
26
  "Select Data Source",
27
  ["Weather Data", "Marine", "Solunar & Tide Data", "Fish Categories Data"]
28
+ )
29
+
30
+ # Initialize global lists for each data source
31
+ openweather_historical_readings = []
32
+ openweather_forecast_readings = []
33
+ stormglass_marine_readings = []
34
+ solunar_tide_readings = []
35
 
36
  # --- API CALLING FUNCTIONS ---
37
  def fetch_openweather_data(lat, lon, datetime_input):
 
41
  try:
42
  response = requests.get(url) # Make the API call
43
  response.raise_for_status() # Raise an error for bad responses
44
+ data = response.json() # Parse JSON response
45
+
46
+ # Store the data in the global list
47
+ if data:
48
+ processed_entry = {
49
+ 'timestamp': datetime_input,
50
+ 'latitude': lat,
51
+ 'longitude': lon,
52
+ 'temperature': data.get('temp', {}),
53
+ 'humidity': data.get('humidity', None),
54
+ 'wind_speed': data.get('wind_speed', None),
55
+ # Add other relevant fields
56
+ }
57
+ openweather_historical_readings.append(processed_entry)
58
+
59
+
60
  return data
61
  except requests.exceptions.HTTPError as http_err:
62
  st.error(f"HTTP error occurred: {http_err}")
 
70
  try:
71
  response = requests.get(url)
72
  response.raise_for_status() # Raise HTTPError for bad responses
73
+ data = response.json()
74
+
75
+ # Store the forecast data in the global list
76
+ if data and 'daily' in data:
77
+ for day_data in data['daily']:
78
+ processed_entry = {
79
+ 'date': day_data.get('dt', None),
80
+ 'latitude': lat,
81
+ 'longitude': lon,
82
+ 'temperature_day': day_data.get('temp', {}).get('day', None),
83
+ 'temperature_night': day_data.get('temp', {}).get('night', None),
84
+ 'humidity': day_data.get('humidity', None),
85
+ 'wind_speed': day_data.get('wind_speed', None),
86
+ # Add other relevant fields
87
+ }
88
+ openweather_forecast_readings.append(processed_entry)
89
+
90
+ return data
91
+
92
  except requests.exceptions.RequestException as e:
93
  st.error(f"Error fetching OpenWeather forecast data: {e}")
94
  return None
 
103
  try:
104
  response = requests.get(url, headers=headers)
105
  response.raise_for_status()
106
+ data = response.json()
107
+
108
+ # Store the marine data in the global list
109
+ if data and 'hours' in data:
110
+ for hour_data in data['hours']:
111
+ processed_entry = {
112
+ 'timestamp': hour_data.get('time', None),
113
+ 'latitude': lat,
114
+ 'longitude': lng,
115
+ 'wave_height': hour_data.get('waveHeight', {}).get('value', None),
116
+ 'wind_speed': hour_data.get('windSpeed', {}).get('value', None),
117
+ 'temperature': hour_data.get('temperature', {}).get('value', None),
118
+ # Add other relevant fields
119
+ }
120
+ stormglass_marine_readings.append(processed_entry)
121
+
122
+ return data
123
  except requests.exceptions.RequestException as e:
124
  st.error(f"Error fetching Stormglass data: {e}")
125
  return None
 
139
 
140
  tide_data = tide_response.json() if tide_response.status_code == 200 else None
141
  astronomy_data = astronomy_response.json() if astronomy_response.status_code == 200 else None
142
+ # Store the solunar and tide data in the global list
143
+ if tide_data or astronomy_data:
144
+ processed_entry = {
145
+ 'date': datetime_input.date().isoformat(),
146
+ 'latitude': lat,
147
+ 'longitude': lon,
148
+ 'tide_data': tide_data,
149
+ 'astronomy_data': astronomy_data
150
+ }
151
+ solunar_tide_readings.append(processed_entry)
152
+
153
 
154
  return {
155
  'tide': tide_data,
 
158
 
159
  except Exception as e:
160
  st.error(f"Error fetching Solunar and Tide data: {e}")
161
+ return None
162
+
163
+ def save_openweather_historical_to_csv():
164
+ """Save historical OpenWeather data to CSV."""
165
+ if not openweather_historical_readings:
166
+ st.error("No historical weather data to save!")
167
+ return
168
+
169
+ df = pd.DataFrame(openweather_historical_readings)
170
+ return df
171
+
172
+ def save_openweather_forecast_to_csv():
173
+ """Save forecast OpenWeather data to CSV."""
174
+ if not openweather_forecast_readings:
175
+ st.error("No forecast weather data to save!")
176
+ return
177
+
178
+ df = pd.DataFrame(openweather_forecast_readings)
179
+ return df
180
+
181
+ def save_stormglass_marine_to_csv():
182
+ """Save Stormglass marine data to CSV."""
183
+ if not stormglass_marine_readings:
184
+ st.error("No marine data to save!")
185
+ return
186
+
187
+ df = pd.DataFrame(stormglass_marine_readings)
188
+ return df
189
+
190
+ def save_solunar_tide_to_csv():
191
+ """Save solunar and tide data to CSV."""
192
+ if not solunar_tide_readings:
193
+ st.error("No solunar or tide data to save!")
194
+ return
195
+
196
+ df = pd.DataFrame(solunar_tide_readings)
197
+ return df
198
+
199
 
200
  # --- MAIN APPLICATION LOGIC ---
201
  def main():
 
279
  ).add_to(m)
280
 
281
  folium_static(m)
282
+ # Download button for historical data
283
+ if st.button("Download Historical Weather Data"):
284
+ df = save_openweather_historical_to_csv()
285
+ if isinstance(df, pd.DataFrame):
286
+ csv = df.to_csv(index=False).encode('utf-8')
287
+ st.download_button(
288
+ label="Download Historical Weather Data CSV",
289
+ data=csv,
290
+ file_name=f"openweather_historical_data_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
291
+ mime="text/csv",
292
+ )
293
+ st.success("Historical weather data saved and ready for download!")
294
+ else:
295
+ st.error("Failed to prepare the historical weather data CSV.")
296
 
297
  with col2:
298
  if st.button("Get Weather Forecast"):