Somewhat fancy voice command recognition software
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

kaylee.py 7.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. # This is part of Kaylee
  2. # -- this code is licensed GPLv3
  3. # Copyright 2015-2016 Clayton G. Hobbs
  4. # Portions Copyright 2013 Jezra
  5. import importlib
  6. import sys
  7. import subprocess
  8. import signal
  9. import os.path
  10. from gi.repository import GObject, GLib
  11. from kayleevc.recognizer import Recognizer
  12. from kayleevc.util import *
  13. from kayleevc.numbers import NumberParser
  14. import kayleevc.plugins
  15. class Kaylee:
  16. def __init__(self):
  17. self.ui = None
  18. self.options = {}
  19. self.continuous_listen = False
  20. # Load configuration
  21. self.config = Config()
  22. self.options = vars(self.config.options)
  23. # Make sure some plugins are configured to be loaded
  24. if self.config.plugins is None:
  25. print("error: no plugins configured", file=sys.stderr)
  26. sys.exit(1)
  27. # Load plugins
  28. self.plugins = []
  29. for plugin in self.config.plugins.keys():
  30. pmod = importlib.import_module(plugin, 'kayleevc.plugins')
  31. self.plugins.append(pmod.Plugin(self.config, plugin))
  32. # Create a hasher
  33. self.hasher = Hasher(self.config)
  34. # Create the strings file
  35. self.update_voice_commands_if_changed()
  36. if self.options['interface']:
  37. if self.options['interface'] == "g":
  38. from kayleevc.gui import GTKInterface as UI
  39. elif self.options['interface'] == "gt":
  40. from kayleevc.gui import GTKTrayInterface as UI
  41. else:
  42. print("no GUI defined")
  43. sys.exit()
  44. self.ui = UI(self.options, self.options['continuous'])
  45. self.ui.connect("command", self.process_command)
  46. # Can we load the icon resource?
  47. icon = self.load_resource("icon_small.png")
  48. if icon:
  49. self.ui.set_icon_active_asset(icon)
  50. # Can we load the icon_inactive resource?
  51. icon_inactive = self.load_resource("icon_inactive_small.png")
  52. if icon_inactive:
  53. self.ui.set_icon_inactive_asset(icon_inactive)
  54. if self.options['history']:
  55. self.history = []
  56. # Update the language if necessary
  57. self.language_updater = LanguageUpdater(self.config)
  58. self.language_updater.update_language_if_changed()
  59. # Create the recognizer
  60. self.recognizer = Recognizer(self.config)
  61. # Connect the recognizer's finished signal to all the plugins
  62. for plugin in self.plugins:
  63. self.recognizer.connect('finished', plugin.recognizer_finished)
  64. plugin.connect('processed', self.plugin_processed)
  65. self.recognizer.connect('finished', self.recognizer_finished)
  66. def update_voice_commands_if_changed(self):
  67. """Use hashes to test if the voice commands have changed"""
  68. stored_hash = self.hasher['voice_commands']
  69. # Calculate the hash the voice commands have right now
  70. hasher = self.hasher.get_hash_object()
  71. for plugin in self.plugins:
  72. for string in sorted(plugin.corpus_strings):
  73. hasher.update(string.encode('utf-8'))
  74. # Add a separator to avoid odd behavior
  75. hasher.update('\n'.encode('utf-8'))
  76. new_hash = hasher.hexdigest()
  77. if new_hash != stored_hash:
  78. self.create_strings_file()
  79. self.hasher['voice_commands'] = new_hash
  80. self.hasher.store()
  81. def create_strings_file(self):
  82. # Open the strings file
  83. with open(self.config.strings_file, 'w') as strings:
  84. # Add command words to the corpus
  85. # FIXME: Doing this twice is a silly thing
  86. for plugin in self.plugins:
  87. for string in sorted(plugin.corpus_strings):
  88. strings.write(string + "\n")
  89. # Add number words to the corpus
  90. if NumberParser.number_words is not None:
  91. for word in NumberParser.number_words:
  92. strings.write(word + " ")
  93. strings.write("\n")
  94. def plugin_processed(self, plugin, text):
  95. """Callback for ``processed`` signal from plugins
  96. Runs the valid_sentence_command and logs the recognized sentence to the
  97. history file.
  98. """
  99. # Run the valid_sentence_command if it's set
  100. if self.options['valid_sentence_command']:
  101. subprocess.call(self.options['valid_sentence_command'], shell=True)
  102. # Log the command to the history file
  103. if self.options['history']:
  104. self.history.append("{}: {}".format(plugin.name, text))
  105. if len(self.history) > self.options['history']:
  106. # Pop off the first item
  107. self.history.pop(0)
  108. # Open and truncate the history file
  109. with open(self.config.history_file, 'w') as hfile:
  110. for line in self.history:
  111. hfile.write(line + '\n')
  112. self._stop_ui(text)
  113. def recognizer_finished(self, recognizer, text):
  114. # No loaded plugin wanted the text, so run the invalid_sentence_command
  115. # if it's set
  116. if self.options['invalid_sentence_command']:
  117. subprocess.call(self.options['invalid_sentence_command'],
  118. shell=True)
  119. print("no matching command {0}".format(text))
  120. self._stop_ui(text)
  121. def _stop_ui(self, text):
  122. # If there is a UI and we are not continuous listen
  123. if self.ui:
  124. if not self.continuous_listen:
  125. # Stop listening
  126. self.recognizer.pause()
  127. # Let the UI know that there is a finish
  128. self.ui.finished(text)
  129. def run(self):
  130. if self.ui:
  131. self.ui.run()
  132. else:
  133. self.recognizer.listen()
  134. def quit(self):
  135. sys.exit()
  136. def process_command(self, UI, command):
  137. print(command)
  138. if command == "listen":
  139. self.recognizer.listen()
  140. elif command == "stop":
  141. self.recognizer.pause()
  142. elif command == "continuous_listen":
  143. self.continuous_listen = True
  144. self.recognizer.listen()
  145. elif command == "continuous_stop":
  146. self.continuous_listen = False
  147. self.recognizer.pause()
  148. elif command == "quit":
  149. self.quit()
  150. def load_resource(self, string):
  151. # TODO: Use the Config object for this path management
  152. local_data = os.path.join(os.path.dirname(__file__), '..', 'data')
  153. paths = ["/usr/share/kaylee/", "/usr/local/share/kaylee", local_data]
  154. for path in paths:
  155. resource = os.path.join(path, string)
  156. if os.path.exists(resource):
  157. return resource
  158. # If we get this far, no resource was found
  159. return False
  160. def run():
  161. # Make our kaylee object
  162. kaylee = Kaylee()
  163. # Init gobject threads
  164. GObject.threads_init()
  165. # We want a main loop
  166. main_loop = GObject.MainLoop()
  167. # Handle sigint
  168. signal.signal(signal.SIGINT, signal.SIG_DFL)
  169. # Run the kaylee
  170. kaylee.run()
  171. # Start the main loop
  172. try:
  173. main_loop.run()
  174. except:
  175. main_loop.quit()
  176. sys.exit()