File size: 3,396 Bytes
307d0dd
 
 
f15d367
 
307d0dd
 
d81dba4
71ff0bf
 
 
f15d367
 
 
 
 
307d0dd
f15d367
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71ff0bf
f15d367
 
 
 
 
 
 
 
 
 
 
e883258
f15d367
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import openmeteo_requests
import requests_cache
import pandas as pd
import streamlit as st
import logging
from retry_requests import retry

def download_data():
	"""
	Fetches the data from the public api
	"""
	try:
		# Setup the Open-Meteo API client with cache and retry on error
		cache_session = requests_cache.CachedSession('.cache', expire_after = 3600)
		retry_session = retry(cache_session, retries = 5, backoff_factor = 0.2)
		openmeteo = openmeteo_requests.Client(session = retry_session)

		# Make sure all required weather variables are listed here
		# The order of variables in hourly or daily is important to assign them correctly below
		url = "https://api.open-meteo.com/v1/forecast"
		params = {
			"latitude": 52.11,
			"longitude": 5.1806,
			"hourly": ["temperature_2m", "dew_point_2m", "wind_speed_10m", "wind_gusts_10m", "sunshine_duration", "global_tilted_irradiance"],
			"wind_speed_unit": "ms",
			"past_days": 2,
			"forecast_days": 3,
			"models": "knmi_seamless"
		}
		responses = openmeteo.weather_api(url, params=params)

		# Process first location. Add a for-loop for multiple locations or weather models
		response = responses[0]
		print(f"Coordinates {response.Latitude()}°N {response.Longitude()}°E")
		print(f"Elevation {response.Elevation()} m asl")
		print(f"Timezone {response.Timezone()} {response.TimezoneAbbreviation()}")
		print(f"Timezone difference to GMT+0 {response.UtcOffsetSeconds()} s")

		# Process hourly data. The order of variables needs to be the same as requested.
		hourly = response.Hourly()
		hourly_temperature_2m = hourly.Variables(0).ValuesAsNumpy()
		hourly_dew_point_2m = hourly.Variables(1).ValuesAsNumpy()
		hourly_wind_speed_10m = hourly.Variables(2).ValuesAsNumpy()
		hourly_wind_gusts_10m = hourly.Variables(3).ValuesAsNumpy()
		hourly_sunshine_duration = hourly.Variables(4).ValuesAsNumpy()
		hourly_global_tilted_irradiance = hourly.Variables(5).ValuesAsNumpy()

		hourly_data = {"date": pd.date_range(
			start = pd.to_datetime(hourly.Time(), unit = "s", utc = True),
			end = pd.to_datetime(hourly.TimeEnd(), unit = "s", utc = True),
			freq = pd.Timedelta(seconds = hourly.Interval()),
			inclusive = "left"
		)}
		hourly_data["temperature_2m"] = hourly_temperature_2m
		hourly_data["dew_point_2m"] = hourly_dew_point_2m
		hourly_data["wind_speed_10m"] = hourly_wind_speed_10m
		hourly_data["wind_gusts_10m"] = hourly_wind_gusts_10m
		hourly_data["sunshine_duration"] = hourly_sunshine_duration
		hourly_data["global_tilted_irradiance"] = hourly_global_tilted_irradiance

		hourly_dataframe = pd.DataFrame(data = hourly_data)

		# check if the columns are as expected
		expected_columns = [
			'temperature_2m',
			'dew_point_2m',
			'wind_speed_10m',  
			'wind_gusts_10m',   
			'sunshine_duration', 
			'global_tilted_irradiance' 
		]


		if not all(col in hourly_dataframe.columns for col in expected_columns):
			return pd.DataFrame()

		return hourly_dataframe

	except Exception as e:
		st.error(" ⚠️ We are currently experiencing issues retrieving the latest weather data. Please try again later  🚀")
		st.image("https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif", caption="Hang in there, we're working on it!")
		#st.write(f"Error details: {e}")  # log the error
		logging.error(f"Error occurred while fetching data: {e}")
		return pd.DataFrame()
	

if __name__ == "__main__":
	print(download_data())