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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 = (
  25. audio_src +
  26. ' ! audioconvert' +
  27. ' ! audioresample' +
  28. ' ! pocketsphinx lm=' + language_file + ' dict=' +
  29. dictionary_file + ' configured=true' +
  30. ' ! appsink sync=false'
  31. )
  32. try:
  33. self.pipeline = Gst.parse_launch(cmd)
  34. except Exception as e:
  35. print(e.message)
  36. print("You may need to install gstreamer1.0-pocketsphinx")
  37. raise e
  38. # Process results from the pipeline with self.result()
  39. bus = self.pipeline.get_bus()
  40. bus.add_signal_watch()
  41. bus.connect('message::element', self.result)
  42. def listen(self):
  43. self.pipeline.set_state(Gst.State.PLAYING)
  44. def pause(self):
  45. self.pipeline.set_state(Gst.State.PAUSED)
  46. def result(self, bus, msg):
  47. msg_struct = msg.get_structure()
  48. # Ignore messages that aren't from pocketsphinx
  49. msgtype = msg_struct.get_name()
  50. if msgtype != 'pocketsphinx':
  51. return
  52. # If we have a final command, send it for processing
  53. command = msg_struct.get_string('hypothesis')
  54. if command != '' and msg_struct.get_boolean('final')[1]:
  55. self.emit("finished", command)