mattritchey commited on
Commit
15e966f
·
verified ·
1 Parent(s): 97dde3f

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +134 -0
app.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)