hotword_dialogflow.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 # Snowboy
4 from snowboy import snowboydecoder
5 # Dialogflow
6 from dialogflow_ros import DialogflowClient
7 # ROS
8 import rospy
9 from rospkg.rospack import RosPack
10 # Python
11 import pyaudio
12 import signal
13 import time
14 import wave
15 
16 
17 class HotwordDialogflow(object):
18  def __init__(self):
19  self.interrupted = False
20  self.detector = None
21  rpack = RosPack()
22  # UMDL or PMDL file paths along with audio files
23  pkg_path = rpack.get_path('dialogflow_ros')
24  self.model_path = pkg_path + '/scripts/snowboy/resources/jarvis.umdl'
25  ding_path = pkg_path + '/scripts/snowboy/resources/ding.wav'
26  # Setup df
27  self.df_client = None
28  # Setup audio output
29  ding = wave.open(ding_path, 'rb')
30  self.ding_data = ding.readframes(ding.getnframes())
31  self.audio = pyaudio.PyAudio()
32  self.stream_out = self.audio.open(
33  format=self.audio.get_format_from_width(ding.getsampwidth()),
34  channels=ding.getnchannels(), rate=ding.getframerate(),
35  input=False, output=True)
36  self.last_contexts = []
37  rospy.loginfo("HOTWORD_CLIENT: Ready!")
38 
39  def _signal_handler(self, signal, frame):
40  rospy.logwarn("SIGINT Caught!")
41  self.exit()
42 
44  return self.interrupted
45 
46  def play_ding(self):
47  """Simple function to play a Ding sound."""
48  self.stream_out.start_stream()
49  self.stream_out.write(self.ding_data)
50  time.sleep(0.2)
51  self.stream_out.stop_stream()
52 
53  def _df_callback(self):
54  rospy.loginfo("HOTWORD_CLIENT: Hotword detected!")
55  self.play_ding()
56  # self.df_client = DialogflowClient(last_contexts=self.last_contexts)
57  df_msg, res = self.df_client.detect_intent_stream(return_result=True)
58  self.last_contexts = res.output_contexts
59 
60  def start(self):
61  # Register Ctrl-C sigint
62  signal.signal(signal.SIGINT, self._signal_handler)
63  # Setup snowboy
64  self.detector = snowboydecoder.HotwordDetector(self.model_path,
65  sensitivity=[0.5, 0.5])
66  self.df_client = DialogflowClient()
67  rospy.loginfo("HOTWORD_CLIENT: Listening... Press Ctrl-C to stop.")
68  while True:
69  try:
70  self.detector.start(detected_callback=self._df_callback,
71  interrupt_check=self._interrupt_callback,
72  sleep_time=0.03)
73  except KeyboardInterrupt:
74  self.exit()
75 
76  def exit(self):
77  self.interrupted = True
78  self._interrupt_callback() # IDK man...
79  self.stream_out.close()
80  self.audio.terminate()
81  self.detector.terminate()
82  exit()
83 
84 
85 if __name__ == '__main__':
86  rospy.init_node('hotword_client', log_level=rospy.DEBUG)
88  hd.start()
def _signal_handler(self, signal, frame)


dialogflow_ros
Author(s): Anas Abou Allaban
autogenerated on Mon Jun 10 2019 13:02:59