Spaces:
Running
Running
# -*- coding: utf-8 -*- | |
""" | |
Created on Tue Apr 8 14:53:45 2025 | |
@author: mritchey | |
""" | |
# streamlit run "C:\Users\mritchey\.spyder-py3\Python Scripts\streamlit projects\weather api\app.py" | |
import glob | |
import os | |
import numpy as np | |
import pandas as pd | |
import plotly.express as px | |
import streamlit as st | |
from geopy.extra.rate_limiter import RateLimiter | |
from geopy.geocoders import Nominatim | |
def geocode(address): | |
try: | |
address2 = address.replace(' ', '+').replace(',', '%2C') | |
df = pd.read_json( | |
f'https://geocoding.geo.census.gov/geocoder/locations/onelineaddress?address={address2}&benchmark=2020&format=json') | |
results = df.iloc[:1, 0][0][0]['coordinates'] | |
lat, lon = results['y'], results['x'] | |
except: | |
geolocator = Nominatim(user_agent="GTA Lookup") | |
geocode = RateLimiter(geolocator.geocode, min_delay_seconds=1) | |
location = geolocator.geocode(address) | |
lat, lon = location.latitude, location.longitude | |
return lat, lon | |
def get_weather_data(lat, lon, start_date, end_date): | |
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' | |
df = pd.read_json(url).reset_index() | |
data = pd.DataFrame({c['index']: c['hourly'] for r, c in df.iterrows()}) | |
data['time'] = pd.to_datetime(data['time']) | |
data['date'] = pd.to_datetime(data['time'].dt.date) | |
data = data.query("temperature_2m==temperature_2m") | |
data_agg = data.groupby(['date']).agg({'temperature_2m': ['min', 'mean', 'max'], | |
'precipitation': ['sum'], | |
'windspeed_10m': ['min', 'mean', 'max'], | |
'windgusts_10m': ['min', 'mean', 'max'] | |
}) | |
data_agg.columns = data_agg.columns.to_series().str.join('_') | |
data_agg = data_agg.query("temperature_2m_min==temperature_2m_min") | |
return data.drop(columns=['date']), data_agg | |
def convert_df(df): | |
return df.to_csv(index=0).encode('utf-8') | |
st.set_page_config(layout="wide") | |
col1, col2 = st.columns((2)) | |
address = st.sidebar.text_input( | |
"Address", "1000 Main St, Cincinnati, OH 45202") | |
start_date = st.sidebar.date_input("Start Date", pd.Timestamp(2022, 9, 28)) | |
end_date = st.sidebar.date_input("End Date", pd.Timestamp(2022, 9, 30)) | |
type_var = st.sidebar.selectbox( | |
'Type:', ('Gust', 'Wind', 'Temp', 'Precipitation')) | |
hourly_daily = st.sidebar.radio('Aggregate Data', ('Hourly', 'Daily')) | |
start_date = start_date.strftime("%Y-%m-%d") | |
end_date = end_date.strftime("%Y-%m-%d") | |
lat, lon = geocode(address) | |
df_all, df_all_agg = get_weather_data(lat, lon, start_date, end_date) | |
# Keys | |
var_key = {'Gust': 'i10fg', 'Wind': 'wind10', | |
'Temp': 't2m', 'Precipitation': 'tp'} | |
variable = var_key[type_var] | |
unit_key = {'Gust': 'MPH', 'Wind': 'MPH', | |
'Temp': 'F', 'Precipitation': 'In.'} | |
unit = unit_key[type_var] | |
cols_key = {'Gust': ['windgusts_10m'], 'Wind': ['windspeed_10m'], 'Temp': ['temperature_2m'], | |
'Precipitation': ['precipitation']} | |
cols_key_agg = {'Gust': ['windgusts_10m_min', 'windgusts_10m_mean', | |
'windgusts_10m_max'], | |
'Wind': ['windspeed_10m_min', 'windspeed_10m_mean', | |
'windspeed_10m_max'], | |
'Temp': ['temperature_2m_min', 'temperature_2m_mean', 'temperature_2m_max'], | |
'Precipitation': ['precipitation_sum']} | |
if hourly_daily == 'Hourly': | |
cols = cols_key[type_var] | |
else: | |
cols = cols_key_agg[type_var] | |
if hourly_daily == 'Hourly': | |
fig = px.line(df_all, x="time", y=cols[0]) | |
df_downloald = df_all | |
else: | |
fig = px.line(df_all_agg.reset_index(), x="date", y=cols[0]) | |
df_downloald = df_all_agg.reset_index() | |
with col1: | |
st.title('Weather Data') | |
st.plotly_chart(fig) | |
csv = convert_df(df_downloald) | |
st.download_button( | |
label="Download data as CSV", | |
data=csv, | |
file_name=f'{start_date}.csv', | |
mime='text/csv') | |
with col2: | |
st.title('') | |
st.markdown(""" <style> | |
#MainMenu {visibility: hidden;} | |
footer {visibility: hidden;} | |
</style> """, unsafe_allow_html=True) | |