Skip to content

Commit f1a229b

Browse files
authored
Merge pull request #37 from Mixss/new-weather-api
use new weather api
2 parents 15e48c3 + b2d530b commit f1a229b

File tree

6 files changed

+78
-85
lines changed

6 files changed

+78
-85
lines changed

data/birthdays/famous_people.csv

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
8,1,Elvis Presley,1935,,,,,,
99
9,1,Rodrygo,2001,Eric Garcia,2001,,,,
1010
10,1,Mason Mount,1999,,,,,,
11-
11,1,Albert Hofmann (odkrywca LSD),,1906,,,,,
11+
11,1,Albert Hofmann (odkrywca LSD),1906,,,,,,
1212
12,1,Jeff Bezos,1964,,,,,,
1313
13,1,Orlando Bloom,1977,,,,,,
1414
14,1,Gosia Andrzejewicz,1984,,,,,,

logic/advanced_forecast.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -60,17 +60,21 @@ def graph_rainfall(canvas, hours, rainfall, humidity):
6060

6161
def graph_wind(canvas, hours, wind_speed, wind_gust):
6262

63-
canvas.plot(hours, wind_speed, linewidth=3.0, color='#4189e8')
64-
canvas.hlines(wind_gust, xmin=[i - 0.2 for i, x in enumerate(hours)], xmax=[i + 0.2 for i, x in enumerate(hours)], colors='red', label='Podmuchy wiatru')
63+
canvas.plot(hours, [x * 0.539957 for x in wind_speed], linewidth=3.0, color='#4189e8')
64+
# canvas.set_ylim(canvas.get_ylim()[0] * 0.539957, canvas.get_ylim()[1] * 0.539957)
65+
canvas.hlines([x * 0.539957 for x in wind_gust], xmin=[i - 0.2 for i, x in enumerate(hours)], xmax=[i + 0.2 for i, x in enumerate(hours)], colors='red', label='Podmuchy wiatru')
66+
67+
# canvas.hlines(wind_gust, xmin=[i - 0.2 for i, x in enumerate(hours)], xmax=[i + 0.2 for i, x in enumerate(hours)], colors='red', label='Podmuchy wiatru')
6568

6669
canvas.margins(x=0.0)
6770

68-
canvas.set_ylabel('Prędkość wiatru [km/h]')
71+
canvas.set_ylabel('Prędkość wiatru [kt]')
6972

7073
secondary_canvas = canvas.twinx()
71-
secondary_canvas.plot(hours, [x * 1000 / 3600 for x in wind_speed], linewidth=3.0, color='#4189e8')
72-
secondary_canvas.set_ylim(canvas.get_ylim()[0] * 1000 / 3600, canvas.get_ylim()[1] * 1000 / 3600)
73-
secondary_canvas.set_ylabel('Prędkość wiatru [m/s]')
74+
# secondary_canvas.plot(hours, [x * 1000 / 3600 for x in wind_speed], linewidth=3.0, color='#4189e8')
75+
secondary_canvas.hlines([x * 0.539957 for x in wind_gust], xmin=[i - 0.2 for i, x in enumerate(hours)], xmax=[i + 0.2 for i, x in enumerate(hours)], colors='red', label='Podmuchy wiatru')
76+
secondary_canvas.set_ylim(canvas.get_ylim()[0], canvas.get_ylim()[1])
77+
secondary_canvas.set_ylabel('Porywy wiatru [kt]')
7478

7579
canvas.grid(True)
7680

logic/forecast_image.py

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020

2121
HOUR_VERT_OFFSET = 400
2222

23-
WIND_SPEED_LEFT_OFFSET = 20
23+
WIND_SPEED_LEFT_OFFSET = -30
2424
WIND_SPEED_TOP_OFFSET = 340
2525

2626

@@ -133,10 +133,11 @@ def draw_temperatures(image, temperatures, color, font_size):
133133

134134
counter = 0
135135
for line_x, temp in zip(lines, temperatures):
136+
temp = round(temp)
136137

137138
center_x = line_x + SPACE_BETWEEN_LINES / 2
138139

139-
text_x = center_x - unicode_font.getsize(str(temp) + "°C")[0] / 2
140+
text_x = center_x - unicode_font.getlength(str(temp) + "°C") / 2
140141

141142
if counter < 3:
142143
draw.text((int(text_x), TEMP_TOP_OFFSET), str(temp) + "°C", font=unicode_font, fill=color)
@@ -222,21 +223,25 @@ def draw_wind(image, wind_speeds, wind_directions, color, text_scale):
222223
rotated_arrow_image = rotation(resized_arrow_image, direction - 180)
223224

224225
if counter < 3:
225-
cv.putText(image, str(speed), (int(text_x) + WIND_SPEED_LEFT_OFFSET, WIND_SPEED_TOP_OFFSET), font,
226+
cv.putText(image, str(speed) + ' km/h', (int(text_x) + WIND_SPEED_LEFT_OFFSET, WIND_SPEED_TOP_OFFSET - 20), font,
227+
text_scale, color, 1, bottomLeftOrigin=False, lineType=cv.LINE_AA)
228+
cv.putText(image, str(round(speed * 0.539957, 1)) + ' kt', (int(text_x) + WIND_SPEED_LEFT_OFFSET + 5, WIND_SPEED_TOP_OFFSET + 30), font,
226229
text_scale, color, 1, bottomLeftOrigin=False, lineType=cv.LINE_AA)
227230

228231
text_y = text_size[1] / 2 + WIND_SPEED_TOP_OFFSET
229232

230-
overlay_image(image, rotated_arrow_image, int(text_x - 35),
233+
overlay_image(image, rotated_arrow_image, int(text_x - 80),
231234
int(text_y - rotated_arrow_image.shape[1] / 2 - 20))
232235
else:
233-
cv.putText(image, str(speed), (int(text_x) + WIND_SPEED_LEFT_OFFSET, WIND_SPEED_TOP_OFFSET +
234-
HOUR_VERT_OFFSET), font, text_scale, color, 1, bottomLeftOrigin=False,
236+
cv.putText(image, str(speed) + ' km/h', (int(text_x) + WIND_SPEED_LEFT_OFFSET, WIND_SPEED_TOP_OFFSET +
237+
HOUR_VERT_OFFSET - 20), font, text_scale, color, 1, bottomLeftOrigin=False,
235238
lineType=cv.LINE_AA)
239+
cv.putText(image, str(round(speed * 0.539957, 1)) + ' kt', (int(text_x) + WIND_SPEED_LEFT_OFFSET + 5, WIND_SPEED_TOP_OFFSET + HOUR_VERT_OFFSET + 30), font,
240+
text_scale, color, 1, bottomLeftOrigin=False, lineType=cv.LINE_AA)
236241

237242
text_y = text_size[1] / 2 + WIND_SPEED_TOP_OFFSET + HOUR_VERT_OFFSET
238243

239-
overlay_image(image, rotated_arrow_image, int(text_x - 35),
244+
overlay_image(image, rotated_arrow_image, int(text_x - 80),
240245
int(text_y - rotated_arrow_image.shape[1] / 2 - 20))
241246
counter += 1
242247

@@ -247,17 +252,17 @@ def generate_forecast_image():
247252

248253
image = np.full((IMAGE_HEIGHT, IMAGE_WIDTH, 3), MAIN_BACKGROUND_COLOR, dtype=np.uint8)
249254

250-
wind_speeds = wind_speeds[::2]
251-
wind_directions = wind_directions[::2]
252-
hours = hours[::2]
253-
temperatures = temperatures[::2]
254-
icons = icons[::2]
255+
wind_speeds = wind_speeds[8::2]
256+
wind_directions = wind_directions[8::2]
257+
hours = hours[8::2]
258+
temperatures = temperatures[8::2]
259+
icons = icons[8::2]
255260

256261
draw_lines(image)
257262
draw_hours(image, hours, (191, 188, 186), 1.0)
258263
image = draw_temperatures(image, temperatures, (221, 218, 216), 86)
259264
draw_icons(image, icons)
260-
draw_wind(image, wind_speeds, wind_directions, (191, 188, 186), 1.3)
265+
draw_wind(image, wind_speeds, wind_directions, (191, 188, 186), 1.2)
261266

262267
cv.imwrite("assets/generated_images/image.png", image)
263268

logic/logic.py

Lines changed: 33 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -154,8 +154,8 @@ def get_day_of_week_capitalized():
154154

155155
def get_sunset_sunrise():
156156
data = download_forecast(type="daily")
157-
sunrise = data["DailyForecasts"][0]["Sun"]["Rise"][11:16]
158-
sunset = data["DailyForecasts"][0]["Sun"]["Set"][11:16]
157+
sunrise = data['daily']['sunrise'][0][11:16]
158+
sunset = data['daily']['sunset'][0][11:16]
159159

160160
return sunrise, sunset
161161

@@ -202,49 +202,46 @@ def download_forecast(type='daily'):
202202
if not Path('data/forecast_daily.json').exists():
203203
print(f"{datetime.today()}: forecast_daily.json doesn't exist, downloading new one")
204204
with urllib.request.urlopen(
205-
"http://dataservice.accuweather.com/forecasts/v1/daily/1day/275174?apikey"
206-
"=GZcekJNnnT8F1qo8VJteym6lRa54mH2b&language=pl-pl&details=true&metric=true") as url:
205+
"https://api.open-meteo.com/v1/forecast?latitude=54.3523&longitude=18.6491&daily=sunrise,sunset,uv_index_max&hourly=temperature_2m,rain,wind_speed_10m,wind_direction_10m,relative_humidity_2m,weather_code,apparent_temperature,wind_gusts_10m&timezone=auto&forecast_days=1") as url:
207206
data = json.loads(url.read())
208207
with open("data/forecast_daily.json", "w") as new_forecast:
209208
json.dump(data, new_forecast)
210209

211210
with open("data/forecast_daily.json") as file:
212211
data = json.load(file)
213-
date_of_download = data["DailyForecasts"][0]["Date"][:10]
212+
date_of_download = data['hourly']['time'][0][:10]
214213
todays_date = f"{datetime.today()}"[:10]
215214

216215
if date_of_download != todays_date:
217216
# forecast data is outdated
218217
print("Downloading new file: forecast_daily.json")
219218

220219
with urllib.request.urlopen(
221-
"http://dataservice.accuweather.com/forecasts/v1/daily/1day/275174?apikey"
222-
"=GZcekJNnnT8F1qo8VJteym6lRa54mH2b&language=pl-pl&details=true&metric=true") as url:
220+
"https://api.open-meteo.com/v1/forecast?latitude=54.3523&longitude=18.6491&daily=sunrise,sunset,uv_index_max&hourly=temperature_2m,rain,wind_speed_10m,wind_direction_10m,relative_humidity_2m,weather_code,apparent_temperature,wind_gusts_10m&timezone=auto&forecast_days=1") as url:
223221
data = json.loads(url.read())
224222
with open("data/forecast_daily.json", "w") as new_forecast:
225223
json.dump(data, new_forecast)
226224

227225
return data
228226
if type == 'hourly':
229227
if not Path('data/forecast_12_hours.json').exists():
230-
with urllib.request.urlopen("http://dataservice.accuweather.com/forecasts/v1/hourly/12hour/275174?apikey"
231-
"=GZcekJNnnT8F1qo8VJteym6lRa54mH2b&language=pl-pl&details=true&metric=true") \
228+
with urllib.request.urlopen("https://api.open-meteo.com/v1/forecast?latitude=54.3523&longitude=18.6491&daily=sunrise,sunset,uv_index_max&hourly=temperature_2m,rain,wind_speed_10m,wind_direction_10m,relative_humidity_2m,weather_code,apparent_temperature,wind_gusts_10m&timezone=auto&forecast_days=1") \
232229
as url:
233230
data = json.loads(url.read())
234231
with open("data/forecast_12_hours.json", "w") as new_forecast:
235232
json.dump(data, new_forecast)
236233

237234
with open("data/forecast_12_hours.json") as file:
238235
data = json.load(file)
239-
date_of_download = data[0]["DateTime"][:10]
236+
237+
date_of_download = data['hourly']['time'][0][:10]
240238
todays_date = f"{datetime.today()}"[:10]
241239

242240
if date_of_download != todays_date:
243241
# forecast data is outdated
244242
print("Downloading new file: forecast_12_hours.json")
245243

246-
with urllib.request.urlopen("http://dataservice.accuweather.com/forecasts/v1/hourly/12hour/275174?apikey"
247-
"=GZcekJNnnT8F1qo8VJteym6lRa54mH2b&language=pl-pl&details=true&metric=true") \
244+
with urllib.request.urlopen("https://api.open-meteo.com/v1/forecast?latitude=54.3523&longitude=18.6491&daily=sunrise,sunset,uv_index_max&hourly=temperature_2m,rain,wind_speed_10m,wind_direction_10m,relative_humidity_2m,weather_code,apparent_temperature,wind_gusts_10m&timezone=auto&forecast_days=1") \
248245
as url:
249246
data = json.loads(url.read())
250247
with open("data/forecast_12_hours.json", "w") as new_forecast:
@@ -258,37 +255,30 @@ def download_forecast(type='daily'):
258255
def get_daily_forecast():
259256
data = download_forecast(type='daily')
260257

261-
headline = data["Headline"]["Text"]
262-
minTemp = round(data["DailyForecasts"][0]["Temperature"]["Minimum"]["Value"])
263-
maxTemp = round(data["DailyForecasts"][0]["Temperature"]["Maximum"]["Value"])
264-
info = data["DailyForecasts"][0]["Day"]["LongPhrase"]
265-
rain = data["DailyForecasts"][0]["Day"]["RainProbability"]
266-
air = data["DailyForecasts"][0]["AirAndPollen"][0]["Category"]
267-
uvindex = data["DailyForecasts"][0]["AirAndPollen"][5]["Value"]
268-
uvdanger = data["DailyForecasts"][0]["AirAndPollen"][5]["Category"]
269-
try:
270-
moon = moon_phases[data["DailyForecasts"][0]["Moon"]["Phase"]]
271-
except KeyError:
272-
moon = data["DailyForecasts"][0]["Moon"]["Phase"]
258+
# headline = data["Headline"]["Text"]
259+
# minTemp = round(data["DailyForecasts"][0]["Temperature"]["Minimum"]["Value"])
260+
# maxTemp = round(data["DailyForecasts"][0]["Temperature"]["Maximum"]["Value"])
261+
# info = data["DailyForecasts"][0]["Day"]["LongPhrase"]
262+
# rain = data["DailyForecasts"][0]["Day"]["RainProbability"]
263+
# air = data["DailyForecasts"][0]["AirAndPollen"][0]["Category"]
264+
# uvindex = data["DailyForecasts"][0]["AirAndPollen"][5]["Value"]
265+
# uvdanger = data["DailyForecasts"][0]["AirAndPollen"][5]["Category"]
266+
# try:
267+
# moon = moon_phases[data["DailyForecasts"][0]["Moon"]["Phase"]]
268+
# except KeyError:
269+
# moon = data["DailyForecasts"][0]["Moon"]["Phase"]
273270

274271
return headline, minTemp, maxTemp, info, rain, air, uvindex, uvdanger, moon
275272

276273

277274
def get_hourly_forecast():
278275
data = download_forecast(type='hourly')
279276

280-
hours = []
281-
temperatures = []
282-
icons = []
283-
wind_speeds = []
284-
wind_directions = []
285-
286-
for one_hour in data:
287-
hours.append(one_hour["DateTime"][11:13])
288-
temperatures.append(round(one_hour["Temperature"]["Value"]))
289-
icons.append(one_hour["WeatherIcon"])
290-
wind_speeds.append(one_hour["Wind"]["Speed"]["Value"])
291-
wind_directions.append(one_hour["Wind"]["Direction"]["Degrees"])
277+
hours = [h[11:13] for h in data['hourly']['time']]
278+
temperatures = [t for t in data['hourly']['temperature_2m']]
279+
icons = [i for i in data['hourly']['weather_code']]
280+
wind_speeds = [w for w in data['hourly']['wind_speed_10m']]
281+
wind_directions = [w for w in data['hourly']['wind_direction_10m']]
292282

293283
return hours, temperatures, icons, wind_speeds, wind_directions
294284

@@ -299,24 +289,15 @@ def get_advanced_hourly_forecast():
299289
# hours, temperature, temperature_feel, rainfall, humidity, wind_speed, wind_gust
300290

301291
forecast = {
302-
'hours': [],
303-
'temperature': [],
304-
'temperature_feel': [],
305-
'rainfall': [],
306-
'humidity': [],
307-
'wind_speed': [],
308-
'wind_gust': [],
292+
'hours': [h[11:13] for h in data['hourly']['time']],
293+
'temperature': [t for t in data['hourly']['temperature_2m']],
294+
'temperature_feel': [t for t in data['hourly']['apparent_temperature']],
295+
'rainfall': [r for r in data['hourly']['rain']],
296+
'humidity': [h for h in data['hourly']['relative_humidity_2m']],
297+
'wind_speed': [w for w in data['hourly']['wind_speed_10m']],
298+
'wind_gust': [w for w in data['hourly']['wind_gusts_10m']],
309299
}
310300

311-
for sample in data:
312-
forecast['hours'].append(sample['DateTime'][11:13])
313-
forecast['temperature'].append(sample['Temperature']['Value'])
314-
forecast['temperature_feel'].append(sample['RealFeelTemperature']['Value'])
315-
forecast['rainfall'].append(sample['TotalLiquid']['Value'])
316-
forecast['humidity'].append(sample['RelativeHumidity'])
317-
forecast['wind_speed'].append(sample['Wind']['Speed']['Value'])
318-
forecast['wind_gust'].append(sample['WindGust']['Speed']['Value'])
319-
320301
return forecast
321302

322303

requirements.txt

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
1-
nextcord
1+
nextcord~=3.0.1
22

3-
matplotlib
4-
numpy
5-
scipy
3+
matplotlib~=3.10.0
4+
numpy~=2.2.2
5+
scipy~=1.15.1
66

7-
pillow<=9.5.0
7+
pillow~=11.1.0
88
opencv-python-headless==4.5.5.64
9-
bs4
10-
requests
9+
bs4~=0.0.2
10+
requests~=2.32.3
1111
setuptools
12+
opencv-python
13+
14+
beautifulsoup4~=4.13.3

ui/message_templates.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99

1010
async def daily_stats_embed(image_path, our_server=False):
11-
_, _, _, _, _, air_quality, uvidex, _, moon_phase = get_daily_forecast()
11+
# _, _, _, _, _, air_quality, uvidex, _, moon_phase = get_daily_forecast()
1212
birthday_message, num_of_birthdays = await get_birthday_message(our_server)
1313

1414
embed = nextcord.Embed(title=f'Statystyki na dzień **{get_today()}** ({get_day_of_week()}):',
@@ -24,10 +24,10 @@ async def daily_stats_embed(image_path, our_server=False):
2424
embed.add_field(name='🌇 Zachód słońca', value=get_sunset_sunrise()[1] + '\n‎', inline=True)
2525

2626
embed.add_field(name='👫 Imieniny', value=get_today_names() + '\n‎', inline=True)
27-
embed.add_field(name='Faza księżyca', value=moon_phase + '\n‎', inline=True)
28-
29-
embed.add_field(name='😷 Jakość powietrza', value=air_quality + '\n‎', inline=True)
30-
embed.add_field(name='😎 Index UV', value=str(uvidex) + '\n‎', inline=True)
27+
# embed.add_field(name='Faza księżyca', value=moon_phase + '\n‎', inline=True)
28+
#
29+
# embed.add_field(name='😷 Jakość powietrza', value=air_quality + '\n‎', inline=True)
30+
# embed.add_field(name='😎 Index UV', value=str(uvidex) + '\n‎', inline=True)
3131

3232
embed.add_field(name='⛅ Prognoza pogody', value=' ', inline=False)
3333

@@ -120,4 +120,4 @@ def help_message_embed():
120120
'prognozę pogody, ceny walut, paliwa itd\n‎', inline=False)
121121
embed.add_field(name='/weather', value='Wyświetla aktualną prognozę pogody w Gdańsku w pigułce')
122122

123-
return embed
123+
return embed

0 commit comments

Comments
 (0)