-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweather-new.py
executable file
·423 lines (372 loc) · 14.6 KB
/
weather-new.py
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
#!/usr/bin/python3 -u
"""
Description: Newer OpenMeteo weather module that takes a zip code as an
argument instead of in a config file.
Author: thnikk
"""
from datetime import datetime, timedelta
import json
import os
import argparse
import requests
from common import print_debug, Cache
import tooltip as tt
def parse_args():
""" Parse arguments """
parser = argparse.ArgumentParser(
description="Get weather formatted for waybar")
parser.add_argument(
'zip', type=str, help="Zip code")
parser.add_argument(
'-n', action='store_true', help="Enable night icons")
parser.add_argument(
'-f', type=int, const=5, nargs='?',
help="How many hours to show in tooltip (default is 5)")
return parser.parse_args()
class OpenMeteo(): # pylint: disable=too-few-public-methods
""" Class for OpenMeteo """
def __init__(self, zip_code):
""" Initialize class"""
geo = self.__cache__(
os.path.expanduser(f"~/.cache/geocode-{zip_code}.json"),
"https://geocoding-api.open-meteo.com/v1/search",
{
"name": zip_code, "count": 1,
"language": "en", "format": "json"
},
zip_code
)
self.latitude = geo['results'][0]['latitude']
self.longitude = geo['results'][0]['longitude']
self.timezone = geo['results'][0]['timezone']
self.city = geo['results'][0]['name']
self.weather = Weather(
self.latitude, self.longitude, self.timezone, zip_code)
self.pollution = Pollution(
self.latitude, self.longitude, self.timezone, zip_code)
def __cache__(self, path, url, qs, zip_code):
""" Update cache file if enough time has passed. """
cache = Cache(path)
try:
data = cache.load()
if str(zip_code) not in data['results'][0]['postcodes']:
raise ValueError("Updated postcode")
# print_debug(f"Loading data from cache at {path}.")
except (FileNotFoundError, ValueError):
try:
print_debug("Fetching new geocode data.")
data = requests.get(url, params=qs, timeout=3).json()
cache.save(data)
except requests.exceptions.ConnectionError:
data = cache.load()
return data
def lookup(code, mode, night=False):
""" Get description for weather code """
weather_lookup = {
0: ["", "Clear"],
1: ["", "Mostly clear"],
2: ["", "Partly cloudy"],
3: ["", "Overcast"],
45: ["", "Fog"],
48: ["", "Depositing rime fog"],
51: ["", "Light drizzle"],
53: ["", "Moderate drizzle"],
55: ["", "Dense drizzle"],
56: ["", "Light freezing drizzle"],
57: ["", "Dense freezing drizzle"],
61: ["", "Slight rain"],
63: ["", "Moderate rain"],
65: ["", "Heavy rain"],
66: ["", "Light freezing rain"],
67: ["", "Heavy freezing rain"],
71: ["", "Slight snow"],
73: ["", "Moderate snow"],
75: ["", "Heavy snow"],
77: ["", "Snow grains"],
80: ["", "Slight rain showers"],
81: ["", "Moderate rain showers"],
82: ["", "Violent rain showers"],
85: ["", "Slight snow showers"],
86: ["", "Heavy snow showers"],
95: ["", "Thunderstorm"],
96: ["", "Slight hailing thunderstorm"],
99: ["", "Heavy hailing thunderstorm"]
}
if night:
weather_lookup[0][0] = ""
weather_lookup[1][0] = ""
weather_lookup[2][0] = ""
return weather_lookup[code][mode]
class Weather(): # pylint: disable=too-few-public-methods
""" Get daily weather data """
def __init__(self, lat, lon, timezone, zip_code):
weather = self.__cache__(
os.path.expanduser(f"~/.cache/weather-{zip_code}.json"),
"https://api.open-meteo.com/v1/forecast",
{
"latitude": lat, "longitude": lon,
"hourly": [
"temperature_2m", "relativehumidity_2m", "weathercode",
"windspeed_10m", "winddirection_10m",
"apparent_temperature"
],
"daily": [
"weathercode", "temperature_2m_max", "temperature_2m_min",
"sunrise,sunset", "wind_speed_10m_max",
"wind_direction_10m_dominant"
],
"temperature_unit": "fahrenheit",
"timezone": timezone,
},
timedelta(hours=1)
)
self.hourly = Hourly(weather)
self.daily = Daily(weather)
def __cache__(self, path, url, qs, delta) -> dict:
""" Update cache file if enough time has passed. """
cache = Cache(path)
try:
mtime = datetime.fromtimestamp(os.path.getmtime(path))
if (datetime.now() - mtime) > delta:
raise ValueError('old')
data = cache.load()
# print_debug(f"Loading data from cache at {path}.")
except (FileNotFoundError, ValueError):
try:
print_debug("Fetching new data.")
data = requests.get(url, params=qs, timeout=3).json()
cache.save(data)
except requests.exceptions.ConnectionError:
data = cache.load()
return data
class Hourly():
""" Parse hourly data and split into objects """
def __init__(self, weather):
self.weathercodes = weather['hourly']['weathercode']
self.temperatures = weather['hourly']['temperature_2m']
self.feelslikes = weather['hourly']['apparent_temperature']
self.windspeeds = weather['hourly']['windspeed_10m']
self.humidities = weather['hourly']['relativehumidity_2m']
def code(self, index):
""" Get weathercode """
return self.weathercodes[index]
def description(self, index):
""" Get description """
return lookup(self.code(index), 1)
def icon(self, index, night=False):
""" Get icon """
return lookup(self.code(index), 0, night)
def temp(self, index):
""" Get temperature """
return round(self.temperatures[index])
def feelslike(self, index):
""" Get temperature """
return round(self.feelslikes[index])
def wind(self, index):
""" Get windspeed """
return self.windspeeds[index]
def humidity(self, index):
""" Get humidity """
return self.humidities[index]
class Daily():
""" Parse daily data and split into objects """
def __init__(self, weather):
self.sunrise = int(datetime.strptime(
weather["daily"]["sunrise"][0],
"%Y-%m-%dT%H:%M").strftime("%H"))
self.sunset = int(datetime.strptime(
weather["daily"]["sunset"][0],
"%Y-%m-%dT%H:%M").strftime("%H"))
self.weathercodes = weather['daily']['weathercode']
self.lows = weather['daily']['temperature_2m_min']
self.highs = weather['daily']['temperature_2m_max']
self.windspeeds = weather['daily']['wind_speed_10m_max']
self.winddirs = weather['daily']['wind_direction_10m_dominant']
def code(self, index):
""" Get weathercode """
return self.weathercodes[index]
def description(self, index) -> str:
""" Get description of weather """
return lookup(self.code(index), 1)
def icon(self, index, night=False):
""" Get icon """
return lookup(self.code(index), 0, night)
def low(self, index) -> int:
""" Get min temperature """
return round(self.lows[index])
def high(self, index) -> int:
""" Get max temperature """
return round(self.highs[index])
def wind(self, index) -> int:
""" Get max wind speed """
return round(self.windspeeds[index])
def direction(self, index) -> int:
""" Get max wind speed """
return round(self.winddirs[index])
class Pollution():
""" Get daily polution data """
def __init__(self, lat, lon, timezone, zip_code) -> None:
pollution = self.__cache__(
os.path.expanduser(f"~/.cache/pollution-{zip_code}.json"),
"https://air-quality-api.open-meteo.com/v1/air-quality",
{
"latitude": lat, "longitude": lon, "hourly": "us_aqi",
"timezone": timezone,
},
timedelta(days=1)
)
self.aqi = pollution["hourly"]["us_aqi"]
def __cache__(self, path, url, qs, delta) -> dict:
""" Update cache file if enough time has passed. """
cache = Cache(path)
try:
mtime = datetime.fromtimestamp(os.path.getmtime(path))
if (datetime.now() - mtime) > delta:
raise ValueError('old')
data = cache.load()
# print_debug(f"Loading data from cache at {path}.")
except (FileNotFoundError, ValueError):
try:
print_debug("Fetching new data.")
data = requests.get(url, params=qs, timeout=3).json()
cache.save(data)
except requests.exceptions.ConnectionError:
data = cache.load()
return data
def __aqi_to_desc__(self, value) -> str:
""" Get description for aqi """
for desc in [
(50, "Good"), (100, "Moderate"), (150, "Unhealthy"),
(200, "Unhealthy"), (300, "Very unhealthy"), (500, "Hazardous")
]:
if 0 < value < desc[0]:
return desc[1]
return "Unknown"
def description(self, index) -> str:
""" Get air quality description for given hour """
return self.__aqi_to_desc__(self.aqi[index])
def tooltip(om, index, hours) -> str:
""" Generate tooltip """
if om.weather.daily.sunset > index > om.weather.daily.sunrise:
sun_status = f"Sunset at {om.weather.daily.sunset - 12}PM\n"
else:
sun_status = f"Sunrise at {om.weather.daily.sunrise}AM\n"
output = (
tt.heading('Today') + '\n'
f"City: {om.city}\n"
f"Description: {om.weather.hourly.description(index)}\n"
f"Temperature: {om.weather.hourly.temp(index)}\n"
f"Feels like: {om.weather.hourly.feelslike(index)}\n"
f"Humidity: {om.weather.hourly.humidity(index)}%\n"
f"Wind: {om.weather.hourly.wind(index)} mph\n"
f"Air quality: {om.pollution.description(index)}\n"
f"{sun_status}"
'\n' + tt.heading('Hourly forecast') + '\n'
)
hourly_output = []
for hour in range(1, (hours or 5) + 1):
hour_index = int(
(datetime.now() + timedelta(hours=hour)).strftime('%H'))
text = (datetime.now() + timedelta(hours=hour)).strftime("%l%P")
hourly_output.append(
f"{text}: {om.weather.hourly.temp(hour_index)} "
f"{om.weather.hourly.description(hour_index)}"
)
# Strip whitespace from hour if all shown hours have whitespace
if set(item[0] for item in hourly_output) == {' '}:
hourly_output = [item[1:] for item in hourly_output]
output += "\n".join(hourly_output) + "\n"
output += '\n' + tt.heading('Weekly forecast') + '\n'
for day in range(0, 6):
abbr = (datetime.now() + timedelta(days=day)).strftime('%A')[:2]
output += (
f"{abbr}: "
f"{om.weather.daily.low(day)}/{om.weather.daily.high(day)} "
f"{om.weather.daily.wind(day)} "
f"{om.weather.daily.description(day)}\n"
)
return output.strip()
def widget(om, index, hours, night) -> dict:
""" Generate tooltip """
hourly = om.weather.hourly
night_now = (
om.weather.daily.sunrise > datetime.now().hour
or datetime.now().hour > om.weather.daily.sunset) and night
output = {
"City": om.city,
"Today": {
"icon-class": "icon-large",
"info": [{
"icon": hourly.icon(index, night_now),
"description": hourly.description(index),
"temperature": hourly.temp(index),
"feels_like": hourly.feelslike(index),
"humidity": hourly.humidity(index),
"wind": hourly.wind(index),
"quality": om.pollution.description(index)
}]
},
"Hourly": {
"icon-class": "icon-small"
},
"Daily": {
"icon-class": "icon-medium"
}
}
if om.weather.daily.sunset > index > om.weather.daily.sunrise:
output["Today"]["info"][0]["sunset"] = om.weather.daily.sunset - 12
else:
output["Today"]["info"][0]["sunrise"] = om.weather.daily.sunrise
hourly_output = []
for hour in range(1, (hours or 5) + 1):
hour_index = int(
(datetime.now() + timedelta(hours=hour)).strftime('%H'))
text = (datetime.now() + timedelta(hours=hour)).strftime("%l%P")
night_hour = (
om.weather.daily.sunrise > hour_index
or hour_index > om.weather.daily.sunset) and night
hourly_output.append({
"icon": om.weather.hourly.icon(hour_index, night_hour),
"description": om.weather.hourly.description(hour_index),
"humidity": om.weather.hourly.humidity(hour_index),
"time": text,
"temperature": om.weather.hourly.temp(hour_index)
})
output["Hourly"]["info"] = hourly_output
daily_output = []
for day in range(0, 5):
abbr = (datetime.now() + timedelta(days=day)).strftime('%A')
daily_output.append({
"time": abbr,
"high": om.weather.daily.high(day),
"low": om.weather.daily.low(day),
"wind": om.weather.daily.wind(day),
"description": om.weather.daily.description(day),
"icon": om.weather.daily.icon(day)
})
output["Daily"]["info"] = daily_output
with open(
os.path.expanduser('~/.cache/weather-widget.json'),
'w', encoding='utf-8'
) as file:
file.write(json.dumps(output, indent=4))
return output
def main():
""" Main function """
args = parse_args()
om = OpenMeteo(args.zip)
now = datetime.now()
hour_now = int(now.strftime('%H'))
night = (
om.weather.daily.sunrise > hour_now
or hour_now > om.weather.daily.sunset) and args.n
print(json.dumps(
{
"text": f"{om.weather.hourly.icon(hour_now, night)} "
f"{om.weather.hourly.temp(hour_now)}°F",
"tooltip": tooltip(om, hour_now, args.f),
"widget": widget(om, hour_now, args.f, args.n)
}
))
if __name__ == "__main__":
main()