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 6.9KB

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