forked from MycroftAI/skill-weather
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__init__.py
More file actions
1833 lines (1563 loc) · 70.9 KB
/
__init__.py
File metadata and controls
1833 lines (1563 loc) · 70.9 KB
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2017, Mycroft AI Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import pytz
import time
from copy import deepcopy
from datetime import datetime, timedelta
from multi_key_dict import multi_key_dict
from pyowm.webapi25.forecaster import Forecaster
from pyowm.webapi25.forecastparser import ForecastParser
from pyowm.webapi25.observationparser import ObservationParser
from requests import HTTPError, Response
import mycroft.audio
from adapt.intent import IntentBuilder
from mycroft.api import Api
from mycroft import MycroftSkill, intent_handler
from mycroft.messagebus.message import Message
from mycroft.util.log import LOG
from mycroft.util.format import (nice_date, nice_time, nice_number,
pronounce_number, join_list)
from mycroft.util.parse import extract_datetime, extract_number
from mycroft.util.time import now_local, to_utc, to_local
MINUTES = 60 # Minutes to seconds multiplier
class LocationNotFoundError(ValueError):
pass
APIErrors = (LocationNotFoundError, HTTPError)
"""
This skill uses the Open Weather Map API (https://openweathermap.org) and
the PyOWM wrapper for it. For more info, see:
General info on PyOWM
https://www.slideshare.net/csparpa/pyowm-my-first-open-source-project
OWM doc for APIs used
https://openweathermap.org/current - current
https://openweathermap.org/forecast5 - three hour forecast
https://openweathermap.org/forecast16 - daily forecasts
PyOWM docs
https://media.readthedocs.org/pdf/pyowm/latest/pyowm.pdf
"""
# Windstrength limits in miles per hour
WINDSTRENGTH_MPH = {
'hard': 20,
'medium': 11
}
# Windstrenght limits in m/s
WINDSTRENGTH_MPS = {
'hard': 9,
'medium': 5
}
class OWMApi(Api):
''' Wrapper that defaults to the Mycroft cloud proxy so user's don't need
to get their own OWM API keys '''
def __init__(self):
super(OWMApi, self).__init__("owm")
self.owmlang = "en"
self.encoding = "utf8"
self.observation = ObservationParser()
self.forecast = ForecastParser()
self.query_cache = {}
self.location_translations = {}
@staticmethod
def get_language(lang):
"""
OWM supports 31 languages, see https://openweathermap.org/current#multi
Convert language code to owm language, if missing use 'en'
"""
owmlang = 'en'
# some special cases
if lang == 'zh-zn' or lang == 'zh_zn':
return 'zh_zn'
elif lang == 'zh-tw' or lang == 'zh_tw':
return 'zh_tw'
# special cases cont'd
lang = lang.lower().split("-")
lookup = {
'sv': 'se',
'cs': 'cz',
'ko': 'kr',
'lv': 'la',
'uk': 'ua'
}
if lang[0] in lookup:
return lookup[lang[0]]
owmsupported = ['ar', 'bg', 'ca', 'cz', 'da', 'de', 'el', 'en', 'fa', 'fi',
'fr', 'gl', 'hr', 'hu', 'it', 'ja', 'kr', 'la', 'lt',
'mk', 'nl', 'pl', 'pt', 'ro', 'ru', 'se', 'sk', 'sl',
'es', 'tr', 'ua', 'vi']
if lang[0] in owmsupported:
owmlang = lang[0]
if (len(lang) == 2):
if lang[1] in owmsupported:
owmlang = lang[1]
return owmlang
def build_query(self, params):
params.get("query").update({"lang": self.owmlang})
return params.get("query")
def request(self, data):
""" Caching the responses """
req_hash = hash(json.dumps(data, sort_keys=True))
cache = self.query_cache.get(req_hash, (0, None))
# check for caches with more days data than requested
if data['query'].get('cnt') and cache == (0, None):
test_req_data = deepcopy(data)
while test_req_data['query']['cnt'] < 16 and cache == (0, None):
test_req_data['query']['cnt'] += 1
test_hash = hash(json.dumps(test_req_data, sort_keys=True))
test_cache = self.query_cache.get(test_hash, (0, None))
if test_cache != (0, None):
cache = test_cache
# Use cached response if value exists and was fetched within 15 min
now = time.monotonic()
if now > (cache[0] + 15 * MINUTES) or cache[1] is None:
resp = super().request(data)
# 404 returned as JSON-like string in some instances
if isinstance(resp, str) and '{"cod":"404"' in resp:
r = Response()
r.status_code = 404
raise HTTPError(resp, response=r)
self.query_cache[req_hash] = (now, resp)
else:
LOG.debug('Using cached OWM Response from {}'.format(cache[0]))
resp = cache[1]
return resp
def get_data(self, response):
return response.text
def weather_at_location(self, name):
if name == '':
raise LocationNotFoundError('The location couldn\'t be found')
q = {"q": name}
try:
data = self.request({
"path": "/weather",
"query": q
})
return self.observation.parse_JSON(data), name
except HTTPError as e:
if e.response.status_code == 404:
name = ' '.join(name.split()[:-1])
return self.weather_at_location(name)
raise
def weather_at_place(self, name, lat, lon):
if lat and lon:
q = {"lat": lat, "lon": lon}
else:
if name in self.location_translations:
name = self.location_translations[name]
response, trans_name = self.weather_at_location(name)
self.location_translations[name] = trans_name
return response
data = self.request({
"path": "/weather",
"query": q
})
return self.observation.parse_JSON(data)
def three_hours_forecast(self, name, lat, lon):
if lat and lon:
q = {"lat": lat, "lon": lon}
else:
if name in self.location_translations:
name = self.location_translations[name]
q = {"q": name}
data = self.request({
"path": "/forecast",
"query": q
})
return self.to_forecast(data, "3h")
def _daily_forecast_at_location(self, name, limit):
if name in self.location_translations:
name = self.location_translations[name]
orig_name = name
while name != '':
try:
q = {"q": name}
if limit is not None:
q["cnt"] = limit
data = self.request({
"path": "/forecast/daily",
"query": q
})
forecast = self.to_forecast(data, 'daily')
self.location_translations[orig_name] = name
return forecast
except HTTPError as e:
if e.response.status_code == 404:
# Remove last word in name
name = ' '.join(name.split()[:-1])
raise LocationNotFoundError('The location couldn\'t be found')
def daily_forecast(self, name, lat, lon, limit=None):
if lat and lon:
q = {"lat": lat, "lon": lon}
else:
return self._daily_forecast_at_location(name, limit)
if limit is not None:
q["cnt"] = limit
data = self.request({
"path": "/forecast/daily",
"query": q
})
return self.to_forecast(data, "daily")
def to_forecast(self, data, interval):
forecast = self.forecast.parse_JSON(data)
if forecast is not None:
forecast.set_interval(interval)
return Forecaster(forecast)
else:
return None
def set_OWM_language(self, lang):
self.owmlang = lang
# Certain OWM condition information is encoded using non-utf8
# encodings. If another language needs similar solution add them to the
# encodings dictionary
encodings = {
'se': 'latin1'
}
self.encoding = encodings.get(lang, 'utf8')
class WeatherSkill(MycroftSkill):
def __init__(self):
super().__init__("WeatherSkill")
# Build a dictionary to translate OWM weather-conditions
# codes into the Mycroft weather icon codes
# (see https://openweathermap.org/weather-conditions)
self.CODES = multi_key_dict()
self.CODES['01d', '01n'] = 0 # clear
self.CODES['02d', '02n', '03d', '03n'] = 1 # partly cloudy
self.CODES['04d', '04n'] = 2 # cloudy
self.CODES['09d', '09n'] = 3 # light rain
self.CODES['10d', '10n'] = 4 # raining
self.CODES['11d', '11n'] = 5 # stormy
self.CODES['13d', '13n'] = 6 # snowing
self.CODES['50d', '50n'] = 7 # windy/misty
# Use Mycroft proxy if no private key provided
self.settings["api_key"] = None
self.settings["use_proxy"] = True
def initialize(self):
# TODO: Remove lat,lon parameters from the OWMApi()
# methods and implement _at_coords() versions
# instead to make the interfaces compatible
# again.
#
# if self.settings["api_key"] and not self.settings['use_proxy']):
# self.owm = OWM(self.settings["api_key"])
# else:
# self.owm = OWMApi()
self.owm = OWMApi()
if self.owm:
self.owm.set_OWM_language(lang=OWMApi.get_language(self.lang))
self.schedule_for_daily_use()
try:
self.mark2_forecast(self.__initialize_report(None))
except Exception as e:
self.log.warning('Could not prepare forecasts. '
'({})'.format(repr(e)))
# Register for handling idle/resting screen
msg_type = '{}.{}'.format(self.skill_id, 'idle')
self.add_event(msg_type, self.handle_idle)
self.add_event('mycroft.mark2.collect_idle',
self.handle_collect_request)
# self.test_screen() # DEBUG: Used during screen testing/debugging
def test_screen(self):
self.gui["current"] = 72
self.gui["min"] = 83
self.gui["max"] = 5
self.gui["location"] = "kansas city"
self.gui["condition"] = "sunny"
self.gui["icon"] = "sunny"
self.gui["weathercode"] = 0
self.gui["humidity"] = "100%"
self.gui["wind"] = "--"
self.gui.show_page('weather.qml')
def prime_weather_cache(self):
# If not already cached, this will reach out for current conditions
report = self.__initialize_report(None)
try:
self.owm.weather_at_place(
report['full_location'], report['lat'],
report['lon']).get_weather()
self.owm.daily_forecast(report['full_location'],
report['lat'], report['lon'], limit=16)
except Exception as e:
self.log.error('Failed to prime weather cache '
'({})'.format(repr(e)))
def schedule_for_daily_use(self):
# Assume the user has a semi-regular schedule. Whenever this method
# is called, it will establish a 45 minute window of pre-cached
# weather info for the next day allowing for snappy responses to the
# daily query.
self.prime_weather_cache()
self.cancel_scheduled_event("precache1")
self.cancel_scheduled_event("precache2")
self.cancel_scheduled_event("precache3")
self.schedule_repeating_event(self.prime_weather_cache, None,
60*60*24, # One day in seconds
name="precache1")
self.schedule_repeating_event(self.prime_weather_cache, None,
60*60*24-60*15, # One day - 15 minutes
name="precache2")
self.schedule_repeating_event(self.prime_weather_cache, None,
60*60*24+60*15, # One day + 15 minutes
name="precache3")
def handle_collect_request(self, message):
self.bus.emit(Message('mycroft.mark2.register_idle',
data={'name': 'Weather',
'id': self.skill_id}))
def handle_idle(self, message):
self.gui.show_page('idle.qml')
def get_coming_days_forecast(self, forecast, unit, days=None):
"""
Get weather forcast for the coming days and returns them as a list
Parameters:
forecast: OWM weather
unit: Temperature unit
dt: Reference time
days: number of days to get forecast for, defaults to 4
Returns: List of dicts containg weather info
"""
days = days or 4
weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
forecast_list = []
# Get tomorrow and 4 days forward
for weather in list(forecast.get_weathers())[1:5]:
result_temp = weather.get_temperature(unit)
day_num = datetime.weekday(
datetime.fromtimestamp(weather.get_reference_time()))
result_temp_day = weekdays[day_num]
forecast_list.append({
"weathercode": self.CODES[weather.get_weather_icon_name()],
"max": round(result_temp['max']),
"min": round(result_temp['min']),
"date": result_temp_day
})
return forecast_list
def mark2_forecast(self, report):
""" Builds forecast for the upcoming days for the Mark-2 display."""
future_weather = self.owm.daily_forecast(report['full_location'],
report['lat'],
report['lon'], limit=5)
if future_weather is None:
self.__report_no_data('weather')
return
f = future_weather.get_forecast()
forecast_list = self.get_coming_days_forecast(
f, self.__get_temperature_unit())
if "gui" in dir(self):
forecast = {}
forecast['first'] = forecast_list[0:2]
forecast['second'] = forecast_list[2:4]
self.gui['forecast'] = forecast
# DATETIME BASED QUERIES
# Handle: what is the weather like?
@intent_handler(IntentBuilder("").one_of("Weather", "Forecast")
.require("Query").optionally("Location")
.optionally("Today").build())
def handle_current_weather(self, message):
try:
self.log.debug("Handler: handle_current_weather")
# Get a date from requests like "weather for next Tuesday"
today, _ = self.__extract_datetime("today")
when, _ = self.__extract_datetime(message.data.get('utterance'),
lang=self.lang)
if when and when != today:
self.log.debug("Doing a forecast {} {}".format(today, when))
return self.handle_forecast(message)
report = self.__populate_report(message)
if report is None:
self.__report_no_data('weather')
return
self.__report_weather(
"current", report,
separate_min_max='Location' not in message.data)
self.mark2_forecast(report)
# Establish the daily cadence
self.schedule_for_daily_use()
except APIErrors as e:
self.log.exception(repr(e))
self.__api_error(e)
except Exception as e:
self.log.exception("Error: {0}".format(e))
@intent_handler("whats.weather.like.intent")
def handle_current_weather_alt(self, message):
self.handle_current_weather(message)
@intent_handler(IntentBuilder("").one_of("Weather", "Forecast")
.one_of("Now", "Today").optionally("Location").build())
def handle_current_weather_simple(self, message):
self.handle_current_weather(message)
@intent_handler("what.is.three.day.forecast.intent")
def handle_three_day_forecast(self, message):
""" Handler for three day forecast without specified location
Examples: "What is the 3 day forecast?"
"What is the weather forecast?"
"""
report = self.__initialize_report(message)
try:
self.report_multiday_forecast(report)
except APIErrors as e:
self.__api_error(e)
except Exception as e:
self.log.exception("Error: {0}".format(e))
@intent_handler("what.is.three.day.forecast.location.intent")
def handle_three_day_forecast_location(self, message):
""" Handler for three day forecast for a specific location
Example: "What is the 3 day forecast for London?"
"""
# padatious lowercases everything including these keys
message.data['Location'] = message.data.pop('location')
return self.handle_three_day_forecast(message)
@intent_handler("what.is.two.day.forecast.intent")
def handle_two_day_forecast(self, message):
""" Handler for two day forecast with no specified location
Examples: "What's the weather like next Monday and Tuesday?"
"What's the weather gonna be like in the coming days?"
"""
# TODO consider merging in weekend intent
report = self.__initialize_report(message)
if message.data.get('day_one'):
# report two or more specific days
days = []
day_num = 1
day = message.data['day_one']
while day:
day_dt, _ = self.__extract_datetime(day)
days.append(day_dt)
day_num += 1
next_day = 'day_{}'.format(pronounce_number(day_num))
day = message.data.get(next_day)
try:
if message.data.get('day_one'):
# report two or more specific days
self.report_multiday_forecast(report, set_days=days)
else:
# report next two days
self.report_multiday_forecast(report, num_days=2)
except APIErrors as e:
self.__api_error(e)
except Exception as e:
self.log.exception("Error: {0}".format(e))
@intent_handler("what.is.multi.day.forecast.intent")
def handle_multi_day_forecast(self, message):
""" Handler for multiple day forecast with no specified location
Examples: "What's the weather like in the next 4 days?"
"""
report = self.__initialize_report(message)
# report x number of days
when, _ = self.__extract_datetime("tomorrow")
num_days = int(extract_number(message.data['num']))
if self.voc_match(message.data['num'], 'Couple'):
self.report_multiday_forecast(report, num_days=2)
self.report_multiday_forecast(report, when,
num_days=num_days)
# Handle: What is the weather forecast tomorrow?
@intent_handler(IntentBuilder("").one_of("Weather", "Forecast")
.optionally("Query").require("RelativeDay")
.optionally("Location").build())
def handle_forecast(self, message):
report = self.__initialize_report(message)
# Get a date from spoken request
when, _ = self.__extract_datetime(message.data.get('utterance'),
lang=self.lang)
today, _ = self.__extract_datetime('today', lang='en-us')
if today == when:
self.handle_current_weather(message)
return
self.report_forecast(report, when)
# Establish the daily cadence
self.schedule_for_daily_use()
# Handle: What's the weather later?
@intent_handler(IntentBuilder("").require("Query").require(
"Weather").optionally("Location").require("Later").build())
def handle_next_hour(self, message):
report = self.__initialize_report(message)
# Get near-future forecast
forecastWeather = self.owm.three_hours_forecast(
report['full_location'],
report['lat'],
report['lon']).get_forecast().get_weathers()[0]
if forecastWeather is None:
self.__report_no_data('weather')
return
# NOTE: The 3-hour forecast uses different temperature labels,
# temp, temp_min and temp_max.
report['temp'] = self.__get_temperature(forecastWeather, 'temp')
report['temp_min'] = self.__get_temperature(forecastWeather,
'temp_min')
report['temp_max'] = self.__get_temperature(forecastWeather,
'temp_max')
report['condition'] = forecastWeather.get_detailed_status()
report['icon'] = forecastWeather.get_weather_icon_name()
self.__report_weather("hour", report)
# Handle: What's the weather tonight / tomorrow morning?
@intent_handler(IntentBuilder("").require("RelativeTime")
.one_of("Weather", "Forecast").optionally("Query")
.optionally("RelativeDay").optionally("Location").build())
def handle_weather_at_time(self, message):
self.log.debug("Handler: handle_weather_at_time")
when, _ = self.__extract_datetime(
message.data.get('utterance'), lang=self.lang)
now = datetime.utcnow()
time_diff = (when - now)
mins_diff = (time_diff.days * 1440) + (time_diff.seconds / 60)
if mins_diff < 120:
self.handle_current_weather(message)
else:
report = self.__populate_report(message)
if report is None:
self.__report_no_data('weather')
return
self.__report_weather("at.time", report)
@intent_handler(IntentBuilder("").require("Query").one_of(
"Weather", "Forecast").require("Weekend").require(
"Next").optionally("Location").build())
def handle_next_weekend_weather(self, message):
""" Handle next weekends weather """
report = self.__initialize_report(message)
when, _ = self.__extract_datetime('next saturday', lang='en-us')
self.report_forecast(report, when)
when, _ = self.__extract_datetime('next sunday', lang='en-us')
self.report_forecast(report, when)
@intent_handler(IntentBuilder("").require("Query")
.one_of("Weather", "Forecast").require("Weekend")
.optionally("Location").build())
def handle_weekend_weather(self, message):
""" Handle weather for weekend. """
report = self.__initialize_report(message)
# Get a date from spoken request
when, _ = self.__extract_datetime('this saturday', lang='en-us')
self.report_forecast(report, when)
when, _ = self.__extract_datetime('this sunday', lang='en-us')
self.report_forecast(report, when)
@intent_handler(IntentBuilder("").optionally("Query")
.one_of("Weather", "Forecast").require("Week")
.optionally("Location").build())
def handle_week_weather(self, message):
""" Handle weather for week.
Speaks overview of week, not daily forecasts """
report = self.__initialize_report(message)
when, _ = self.__extract_datetime(message.data['utterance'])
today, _ = self.__extract_datetime("today")
if not when:
when = today
days = [when + timedelta(days=i) for i in range(7)]
# Fetch forecasts/reports for week
forecasts = [dict(self.__populate_forecast(report, day,
preface_day=False))
if day != today
else dict(self.__populate_current(report, day))
for day in days]
if forecasts is None:
self.__report_no_data('weather')
return
# collate forecasts
collated = {'condition': [], 'condition_cat': [], 'icon': [],
'temp': [], 'temp_min': [], 'temp_max': []}
for fc in forecasts:
for attribute in collated.keys():
collated[attribute].append(fc.get(attribute))
# analyse for commonality/difference
primary_category = max(collated['condition_cat'],
key=collated['condition_cat'].count)
days_with_primary_cat, conditions_in_primary_cat = [], []
days_with_other_cat = {}
for i, item in enumerate(collated['condition_cat']):
if item == primary_category:
days_with_primary_cat.append(i)
conditions_in_primary_cat.append(collated['condition'][i])
else:
if not days_with_other_cat.get(item):
days_with_other_cat[item] = []
days_with_other_cat[item].append(i)
primary_condition = max(conditions_in_primary_cat,
key=conditions_in_primary_cat.count)
# CONSTRUCT DIALOG
speak_category = self.translate_namedvalues('condition.category')
# 0. Report period starting day
if days[0] == today:
dialog = self.translate('this.week')
else:
speak_day = self.__to_day(days[0])
dialog = self.translate('from.day', {'day': speak_day})
# 1. whichever is longest (has most days), report as primary
# if over half the days => "it will be mostly {cond}"
speak_primary = speak_category[primary_category]
seq_primary_days = self.__get_seqs_from_list(days_with_primary_cat)
if len(days_with_primary_cat) >= (len(days) / 2):
dialog = self.concat_dialog(dialog,
'weekly.conditions.mostly.one',
{'condition': speak_primary})
elif seq_primary_days:
# if condition occurs on sequential days, report date range
dialog = self.concat_dialog(dialog,
'weekly.conditions.seq.start',
{'condition': speak_primary})
for seq in seq_primary_days:
if seq is not seq_primary_days[0]:
dialog = self.concat_dialog(dialog, 'and')
day_from = self.__to_day(days[seq[0]])
day_to = self.__to_day(days[seq[-1]])
dialog = self.concat_dialog(dialog,
'weekly.conditions.seq.period',
{'from': day_from,
'to': day_to})
else:
# condition occurs on random days
dialog = self.concat_dialog(dialog,
'weekly.conditions.some.days',
{'condition': speak_primary})
self.speak_dialog(dialog)
# 2. Any other conditions present:
dialog = ""
dialog_list = []
for cat in days_with_other_cat:
spoken_cat = speak_category[cat]
cat_days = days_with_other_cat[cat]
seq_days = self.__get_seqs_from_list(cat_days)
for seq in seq_days:
if seq is seq_days[0]:
seq_dialog = spoken_cat
else:
seq_dialog = self.translate('and')
day_from = self.__to_day(days[seq[0]])
day_to = self.__to_day(days[seq[-1]])
seq_dialog = self.concat_dialog(
seq_dialog,
self.translate('weekly.conditions.seq.period',
{'from': day_from,
'to': day_to}))
dialog_list.append(seq_dialog)
if not seq_days:
for day in cat_days:
speak_day = self.__to_day(days[day])
dialog_list.append(self.translate(
'weekly.condition.on.day',
{'condition': collated['condition'][day],
'day': speak_day}))
dialog = join_list(dialog_list, 'and')
self.speak_dialog(dialog)
# 3. Report temps:
temp_ranges = {
'low_min': min(collated['temp_min']),
'low_max': max(collated['temp_min']),
'high_min': min(collated['temp_max']),
'high_max': max(collated['temp_max'])
}
self.speak_dialog('weekly.temp.range', temp_ranges)
# CONDITION BASED QUERY HANDLERS ####
@intent_handler(IntentBuilder("").require("Temperature")
.require("Query").optionally("Location")
.optionally("Unit").optionally("Today")
.optionally("Now").build())
def handle_current_temperature(self, message):
return self.__handle_typed(message, 'temperature')
@intent_handler('simple.temperature.intent')
def handle_simple_temperature(self, message):
return self.__handle_typed(message, 'temperature')
@intent_handler(IntentBuilder("").require("Query").require("High")
.optionally("Temperature").optionally("Location")
.optionally("Unit").optionally("RelativeDay")
.optionally("Now").build())
def handle_high_temperature(self, message):
return self.__handle_typed(message, 'high.temperature')
@intent_handler(IntentBuilder("").require("Query").require("Low")
.optionally("Temperature").optionally("Location")
.optionally("Unit").optionally("RelativeDay")
.optionally("Now").build())
def handle_low_temperature(self, message):
return self.__handle_typed(message, 'low.temperature')
@intent_handler(IntentBuilder("").require("ConfirmQuery").require(
"Windy").optionally("Location").build())
def handle_isit_windy(self, message):
""" Handler for utterances similar to "is it windy today?" """
report = self.__populate_report(message)
if report is None:
self.__report_no_data('weather')
return
if self.__get_speed_unit() == 'mph':
limits = WINDSTRENGTH_MPH
report['wind_unit'] = self.translate('miles per hour')
else:
limits = WINDSTRENGTH_MPS
report['wind_unit'] = self.translate('meters per second')
dialog = []
if 'day' in report:
dialog.append('forecast')
if "Location" not in message.data:
dialog.append('local')
if int(report['wind']) >= limits['hard']:
dialog.append('hard')
elif int(report['wind']) >= limits['medium']:
dialog.append('medium')
else:
dialog.append('light')
dialog.append('wind')
dialog = '.'.join(dialog)
self.speak_dialog(dialog, report)
@intent_handler(IntentBuilder("").require("ConfirmQueryCurrent").one_of(
"Hot", "Cold").optionally("Location").optionally("Today").build())
def handle_isit_hot(self, message):
""" Handler for utterances similar to
is it hot today?, is it cold? etc
"""
return self.__handle_typed(message, 'hot')
# TODO This seems to present current temp, or possibly just hottest temp
@intent_handler(IntentBuilder("").optionally("How").one_of("Hot", "Cold")
.one_of("ConfirmQueryFuture", "ConfirmQueryCurrent")
.optionally("Location").optionally("RelativeDay").build())
def handle_how_hot_or_cold(self, message):
""" Handler for utterances similar to
how hot will it be today?, how cold will it be? , etc
"""
response_type = 'high.temperature' if message.data.get('Hot') \
else 'low.temperature'
return self.__handle_typed(message, response_type)
@intent_handler(IntentBuilder("").require("How").one_of("Hot", "Cold")
.one_of("ConfirmQueryFuture", "ConfirmQueryCurrent")
.optionally("Location").optionally("RelativeDay").build())
def handle_how_hot_or_cold_alt(self, message):
self.handle_how_hot_or_cold(message)
@intent_handler(IntentBuilder("").require("ConfirmQuery")
.require("Snowing").optionally("Location").build())
def handle_isit_snowing(self, message):
""" Handler for utterances similar to "is it snowing today?"
"""
report = self.__populate_report(message)
if report is None:
self.__report_no_data('weather')
return
dialog = self.__select_condition_dialog(message, report,
"snow", "snowing")
self.speak_dialog(dialog, report)
@intent_handler(IntentBuilder("").require("ConfirmQuery").require(
"Clear").optionally("Location").build())
def handle_isit_clear(self, message):
""" Handler for utterances similar to "is it clear skies today?"
"""
report = self.__populate_report(message)
if report is None:
self.__report_no_data('weather')
return
dialog = self.__select_condition_dialog(message, report, "clear")
self.speak_dialog(dialog, report)
@intent_handler(IntentBuilder("").require("ConfirmQuery").require(
"Cloudy").optionally("Location").optionally("RelativeTime").build())
def handle_isit_cloudy(self, message):
""" Handler for utterances similar to "is it cloudy skies today?"
"""
report = self.__populate_report(message)
if report is None:
self.__report_no_data('weather')
return
dialog = self.__select_condition_dialog(message, report, "cloudy")
self.speak_dialog(dialog, report)
@intent_handler(IntentBuilder("").require("ConfirmQuery").require(
"Foggy").optionally("Location").build())
def handle_isit_foggy(self, message):
""" Handler for utterances similar to "is it foggy today?"
"""
report = self.__populate_report(message)
if report is None:
self.__report_no_data('weather')
return
dialog = self.__select_condition_dialog(message, report, "fog",
"foggy")
self.speak_dialog(dialog, report)
@intent_handler(IntentBuilder("").require("ConfirmQuery").require(
"Raining").optionally("Location").build())
def handle_isit_raining(self, message):
""" Handler for utterances similar to "is it raining today?"
"""
report = self.__populate_report(message)
if report is None:
self.__report_no_data('weather')
return
dialog = self.__select_condition_dialog(message, report, "rain",
"raining")
self.speak_dialog(dialog, report)
@intent_handler("do.i.need.an.umbrella.intent")
def handle_need_umbrella(self, message):
self.handle_isit_raining(message)
@intent_handler(IntentBuilder("").require("ConfirmQuery").require(
"Storm").optionally("Location").build())
def handle_isit_storming(self, message):
""" Handler for utterances similar to "is it storming today?"
"""
report = self.__populate_report(message)
if report is None:
self.__report_no_data('weather')
return
dialog = self.__select_condition_dialog(message, report, "storm")
self.speak_dialog(dialog, report)
# Handle: When will it rain again?
@intent_handler(IntentBuilder("").require("When").optionally(
"Next").require("Precipitation").optionally("Location").build())
def handle_next_precipitation(self, message):
report = self.__initialize_report(message)
# Get a date from spoken request
today, _ = self.__extract_datetime("today")
when, _ = self.__extract_datetime(message.data.get('utterance'),
lang=self.lang)
# search the forecast for precipitation
weathers = self.owm.daily_forecast(
report['full_location'],
report['lat'],
report['lon'], 10).get_forecast()
if weathers is None:
self.__report_no_data('weather')
return
weathers = weathers.get_weathers()
for weather in weathers:
forecastDate = datetime.fromtimestamp(weather.get_reference_time())
if when and when != today:
# User asked about a specific date, is this it?
if forecastDate.date() != when.date():
continue
rain = weather.get_rain()
if rain and rain["all"] > 0:
data = {
"modifier": "",
"precip": "rain",
"day": self.__to_day(forecastDate, preface=True)
}
if rain["all"] < 10:
data["modifier"] = self.__translate("light")
elif rain["all"] > 20:
data["modifier"] = self.__translate("heavy")
self.speak_dialog("precipitation expected", data)
return
snow = weather.get_snow()
if snow and snow["all"] > 0:
data = {
"modifier": "",
"precip": "snow",
"day": self.__to_day(forecastDate, preface=True)
}
if snow["all"] < 10:
data["modifier"] = self.__translate("light")
elif snow["all"] > 20:
data["modifier"] = self.__translate("heavy")
self.speak_dialog("precipitation expected", data)
return
self.speak_dialog("no precipitation expected", report)
# Handle: How humid is it?
@intent_handler(IntentBuilder("").require("Query").require("Humidity")