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.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. #!/usr/bin/env python3
  2. # This is part of Kaylee
  3. # -- this code is licensed GPLv3
  4. # Copyright 2015-2016 Clayton G. Hobbs
  5. # Portions Copyright 2013 Jezra
  6. import sys
  7. import signal
  8. import os.path
  9. import subprocess
  10. from gi.repository import GObject, GLib
  11. from recognizer import Recognizer
  12. from config import Config
  13. from languageupdater import LanguageUpdater
  14. from numberparser import NumberParser
  15. from hasher import Hasher
  16. class Kaylee:
  17. def __init__(self):
  18. self.ui = None
  19. self.options = {}
  20. ui_continuous_listen = False
  21. self.continuous_listen = False
  22. # Load configuration
  23. self.config = Config()
  24. self.options = vars(self.config.options)
  25. self.commands = self.options['commands']
  26. # Create number parser for later use
  27. self.number_parser = NumberParser()
  28. # Create a hasher
  29. self.hasher = Hasher(self.config)
  30. # Create the strings file
  31. self.update_strings_file_if_changed()
  32. if self.options['interface']:
  33. if self.options['interface'] == "g":
  34. from gtkui import UI
  35. elif self.options['interface'] == "gt":
  36. from gtktrayui import 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.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.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. self.recognizer.connect('finished', self.recognizer_finished)
  58. def update_voice_commands_if_changed(self):
  59. """Use hashes to test if the voice commands have changed"""
  60. stored_hash = self.hasher['voice_commands']
  61. # Calculate the hash the voice commands have right now
  62. hasher = self.hasher.get_hash_object()
  63. for voice_cmd in self.commands.keys():
  64. hasher.update(voice_cmd.encode('utf-8'))
  65. # Add a separator to avoid odd behavior
  66. hasher.update('\n'.encode('utf-8'))
  67. new_hash = hasher.hexdigest()
  68. if new_hash != stored_hash:
  69. self.create_strings_file()
  70. self.hasher['voice_commands'] = new_hash
  71. self.hasher.store()
  72. def create_strings_file(self):
  73. # Open the strings file
  74. with open(self.config.strings_file, 'w') as strings:
  75. # Add command words to the corpus
  76. for voice_cmd in sorted(self.commands.keys()):
  77. strings.write(voice_cmd.strip().replace('%d', '') + "\n")
  78. # Add number words to the corpus
  79. for word in self.number_parser.number_words:
  80. strings.write(word + "\n")
  81. def log_history(self, text):
  82. if self.options['history']:
  83. self.history.append(text)
  84. if len(self.history) > self.options['history']:
  85. # Pop off the first item
  86. self.history.pop(0)
  87. # Open and truncate the history file
  88. with open(self.config.history_file, 'w') as hfile:
  89. for line in self.history:
  90. hfile.write(line + '\n')
  91. def run_command(self, cmd):
  92. """Print the command, then run it"""
  93. print(cmd)
  94. subprocess.call(cmd, shell=True)
  95. def recognizer_finished(self, recognizer, text):
  96. t = text.lower()
  97. numt, nums = self.number_parser.parse_all_numbers(t)
  98. # Is there a matching command?
  99. if t in self.commands:
  100. # Run the valid_sentence_command if it's set
  101. if self.options['valid_sentence_command']:
  102. subprocess.call(self.options['valid_sentence_command'],
  103. shell=True)
  104. cmd = self.commands[t]
  105. # Should we be passing words?
  106. if self.options['pass_words']:
  107. cmd += " " + t
  108. self.run_command(cmd)
  109. self.log_history(text)
  110. elif numt in self.commands:
  111. # Run the valid_sentence_command if it's set
  112. if self.options['valid_sentence_command']:
  113. subprocess.call(self.options['valid_sentence_command'],
  114. shell=True)
  115. cmd = self.commands[numt]
  116. cmd = cmd.format(*nums)
  117. # Should we be passing words?
  118. if self.options['pass_words']:
  119. cmd += " " + t
  120. self.run_command(cmd)
  121. self.log_history(text)
  122. else:
  123. # Run the invalid_sentence_command if it's set
  124. if self.options['invalid_sentence_command']:
  125. subprocess.call(self.options['invalid_sentence_command'],
  126. shell=True)
  127. print("no matching command {0}".format(t))
  128. # If there is a UI and we are not continuous listen
  129. if self.ui:
  130. if not self.continuous_listen:
  131. # Stop listening
  132. self.recognizer.pause()
  133. # Let the UI know that there is a finish
  134. self.ui.finished(t)
  135. def run(self):
  136. if self.ui:
  137. self.ui.run()
  138. else:
  139. self.recognizer.listen()
  140. def quit(self):
  141. sys.exit()
  142. def process_command(self, UI, command):
  143. print(command)
  144. if command == "listen":
  145. self.recognizer.listen()
  146. elif command == "stop":
  147. self.recognizer.pause()
  148. elif command == "continuous_listen":
  149. self.continuous_listen = True
  150. self.recognizer.listen()
  151. elif command == "continuous_stop":
  152. self.continuous_listen = False
  153. self.recognizer.pause()
  154. elif command == "quit":
  155. self.quit()
  156. def load_resource(self, string):
  157. local_data = os.path.join(os.path.dirname(__file__), 'data')
  158. paths = ["/usr/share/kaylee/", "/usr/local/share/kaylee", local_data]
  159. for path in paths:
  160. resource = os.path.join(path, string)
  161. if os.path.exists(resource):
  162. return resource
  163. # If we get this far, no resource was found
  164. return False
  165. if __name__ == "__main__":
  166. # Make our kaylee object
  167. kaylee = Kaylee()
  168. # Init gobject threads
  169. GObject.threads_init()
  170. # We want a main loop
  171. main_loop = GObject.MainLoop()
  172. # Handle sigint
  173. signal.signal(signal.SIGINT, signal.SIG_DFL)
  174. # Run the kaylee
  175. kaylee.run()
  176. # Start the main loop
  177. try:
  178. main_loop.run()
  179. except:
  180. print("time to quit")
  181. main_loop.quit()
  182. sys.exit()