Somewhat fancy voice command recognition software
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

Blather.py 7.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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. #read the commands
  36. self.read_commands()
  37. #load the options file
  38. self.load_options()
  39. #merge the opts
  40. for k,v in opts.__dict__.items():
  41. if (not k in self.options) or opts.override:
  42. self.options[k] = v
  43. if self.options['interface'] != None:
  44. if self.options['interface'] == "q":
  45. from QtUI import UI
  46. elif self.options['interface'] == "g":
  47. from GtkUI import UI
  48. elif self.options['interface'] == "gt":
  49. from GtkTrayUI import UI
  50. else:
  51. print "no GUI defined"
  52. sys.exit()
  53. self.ui = UI(args, self.options['continuous'])
  54. self.ui.connect("command", self.process_command)
  55. #can we load the icon resource?
  56. icon = self.load_resource("icon.png")
  57. if icon:
  58. self.ui.set_icon_active_asset(icon)
  59. #can we load the icon_inactive resource?
  60. icon_inactive = self.load_resource("icon_inactive.png")
  61. if icon_inactive:
  62. self.ui.set_icon_inactive_asset(icon_inactive)
  63. if self.options['history']:
  64. self.history = []
  65. #create the recognizer
  66. try:
  67. self.recognizer = Recognizer(lang_file, dic_file, self.options['microphone'] )
  68. except Exception, e:
  69. #no recognizer? bummer
  70. sys.exit()
  71. self.recognizer.connect('finished',self.recognizer_finished)
  72. print "Using Options: ", self.options
  73. def read_commands(self):
  74. #read the.commands file
  75. file_lines = open(command_file)
  76. strings = open(strings_file, "w")
  77. for line in file_lines:
  78. print line
  79. #trim the white spaces
  80. line = line.strip()
  81. #if the line has length and the first char isn't a hash
  82. if len(line) and line[0]!="#":
  83. #this is a parsible line
  84. (key,value) = line.split(":",1)
  85. print key, value
  86. self.commands[key.strip().lower()] = value.strip()
  87. strings.write( key.strip()+"\n")
  88. #close the strings file
  89. strings.close()
  90. def load_options(self):
  91. #is there an opt file?
  92. try:
  93. opt_fh = open(opt_file)
  94. text = opt_fh.read()
  95. self.options = yaml.load(text)
  96. except:
  97. pass
  98. def log_history(self,text):
  99. if self.options['history']:
  100. self.history.append(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 blather history file
  105. hfile = open(history_file, "w")
  106. for line in self.history:
  107. hfile.write( line+"\n")
  108. #close the file
  109. hfile.close()
  110. # Print the cmd and then run the command
  111. def run_command(self, cmd):
  112. print cmd
  113. subprocess.call(cmd, shell=True)
  114. def recognizer_finished(self, recognizer, text):
  115. t = text.lower()
  116. #is there a matching command?
  117. if self.commands.has_key( t ):
  118. #run the valid_sentence_command if there is a valid sentence command
  119. if self.options['valid_sentence_command']:
  120. subprocess.call(self.options['valid_sentence_command'], shell=True)
  121. cmd = self.commands[t]
  122. #should we be passing words?
  123. if self.options['pass_words']:
  124. cmd+=" "+t
  125. self.run_command(cmd)
  126. else:
  127. self.run_command(cmd)
  128. self.log_history(text)
  129. else:
  130. #run the invalid_sentence_command if there is a valid sentence command
  131. if self.options['invalid_sentence_command']:
  132. subprocess.call(self.options['invalid_sentence_command'], shell=True)
  133. print "no matching command %s" %(t)
  134. #if there is a UI and we are not continuous listen
  135. if self.ui:
  136. if not self.continuous_listen:
  137. #stop listening
  138. self.recognizer.pause()
  139. #let the UI know that there is a finish
  140. self.ui.finished(t)
  141. def run(self):
  142. if self.ui:
  143. self.ui.run()
  144. else:
  145. blather.recognizer.listen()
  146. def quit(self):
  147. sys.exit()
  148. def process_command(self, UI, command):
  149. print command
  150. if command == "listen":
  151. self.recognizer.listen()
  152. elif command == "stop":
  153. self.recognizer.pause()
  154. elif command == "continuous_listen":
  155. self.continuous_listen = True
  156. self.recognizer.listen()
  157. elif command == "continuous_stop":
  158. self.continuous_listen = False
  159. self.recognizer.pause()
  160. elif command == "quit":
  161. self.quit()
  162. def load_resource(self,string):
  163. local_data = os.path.join(os.path.dirname(__file__), 'data')
  164. paths = ["/usr/share/blather/","/usr/local/share/blather", local_data]
  165. for path in paths:
  166. resource = os.path.join(path, string)
  167. if os.path.exists( resource ):
  168. return resource
  169. #if we get this far, no resource was found
  170. return False
  171. if __name__ == "__main__":
  172. parser = OptionParser()
  173. parser.add_option("-i", "--interface", type="string", dest="interface",
  174. action='store',
  175. help="Interface to use (if any). 'q' for Qt, 'g' for GTK, 'gt' for GTK system tray icon")
  176. parser.add_option("-c", "--continuous",
  177. action="store_true", dest="continuous", default=False,
  178. help="starts interface with 'continuous' listen enabled")
  179. parser.add_option("-p", "--pass-words",
  180. action="store_true", dest="pass_words", default=False,
  181. help="passes the recognized words as arguments to the shell command")
  182. parser.add_option("-o", "--override",
  183. action="store_true", dest="override", default=False,
  184. help="override config file with command line options")
  185. parser.add_option("-H", "--history", type="int",
  186. action="store", dest="history",
  187. help="number of commands to store in history file")
  188. parser.add_option("-m", "--microphone", type="int",
  189. action="store", dest="microphone", default=None,
  190. help="Audio input card to use (if other than system default)")
  191. parser.add_option("--valid-sentence-command", type="string", dest="valid_sentence_command",
  192. action='store',
  193. help="command to run when a valid sentence is detected")
  194. parser.add_option( "--invalid-sentence-command", type="string", dest="invalid_sentence_command",
  195. action='store',
  196. help="command to run when an invalid sentence is detected")
  197. (options, args) = parser.parse_args()
  198. #make our blather object
  199. blather = Blather(options)
  200. #init gobject threads
  201. gobject.threads_init()
  202. #we want a main loop
  203. main_loop = gobject.MainLoop()
  204. #handle sigint
  205. signal.signal(signal.SIGINT, signal.SIG_DFL)
  206. #run the blather
  207. blather.run()
  208. #start the main loop
  209. try:
  210. main_loop.run()
  211. except:
  212. print "time to quit"
  213. main_loop.quit()
  214. sys.exit()