Somewhat fancy voice command recognition software
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

darksky.py 7.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. # This is part of Kaylee
  2. # -- this code is licensed GPLv3
  3. # Copyright 2015-2017 Clayton G. Hobbs
  4. # Portions Copyright 2013 Jezra
  5. """Dark Sky weather plugin for Kaylee
  6. This plugin provides weather information `powered by Dark Sky
  7. <https://darksky.net/poweredby/>`__. The user must provide a key for
  8. the Dark Sky API, as well as decimal latitude and longitude::
  9. ".darksky": {
  10. "api_key": "USER_API_KEY",
  11. "latitude": USER_LATITUDE,
  12. "longitude": USER_LONGITUDE
  13. }
  14. Weather information is cached for up to ``cache_max_age`` seconds
  15. (default 1800, half an hour). To conserve API calls, the cache is not
  16. updated until the first time the user requests weather information
  17. after the cache becomes stale.
  18. Temperatures are read to the nearest ``temp_precision`` decimal places
  19. (default 0).
  20. """
  21. import json
  22. import os
  23. import time
  24. import requests
  25. from . import PluginBase, Handler
  26. class Plugin(PluginBase):
  27. """Main class for the Dark Sky weather plugin"""
  28. def __init__(self, config, name):
  29. """Initialize the Dark Sky weather plugin"""
  30. super().__init__(config, name)
  31. self._cache_filename = os.path.join(config.cache_dir, 'darksky.json')
  32. key = self.options['api_key']
  33. lat = self.options['latitude']
  34. lon = self.options['longitude']
  35. self._url = f'https://api.darksky.net/forecast/{key}/{lat},{lon}'
  36. try:
  37. self._cache_max_age = self.options['cache_max_age']
  38. except KeyError:
  39. self._cache_max_age = 1800
  40. try:
  41. self._temp_precision = self.options['temp_precision']
  42. except KeyError:
  43. self._temp_precision = 0
  44. self.commands = {
  45. 'whats the temperature': DarkSkyTemperatureHandler,
  46. 'whats todays high': DarkSkyTodaysHighHandler,
  47. 'whats todays low': DarkSkyTodaysLowHandler,
  48. 'whats tomorrows high': DarkSkyTomorrowsHighHandler,
  49. 'whats the humidity': DarkSkyHumidityHandler,
  50. 'whats the weather': DarkSkyCurrentConditionsHandler,
  51. 'whens sunset': DarkSkySunsetHandler,
  52. 'hoos your weather provider': DarkSkyProviderHandler
  53. }
  54. self.corpus_strings.update(self.commands)
  55. def get_handler(self, text):
  56. """Return a handler if a recognized command is heard"""
  57. if text in self.corpus_strings:
  58. return self.commands[text](1, self._cache_filename,
  59. self._url, self._cache_max_age,
  60. self._temp_precision)
  61. else:
  62. return None
  63. class DarkSkyHandler(Handler):
  64. """Base class for Dark Sky plugin handlers"""
  65. def __init__(self, confidence, cache_filename, url, cache_max_age,
  66. temp_precision):
  67. super().__init__(confidence)
  68. self._cache_filename = cache_filename
  69. self._url = url
  70. self._cache_max_age = cache_max_age
  71. self._temp_precision = temp_precision
  72. def _update_cache_if_stale(self):
  73. try:
  74. st = os.stat(self._cache_filename)
  75. except FileNotFoundError:
  76. # If there's no cache file, we need to get one
  77. self._update_cache()
  78. else:
  79. if time.time() - st.st_mtime > self._cache_max_age:
  80. self._update_cache()
  81. def _update_cache(self):
  82. r = requests.get(self._url, stream=True)
  83. if r.status_code == 200:
  84. with open(self._cache_filename, 'wb') as f:
  85. for chunk in r:
  86. f.write(chunk)
  87. def _read_cache(self):
  88. with open(self._cache_filename, 'r') as f:
  89. return json.load(f)
  90. def _format_temperature(self, temperature, unit='Fahrenheit'):
  91. """Format a temperature for the TTS system"""
  92. return f'{temperature:.{self._temp_precision}f} degrees {unit}'
  93. def _format_percent(self, value):
  94. """Format a percentage value for the TTS system"""
  95. return f'{100*value:.0f} percent'
  96. def _format_time(self, epoch_time):
  97. """Format a time in seconds since the epoch for the TTS system"""
  98. t = time.localtime(epoch_time)
  99. # Format each part of the time to be pronounced nicely
  100. hour = time.strftime('%I', t)
  101. if hour[0] == '0':
  102. hour = hour[1]
  103. minute = time.strftime('%M', t)
  104. if minute[0] == '0':
  105. if minute[1] == '0':
  106. minute = "o'clock"
  107. else:
  108. minute = 'O' + minute[1]
  109. ante_post = time.strftime('%p', t)
  110. if ante_post[0] == 'A':
  111. ante_post = 'AE ' + ante_post[1]
  112. # Put the parts together
  113. return f'{hour} {minute} {ante_post}'
  114. def __call__(self, tts):
  115. """Update the cache if necessary and load it"""
  116. self._update_cache_if_stale()
  117. self.cache = self._read_cache()
  118. class DarkSkyTemperatureHandler(DarkSkyHandler):
  119. """Handler to speak the current temperature"""
  120. def __call__(self, tts):
  121. """Speak the current temperature"""
  122. super().__call__(tts)
  123. tts(self._format_temperature(self.cache['currently']['temperature']))
  124. class DarkSkyTodaysHighHandler(DarkSkyHandler):
  125. """Handler to speak today's high temperature"""
  126. def __call__(self, tts):
  127. """Speak today's high"""
  128. super().__call__(tts)
  129. tts(self._format_temperature(
  130. self.cache['daily']['data'][0]['temperatureMax']))
  131. class DarkSkyTodaysLowHandler(DarkSkyHandler):
  132. """Handler to speak today's low temperature"""
  133. def __call__(self, tts):
  134. """Speak today's low"""
  135. super().__call__(tts)
  136. tts(self._format_temperature(
  137. self.cache['daily']['data'][0]['temperatureMin']))
  138. class DarkSkyTomorrowsHighHandler(DarkSkyHandler):
  139. """Handler to speak tomorrow's high temperature"""
  140. def __call__(self, tts):
  141. """Speak tomorrow's high"""
  142. super().__call__(tts)
  143. tts(self._format_temperature(
  144. self.cache['daily']['data'][1]['temperatureMax']))
  145. class DarkSkyHumidityHandler(DarkSkyHandler):
  146. """Handler to speak the current relative humidity"""
  147. def __call__(self, tts):
  148. """Speak the current relative humidity"""
  149. super().__call__(tts)
  150. tts(self._format_percent(self.cache['currently']['humidity']))
  151. class DarkSkyCurrentConditionsHandler(DarkSkyHandler):
  152. """Handler to speak the current weather conditions"""
  153. def __call__(self, tts):
  154. """Speak the current weather conditions"""
  155. super().__call__(tts)
  156. summary = self.cache['currently']['summary']
  157. temperature = self._format_temperature(
  158. self.cache['currently']['temperature'])
  159. humidity = self._format_percent(self.cache['currently']['humidity'])
  160. tts(f'{summary}, {temperature}, relative humidity {humidity}')
  161. class DarkSkySunsetHandler(DarkSkyHandler):
  162. """Handler to speak the time of sunset"""
  163. def __call__(self, tts):
  164. """Speak the time of sunset"""
  165. super().__call__(tts)
  166. tts(self._format_time(self.cache['daily']['data'][0]['sunsetTime']))
  167. class DarkSkyProviderHandler(DarkSkyHandler):
  168. """Handler to speak information about the weather provider"""
  169. def __call__(self, tts):
  170. """Speak information about the weather provider"""
  171. # No need for super since this doesn't need any weather information
  172. tts('Powered by Dark Sky, https:// dark sky .net/ powered by/.')