Spaces:
Running
Running
Create Weather API.py
Browse files- pages/Weather API.py +164 -0
pages/Weather API.py
ADDED
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import datetime
|
2 |
+
import glob
|
3 |
+
import os
|
4 |
+
import branca.colormap as cm
|
5 |
+
import folium
|
6 |
+
import numpy as np
|
7 |
+
import pandas as pd
|
8 |
+
import plotly.express as px
|
9 |
+
import streamlit as st
|
10 |
+
from geopy.extra.rate_limiter import RateLimiter
|
11 |
+
from geopy.geocoders import Nominatim
|
12 |
+
from matplotlib import colors as colors
|
13 |
+
from streamlit_folium import st_folium
|
14 |
+
import rioxarray
|
15 |
+
import xarray as xr
|
16 |
+
import cdsapi
|
17 |
+
import os
|
18 |
+
|
19 |
+
|
20 |
+
def mapvalue2color(value, cmap):
|
21 |
+
if np.isnan(value):
|
22 |
+
return (1, 0, 0, 0)
|
23 |
+
else:
|
24 |
+
return colors.to_rgba(cmap(value), 0.7)
|
25 |
+
|
26 |
+
|
27 |
+
def geocode(address):
|
28 |
+
try:
|
29 |
+
address2 = address.replace(' ', '+').replace(',', '%2C')
|
30 |
+
df = pd.read_json(
|
31 |
+
f'https://geocoding.geo.census.gov/geocoder/locations/onelineaddress?address={address2}&benchmark=2020&format=json')
|
32 |
+
results = df.iloc[:1, 0][0][0]['coordinates']
|
33 |
+
lat, lon = results['y'], results['x']
|
34 |
+
except:
|
35 |
+
geolocator = Nominatim(user_agent="GTA Lookup")
|
36 |
+
geocode = RateLimiter(geolocator.geocode, min_delay_seconds=1)
|
37 |
+
location = geolocator.geocode(address)
|
38 |
+
lat, lon = location.latitude, location.longitude
|
39 |
+
return lat, lon
|
40 |
+
|
41 |
+
|
42 |
+
def graph_within_date_range(d, number_days_range):
|
43 |
+
year, month, day = d[:4], d[4:6], d[6:8]
|
44 |
+
date = pd.Timestamp(d)
|
45 |
+
start_date, end_date = date - \
|
46 |
+
pd.Timedelta(days=number_days_range), date + \
|
47 |
+
pd.Timedelta(days=number_days_range+1)
|
48 |
+
start_date = start_date.strftime("%Y-%m-%d")
|
49 |
+
end_date = end_date.strftime("%Y-%m-%d")
|
50 |
+
url = f'https://archive-api.open-meteo.com/v1/archive?latitude={lat}&longitude={lon}&start_date={start_date}&end_date={end_date}&hourly=temperature_2m,precipitation,windspeed_10m,wind_gusts_10m&models=best_match&temperature_unit=fahrenheit&windspeed_unit=mph&precipitation_unit=inch'
|
51 |
+
df = pd.read_json(url).reset_index()
|
52 |
+
data = pd.DataFrame({c['index']: c['hourly'] for r, c in df.iterrows()})
|
53 |
+
data['time'] = pd.to_datetime(data['time'])
|
54 |
+
data['date'] = pd.to_datetime(data['time'].dt.date)
|
55 |
+
data = data.query("temperature_2m==temperature_2m")
|
56 |
+
|
57 |
+
data_agg = data.groupby(['date']).agg({'temperature_2m': ['min', 'mean', 'max'],
|
58 |
+
'precipitation': ['sum'],
|
59 |
+
'windspeed_10m': ['min', 'mean', 'max'],
|
60 |
+
'wind_gusts_10m': ['min', 'mean', 'max']
|
61 |
+
})
|
62 |
+
data_agg.columns = data_agg.columns.to_series().str.join('_')
|
63 |
+
data_agg = data_agg.query("temperature_2m_min==temperature_2m_min")
|
64 |
+
return data.drop(columns=['date']), data_agg
|
65 |
+
|
66 |
+
|
67 |
+
@st.cache_data
|
68 |
+
def get_weather_data(lat, lon, start_date, end_date):
|
69 |
+
|
70 |
+
url = f'https://archive-api.open-meteo.com/v1/archive?latitude={lat}&longitude={lon}&start_date={start_date}&end_date={end_date}&hourly=temperature_2m,precipitation,windspeed_10m,windgusts_10m&models=best_match&temperature_unit=fahrenheit&windspeed_unit=mph&precipitation_unit=inch'
|
71 |
+
df = pd.read_json(url).reset_index()
|
72 |
+
data = pd.DataFrame({c['index']: c['hourly'] for r, c in df.iterrows()})
|
73 |
+
data['time'] = pd.to_datetime(data['time'])
|
74 |
+
data['date'] = pd.to_datetime(data['time'].dt.date)
|
75 |
+
data = data.query("temperature_2m==temperature_2m")
|
76 |
+
|
77 |
+
data_agg = data.groupby(['date']).agg({'temperature_2m': ['min', 'mean', 'max'],
|
78 |
+
'precipitation': ['sum'],
|
79 |
+
'windspeed_10m': ['min', 'mean', 'max'],
|
80 |
+
'windgusts_10m': ['min', 'mean', 'max']
|
81 |
+
})
|
82 |
+
data_agg.columns = data_agg.columns.to_series().str.join('_')
|
83 |
+
data_agg = data_agg.query("temperature_2m_min==temperature_2m_min")
|
84 |
+
return data.drop(columns=['date']), data_agg
|
85 |
+
|
86 |
+
|
87 |
+
@st.cache_data
|
88 |
+
def convert_df(df):
|
89 |
+
return df.to_csv(index=0).encode('utf-8')
|
90 |
+
|
91 |
+
|
92 |
+
st.set_page_config(layout="wide")
|
93 |
+
col1, col2 = st.columns((2))
|
94 |
+
|
95 |
+
|
96 |
+
address = st.sidebar.text_input(
|
97 |
+
"Address", "1000 Main St, Cincinnati, OH 45202")
|
98 |
+
start_date = st.sidebar.date_input("Start Date", pd.Timestamp(2022, 9, 28))
|
99 |
+
end_date = st.sidebar.date_input("End Date", pd.Timestamp(2022, 9, 30))
|
100 |
+
type_var = st.sidebar.selectbox(
|
101 |
+
'Type:', ('Gust', 'Wind', 'Temp', 'Precipitation'))
|
102 |
+
hourly_daily = st.sidebar.radio('Aggregate Data', ('Hourly', 'Daily'))
|
103 |
+
|
104 |
+
|
105 |
+
start_date = start_date.strftime("%Y-%m-%d")
|
106 |
+
end_date = end_date.strftime("%Y-%m-%d")
|
107 |
+
|
108 |
+
lat, lon = geocode(address)
|
109 |
+
|
110 |
+
df_all, df_all_agg = get_weather_data(lat, lon, start_date, end_date)
|
111 |
+
|
112 |
+
# Keys
|
113 |
+
var_key = {'Gust': 'i10fg', 'Wind': 'wind10',
|
114 |
+
'Temp': 't2m', 'Precipitation': 'tp'}
|
115 |
+
|
116 |
+
variable = var_key[type_var]
|
117 |
+
|
118 |
+
unit_key = {'Gust': 'MPH', 'Wind': 'MPH',
|
119 |
+
'Temp': 'F', 'Precipitation': 'In.'}
|
120 |
+
unit = unit_key[type_var]
|
121 |
+
|
122 |
+
cols_key = {'Gust': ['windgusts_10m'], 'Wind': ['windspeed_10m'], 'Temp': ['temperature_2m'],
|
123 |
+
'Precipitation': ['precipitation']}
|
124 |
+
|
125 |
+
cols_key_agg = {'Gust': ['windgusts_10m_min', 'windgusts_10m_mean',
|
126 |
+
'windgusts_10m_max'],
|
127 |
+
'Wind': ['windspeed_10m_min', 'windspeed_10m_mean',
|
128 |
+
'windspeed_10m_max'],
|
129 |
+
'Temp': ['temperature_2m_min', 'temperature_2m_mean', 'temperature_2m_max'],
|
130 |
+
'Precipitation': ['precipitation_sum']}
|
131 |
+
|
132 |
+
if hourly_daily == 'Hourly':
|
133 |
+
cols = cols_key[type_var]
|
134 |
+
else:
|
135 |
+
cols = cols_key_agg[type_var]
|
136 |
+
|
137 |
+
if hourly_daily == 'Hourly':
|
138 |
+
fig = px.line(df_all, x="time", y=cols[0])
|
139 |
+
df_downloald = df_all
|
140 |
+
else:
|
141 |
+
fig = px.line(df_all_agg.reset_index(), x="date", y=cols[0])
|
142 |
+
df_downloald = df_all_agg.reset_index()
|
143 |
+
|
144 |
+
with col1:
|
145 |
+
st.title('Weather Data')
|
146 |
+
st.plotly_chart(fig)
|
147 |
+
|
148 |
+
csv = convert_df(df_downloald)
|
149 |
+
|
150 |
+
st.download_button(
|
151 |
+
label="Download data as CSV",
|
152 |
+
data=csv,
|
153 |
+
file_name=f'{start_date}.csv',
|
154 |
+
mime='text/csv')
|
155 |
+
|
156 |
+
|
157 |
+
with col2:
|
158 |
+
st.title('')
|
159 |
+
|
160 |
+
|
161 |
+
st.markdown(""" <style>
|
162 |
+
#MainMenu {visibility: hidden;}
|
163 |
+
footer {visibility: hidden;}
|
164 |
+
</style> """, unsafe_allow_html=True)
|