mattritchey commited on
Commit
3dfb6d7
·
verified ·
1 Parent(s): 7744acf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +132 -134
app.py CHANGED
@@ -1,134 +1,132 @@
1
- # -*- coding: utf-8 -*-
2
- """
3
- Created on Tue Apr 8 14:53:45 2025
4
-
5
- @author: mritchey
6
- """
7
-
8
-
9
- # streamlit run "C:\Users\mritchey\.spyder-py3\Python Scripts\streamlit projects\weather api\app.py"
10
- import glob
11
- import os
12
- import folium
13
- import numpy as np
14
- import pandas as pd
15
- import plotly.express as px
16
- import streamlit as st
17
- from geopy.extra.rate_limiter import RateLimiter
18
- from geopy.geocoders import Nominatim
19
-
20
-
21
- def geocode(address):
22
- try:
23
- address2 = address.replace(' ', '+').replace(',', '%2C')
24
- df = pd.read_json(
25
- f'https://geocoding.geo.census.gov/geocoder/locations/onelineaddress?address={address2}&benchmark=2020&format=json')
26
- results = df.iloc[:1, 0][0][0]['coordinates']
27
- lat, lon = results['y'], results['x']
28
- except:
29
- geolocator = Nominatim(user_agent="GTA Lookup")
30
- geocode = RateLimiter(geolocator.geocode, min_delay_seconds=1)
31
- location = geolocator.geocode(address)
32
- lat, lon = location.latitude, location.longitude
33
- return lat, lon
34
-
35
-
36
-
37
- @st.cache_data
38
- def get_weather_data(lat, lon, start_date, end_date):
39
-
40
- 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'
41
- df = pd.read_json(url).reset_index()
42
- data = pd.DataFrame({c['index']: c['hourly'] for r, c in df.iterrows()})
43
- data['time'] = pd.to_datetime(data['time'])
44
- data['date'] = pd.to_datetime(data['time'].dt.date)
45
- data = data.query("temperature_2m==temperature_2m")
46
-
47
- data_agg = data.groupby(['date']).agg({'temperature_2m': ['min', 'mean', 'max'],
48
- 'precipitation': ['sum'],
49
- 'windspeed_10m': ['min', 'mean', 'max'],
50
- 'windgusts_10m': ['min', 'mean', 'max']
51
- })
52
- data_agg.columns = data_agg.columns.to_series().str.join('_')
53
- data_agg = data_agg.query("temperature_2m_min==temperature_2m_min")
54
- return data.drop(columns=['date']), data_agg
55
-
56
-
57
- @st.cache_data
58
- def convert_df(df):
59
- return df.to_csv(index=0).encode('utf-8')
60
-
61
-
62
- st.set_page_config(layout="wide")
63
- col1, col2 = st.columns((2))
64
-
65
-
66
- address = st.sidebar.text_input(
67
- "Address", "1000 Main St, Cincinnati, OH 45202")
68
- start_date = st.sidebar.date_input("Start Date", pd.Timestamp(2022, 9, 28))
69
- end_date = st.sidebar.date_input("End Date", pd.Timestamp(2022, 9, 30))
70
- type_var = st.sidebar.selectbox(
71
- 'Type:', ('Gust', 'Wind', 'Temp', 'Precipitation'))
72
- hourly_daily = st.sidebar.radio('Aggregate Data', ('Hourly', 'Daily'))
73
-
74
-
75
- start_date = start_date.strftime("%Y-%m-%d")
76
- end_date = end_date.strftime("%Y-%m-%d")
77
-
78
- lat, lon = geocode(address)
79
-
80
- df_all, df_all_agg = get_weather_data(lat, lon, start_date, end_date)
81
-
82
- # Keys
83
- var_key = {'Gust': 'i10fg', 'Wind': 'wind10',
84
- 'Temp': 't2m', 'Precipitation': 'tp'}
85
-
86
- variable = var_key[type_var]
87
-
88
- unit_key = {'Gust': 'MPH', 'Wind': 'MPH',
89
- 'Temp': 'F', 'Precipitation': 'In.'}
90
- unit = unit_key[type_var]
91
-
92
- cols_key = {'Gust': ['windgusts_10m'], 'Wind': ['windspeed_10m'], 'Temp': ['temperature_2m'],
93
- 'Precipitation': ['precipitation']}
94
-
95
- cols_key_agg = {'Gust': ['windgusts_10m_min', 'windgusts_10m_mean',
96
- 'windgusts_10m_max'],
97
- 'Wind': ['windspeed_10m_min', 'windspeed_10m_mean',
98
- 'windspeed_10m_max'],
99
- 'Temp': ['temperature_2m_min', 'temperature_2m_mean', 'temperature_2m_max'],
100
- 'Precipitation': ['precipitation_sum']}
101
-
102
- if hourly_daily == 'Hourly':
103
- cols = cols_key[type_var]
104
- else:
105
- cols = cols_key_agg[type_var]
106
-
107
- if hourly_daily == 'Hourly':
108
- fig = px.line(df_all, x="time", y=cols[0])
109
- df_downloald = df_all
110
- else:
111
- fig = px.line(df_all_agg.reset_index(), x="date", y=cols[0])
112
- df_downloald = df_all_agg.reset_index()
113
-
114
- with col1:
115
- st.title('Weather Data')
116
- st.plotly_chart(fig)
117
-
118
- csv = convert_df(df_downloald)
119
-
120
- st.download_button(
121
- label="Download data as CSV",
122
- data=csv,
123
- file_name=f'{start_date}.csv',
124
- mime='text/csv')
125
-
126
-
127
- with col2:
128
- st.title('')
129
-
130
-
131
- st.markdown(""" <style>
132
- #MainMenu {visibility: hidden;}
133
- footer {visibility: hidden;}
134
- </style> """, unsafe_allow_html=True)
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Created on Tue Apr 8 14:53:45 2025
4
+
5
+ @author: mritchey
6
+ """
7
+
8
+ # streamlit run "C:\Users\mritchey\.spyder-py3\Python Scripts\streamlit projects\weather api\app.py"
9
+ import glob
10
+ import os
11
+ import numpy as np
12
+ import pandas as pd
13
+ import plotly.express as px
14
+ import streamlit as st
15
+ from geopy.extra.rate_limiter import RateLimiter
16
+ from geopy.geocoders import Nominatim
17
+
18
+
19
+ def geocode(address):
20
+ try:
21
+ address2 = address.replace(' ', '+').replace(',', '%2C')
22
+ df = pd.read_json(
23
+ f'https://geocoding.geo.census.gov/geocoder/locations/onelineaddress?address={address2}&benchmark=2020&format=json')
24
+ results = df.iloc[:1, 0][0][0]['coordinates']
25
+ lat, lon = results['y'], results['x']
26
+ except:
27
+ geolocator = Nominatim(user_agent="GTA Lookup")
28
+ geocode = RateLimiter(geolocator.geocode, min_delay_seconds=1)
29
+ location = geolocator.geocode(address)
30
+ lat, lon = location.latitude, location.longitude
31
+ return lat, lon
32
+
33
+
34
+
35
+ @st.cache_data
36
+ def get_weather_data(lat, lon, start_date, end_date):
37
+
38
+ 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'
39
+ df = pd.read_json(url).reset_index()
40
+ data = pd.DataFrame({c['index']: c['hourly'] for r, c in df.iterrows()})
41
+ data['time'] = pd.to_datetime(data['time'])
42
+ data['date'] = pd.to_datetime(data['time'].dt.date)
43
+ data = data.query("temperature_2m==temperature_2m")
44
+
45
+ data_agg = data.groupby(['date']).agg({'temperature_2m': ['min', 'mean', 'max'],
46
+ 'precipitation': ['sum'],
47
+ 'windspeed_10m': ['min', 'mean', 'max'],
48
+ 'windgusts_10m': ['min', 'mean', 'max']
49
+ })
50
+ data_agg.columns = data_agg.columns.to_series().str.join('_')
51
+ data_agg = data_agg.query("temperature_2m_min==temperature_2m_min")
52
+ return data.drop(columns=['date']), data_agg
53
+
54
+
55
+ @st.cache_data
56
+ def convert_df(df):
57
+ return df.to_csv(index=0).encode('utf-8')
58
+
59
+
60
+ st.set_page_config(layout="wide")
61
+ col1, col2 = st.columns((2))
62
+
63
+
64
+ address = st.sidebar.text_input(
65
+ "Address", "1000 Main St, Cincinnati, OH 45202")
66
+ start_date = st.sidebar.date_input("Start Date", pd.Timestamp(2022, 9, 28))
67
+ end_date = st.sidebar.date_input("End Date", pd.Timestamp(2022, 9, 30))
68
+ type_var = st.sidebar.selectbox(
69
+ 'Type:', ('Gust', 'Wind', 'Temp', 'Precipitation'))
70
+ hourly_daily = st.sidebar.radio('Aggregate Data', ('Hourly', 'Daily'))
71
+
72
+
73
+ start_date = start_date.strftime("%Y-%m-%d")
74
+ end_date = end_date.strftime("%Y-%m-%d")
75
+
76
+ lat, lon = geocode(address)
77
+
78
+ df_all, df_all_agg = get_weather_data(lat, lon, start_date, end_date)
79
+
80
+ # Keys
81
+ var_key = {'Gust': 'i10fg', 'Wind': 'wind10',
82
+ 'Temp': 't2m', 'Precipitation': 'tp'}
83
+
84
+ variable = var_key[type_var]
85
+
86
+ unit_key = {'Gust': 'MPH', 'Wind': 'MPH',
87
+ 'Temp': 'F', 'Precipitation': 'In.'}
88
+ unit = unit_key[type_var]
89
+
90
+ cols_key = {'Gust': ['windgusts_10m'], 'Wind': ['windspeed_10m'], 'Temp': ['temperature_2m'],
91
+ 'Precipitation': ['precipitation']}
92
+
93
+ cols_key_agg = {'Gust': ['windgusts_10m_min', 'windgusts_10m_mean',
94
+ 'windgusts_10m_max'],
95
+ 'Wind': ['windspeed_10m_min', 'windspeed_10m_mean',
96
+ 'windspeed_10m_max'],
97
+ 'Temp': ['temperature_2m_min', 'temperature_2m_mean', 'temperature_2m_max'],
98
+ 'Precipitation': ['precipitation_sum']}
99
+
100
+ if hourly_daily == 'Hourly':
101
+ cols = cols_key[type_var]
102
+ else:
103
+ cols = cols_key_agg[type_var]
104
+
105
+ if hourly_daily == 'Hourly':
106
+ fig = px.line(df_all, x="time", y=cols[0])
107
+ df_downloald = df_all
108
+ else:
109
+ fig = px.line(df_all_agg.reset_index(), x="date", y=cols[0])
110
+ df_downloald = df_all_agg.reset_index()
111
+
112
+ with col1:
113
+ st.title('Weather Data')
114
+ st.plotly_chart(fig)
115
+
116
+ csv = convert_df(df_downloald)
117
+
118
+ st.download_button(
119
+ label="Download data as CSV",
120
+ data=csv,
121
+ file_name=f'{start_date}.csv',
122
+ mime='text/csv')
123
+
124
+
125
+ with col2:
126
+ st.title('')
127
+
128
+
129
+ st.markdown(""" <style>
130
+ #MainMenu {visibility: hidden;}
131
+ footer {visibility: hidden;}
132
+ </style> """, unsafe_allow_html=True)