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.

recognizer.py 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # This is part of Kaylee
  2. # -- this code is licensed GPLv3
  3. # Copyright 2013 Jezra
  4. # Copyright 2015 Clayton G. Hobbs
  5. import os.path
  6. import sys
  7. import gi
  8. gi.require_version('Gst', '1.0')
  9. from gi.repository import GObject, Gst
  10. GObject.threads_init()
  11. Gst.init(None)
  12. class Recognizer(GObject.GObject):
  13. __gsignals__ = {
  14. 'finished' : (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, (GObject.TYPE_STRING,))
  15. }
  16. def __init__(self, language_file, dictionary_file, src=None):
  17. GObject.GObject.__init__(self)
  18. self.commands = {}
  19. if src:
  20. audio_src = 'alsasrc device="hw:%d,0"' % (src)
  21. else:
  22. audio_src = 'autoaudiosrc'
  23. # Build the pipeline
  24. cmd = audio_src + ' ! audioconvert ! audioresample ! pocketsphinx name=asr ! appsink sync=false'
  25. try:
  26. self.pipeline = Gst.parse_launch(cmd)
  27. except Exception as e:
  28. print(e.message)
  29. print("You may need to install gstreamer1.0-pocketsphinx")
  30. raise e
  31. bus = self.pipeline.get_bus()
  32. bus.add_signal_watch()
  33. # Get the Auto Speech Recognition piece
  34. asr = self.pipeline.get_by_name('asr')
  35. bus.connect('message::element', self.result)
  36. asr.set_property('lm', language_file)
  37. asr.set_property('dict', dictionary_file)
  38. asr.set_property('configured', True)
  39. def listen(self):
  40. self.pipeline.set_state(Gst.State.PLAYING)
  41. def pause(self):
  42. self.pipeline.set_state(Gst.State.PAUSED)
  43. def result(self, bus, msg):
  44. msg_struct = msg.get_structure()
  45. # Ignore messages that aren't from pocketsphinx
  46. msgtype = msg_struct.get_name()
  47. if msgtype != 'pocketsphinx':
  48. return
  49. # If we have a final command, send it for processing
  50. command = msg_struct.get_string('hypothesis')
  51. if command != '' and msg_struct.get_boolean('final')[1]:
  52. self.emit("finished", command)