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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. #!/usr/bin/env python2
  2. # -- this code is licensed GPLv3
  3. # Copyright 2013 Jezra
  4. import sys
  5. import signal
  6. import gobject
  7. import os.path
  8. import subprocess
  9. from optparse import OptionParser
  10. try:
  11. import yaml
  12. except:
  13. print "YAML is not supported. ~/.config/blather/options.yaml will not function"
  14. #where are the files?
  15. conf_dir = os.path.expanduser("~/.config/blather")
  16. lang_dir = os.path.join(conf_dir, "language")
  17. command_file = os.path.join(conf_dir, "commands.conf")
  18. strings_file = os.path.join(conf_dir, "sentences.corpus")
  19. history_file = os.path.join(conf_dir, "blather.history")
  20. opt_file = os.path.join(conf_dir, "options.yaml")
  21. lang_file = os.path.join(lang_dir,'lm')
  22. dic_file = os.path.join(lang_dir,'dic')
  23. #make the lang_dir if it doesn't exist
  24. if not os.path.exists(lang_dir):
  25. os.makedirs(lang_dir)
  26. class Blather:
  27. def __init__(self, opts):
  28. #import the recognizer so Gst doesn't clobber our -h
  29. from Recognizer import Recognizer
  30. self.ui = None
  31. self.options = {}
  32. ui_continuous_listen = False
  33. self.continuous_listen = False
  34. self.commands = {}
  35. self.read_commands()
  36. self.recognizer = Recognizer(lang_file, dic_file, opts.microphone )
  37. self.recognizer.connect('finished',self.recognizer_finished)
  38. #load the options file
  39. self.load_options()
  40. #merge the opts
  41. for k,v in opts.__dict__.items():
  42. if (not k in self.options) or opts.override:
  43. self.options[k] = v
  44. print "Using Options: ", self.options
  45. if self.options['interface'] != None:
  46. if self.options['interface'] == "q":
  47. from QtUI import UI
  48. elif self.options['interface'] == "g":
  49. from GtkUI import UI
  50. elif self.options['interface'] == "gt":
  51. from GtkTrayUI import UI
  52. else:
  53. print "no GUI defined"
  54. sys.exit()
  55. self.ui = UI(args, self.options['continuous'])
  56. self.ui.connect("command", self.process_command)
  57. #can we load the icon resource?
  58. icon = self.load_resource("icon.png")
  59. if icon:
  60. self.ui.set_icon_active_asset(icon)
  61. #can we load the icon_inactive resource?
  62. icon_inactive = self.load_resource("icon_inactive.png")
  63. if icon_inactive:
  64. self.ui.set_icon_inactive_asset(icon_inactive)
  65. if self.options['history']:
  66. self.history = []
  67. def read_commands(self):
  68. #read the.commands file
  69. file_lines = open(command_file)
  70. strings = open(strings_file, "w")
  71. for line in file_lines:
  72. print line
  73. #trim the white spaces
  74. line = line.strip()
  75. #if the line has length and the first char isn't a hash
  76. if len(line) and line[0]!="#":
  77. #this is a parsible line
  78. (key,value) = line.split(":",1)
  79. print key, value
  80. self.commands[key.strip().lower()] = value.strip()
  81. strings.write( key.strip()+"\n")
  82. #close the strings file
  83. strings.close()
  84. def load_options(self):
  85. #is there an opt file?
  86. try:
  87. opt_fh = open(opt_file)
  88. text = opt_fh.read()
  89. self.options = yaml.load(text)
  90. except:
  91. pass
  92. def log_history(self,text):
  93. if self.options['history']:
  94. self.history.append(text)
  95. if len(self.history) > self.options['history']:
  96. #pop off the first item
  97. self.history.pop(0)
  98. #open and truncate the blather history file
  99. hfile = open(history_file, "w")
  100. for line in self.history:
  101. hfile.write( line+"\n")
  102. #close the file
  103. hfile.close()
  104. def recognizer_finished(self, recognizer, text):
  105. t = text.lower()
  106. #is there a matching command?
  107. if self.commands.has_key( t ):
  108. #run the valid_sentence_command if there is a valid sentence command
  109. if self.options['valid_sentence_command']:
  110. subprocess.call(self.options['valid_sentence_command'], shell=True)
  111. cmd = self.commands[t]
  112. print cmd
  113. subprocess.call(cmd, shell=True)
  114. self.log_history(text)
  115. else:
  116. #run the invalid_sentence_command if there is a valid sentence command
  117. if self.options['invalid_sentence_command']:
  118. subprocess.call(self.options['invalid_sentence_command'], shell=True)
  119. print "no matching command %s" %(t)
  120. #if there is a UI and we are not continuous listen
  121. if self.ui:
  122. if not self.continuous_listen:
  123. #stop listening
  124. self.recognizer.pause()
  125. #let the UI know that there is a finish
  126. self.ui.finished(t)
  127. def run(self):
  128. if self.ui:
  129. self.ui.run()
  130. else:
  131. blather.recognizer.listen()
  132. def quit(self):
  133. sys.exit()
  134. def process_command(self, UI, command):
  135. print command
  136. if command == "listen":
  137. self.recognizer.listen()
  138. elif command == "stop":
  139. self.recognizer.pause()
  140. elif command == "continuous_listen":
  141. self.continuous_listen = True
  142. self.recognizer.listen()
  143. elif command == "continuous_stop":
  144. self.continuous_listen = False
  145. self.recognizer.pause()
  146. elif command == "quit":
  147. self.quit()
  148. def load_resource(self,string):
  149. local_data = os.path.join(os.path.dirname(__file__), 'data')
  150. paths = ["/usr/share/blather/","/usr/local/share/blather", local_data]
  151. for path in paths:
  152. resource = os.path.join(path, string)
  153. if os.path.exists( resource ):
  154. return resource
  155. #if we get this far, no resource was found
  156. return False
  157. if __name__ == "__main__":
  158. parser = OptionParser()
  159. parser.add_option("-i", "--interface", type="string", dest="interface",
  160. action='store',
  161. help="Interface to use (if any). 'q' for Qt, 'g' for GTK, 'gt' for GTK system tray icon")
  162. parser.add_option("-c", "--continuous",
  163. action="store_true", dest="continuous", default=False,
  164. help="starts interface with 'continuous' listen enabled")
  165. parser.add_option("-o", "--override",
  166. action="store_true", dest="override", default=False,
  167. help="override config file with command line options")
  168. parser.add_option("-H", "--history", type="int",
  169. action="store", dest="history",
  170. help="number of commands to store in history file")
  171. parser.add_option("-m", "--microphone", type="int",
  172. action="store", dest="microphone", default=None,
  173. help="Audio input card to use (if other than system default)")
  174. parser.add_option("--valid-sentence-command", type="string", dest="valid_sentence_command",
  175. action='store',
  176. help="command to run when a valid sentence is detected")
  177. parser.add_option( "--invalid-sentence-command", type="string", dest="invalid_sentence_command",
  178. action='store',
  179. help="command to run when an invalid sentence is detected")
  180. (options, args) = parser.parse_args()
  181. #make our blather object
  182. blather = Blather(options)
  183. #init gobject threads
  184. gobject.threads_init()
  185. #we want a main loop
  186. main_loop = gobject.MainLoop()
  187. #handle sigint
  188. signal.signal(signal.SIGINT, signal.SIG_DFL)
  189. #run the blather
  190. blather.run()
  191. #start the main loop
  192. try:
  193. main_loop.run()
  194. except:
  195. print "time to quit"
  196. main_loop.quit()
  197. sys.exit()