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.

Blather.py 5.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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:
  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. cmd = self.commands[t]
  109. print cmd
  110. subprocess.call(cmd, shell=True)
  111. self.log_history(text)
  112. else:
  113. print "no matching command"
  114. #if there is a UI and we are not continuous listen
  115. if self.ui:
  116. if not self.continuous_listen:
  117. #stop listening
  118. self.recognizer.pause()
  119. #let the UI know that there is a finish
  120. self.ui.finished(t)
  121. def run(self):
  122. if self.ui:
  123. self.ui.run()
  124. else:
  125. blather.recognizer.listen()
  126. def quit(self):
  127. sys.exit()
  128. def process_command(self, UI, command):
  129. print command
  130. if command == "listen":
  131. self.recognizer.listen()
  132. elif command == "stop":
  133. self.recognizer.pause()
  134. elif command == "continuous_listen":
  135. self.continuous_listen = True
  136. self.recognizer.listen()
  137. elif command == "continuous_stop":
  138. self.continuous_listen = False
  139. self.recognizer.pause()
  140. elif command == "quit":
  141. self.quit()
  142. def load_resource(self,string):
  143. local_data = os.path.join(os.path.dirname(__file__), 'data')
  144. paths = ["/usr/share/blather/","/usr/local/share/blather", local_data]
  145. for path in paths:
  146. resource = os.path.join(path, string)
  147. if os.path.exists( resource ):
  148. return resource
  149. #if we get this far, no resource was found
  150. return False
  151. if __name__ == "__main__":
  152. parser = OptionParser()
  153. parser.add_option("-i", "--interface", type="string", dest="interface",
  154. action='store',
  155. help="Interface to use (if any). 'q' for Qt, 'g' for GTK, 'gt' for GTK system tray icon")
  156. parser.add_option("-c", "--continuous",
  157. action="store_true", dest="continuous", default=False,
  158. help="starts interface with 'continuous' listen enabled")
  159. parser.add_option("-H", "--history", type="int",
  160. action="store", dest="history",
  161. help="number of commands to store in history file")
  162. parser.add_option("-m", "--microphone", type="int",
  163. action="store", dest="microphone", default=None,
  164. help="Audio input card to use (if other than system default)")
  165. (options, args) = parser.parse_args()
  166. #make our blather object
  167. blather = Blather(options)
  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 blather
  175. blather.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()