Advertisement
Guest User

Python Script

a guest
Mar 27th, 2018
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.84 KB | None | 0 0
  1. # TTS elements derived from
  2. # Joshua Rees-Jones, IBM intern
  3. # "Getting robots to listen"
  4. #
  5. # Conversation elements derived from:
  6. # watson-developer-cloud/python-sdk/examples/conversation_v1.py
  7. #
  8. # Snowboy elements derived from
  9. # Kitt-AI/snowboy/examples/Python/demo.py
  10. #
  11.  
  12. from ws4py.client.threadedclient import WebSocketClient
  13. from watson_developer_cloud import ConversationV1
  14. import sys, signal, snowboydecoder, re, base64, json, ssl, subprocess, threading, time
  15.  
  16. # Initialising TTS global variables
  17. speech_received = False # has speech been returned by Watson?
  18. transcript = "silence" # default value for speech if nothing returned
  19.  
  20. # Initialise conversation global variables
  21. conversation = ConversationV1(
  22. username='c9a2170c-c2b4-436b-a4a7-b51ff43412c6',
  23. password='xDLxHMmAIDtC',
  24. version='2018-02-16')
  25. workspace_id = '85919db8-1efc-4903-b8a2-8e08ba67a6a9'
  26.  
  27. # Initialise the PWM device using the default address
  28. # pwm = PWM(0x40)
  29. # pwm.setPWMFreq(100) # Set frequency to 100 Hz
  30.  
  31. # Create names for each PWM channel
  32. # PWM_eye = 0
  33. # PWM_hover = 1
  34.  
  35. def signal_handler(signal, frame):
  36. global interrupted
  37. interrupted = True
  38. def interrupt_callback():
  39. global interrupted
  40. return interrupted
  41.  
  42. # Initialise snowboy global variables
  43. model = "./K9.pmdl"
  44. ##model = sys.argv[1]
  45. interrupted = False
  46.  
  47. signal.signal(signal.SIGINT, signal_handler)
  48.  
  49. detector = snowboydecoder.HotwordDetector(model, sensitivity=0.7)
  50.  
  51. # Web Socket object for communicating to Watson Developer Cloud
  52. # Test to Speech
  53. class SpeechToTextClient(WebSocketClient):
  54. def __init__(self):
  55. username = "71bcad99-9a37-449d-b5c7-4aabcbc4c495"
  56. password = "AZOXanrF3Ful"
  57. ws_url = "wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize"
  58. ##ws_url = "https://stream.watsonplatform.net/speech-to-text/api"
  59. auth_string = "%s:%s" % (username, password)
  60. base64string = base64.encodestring(auth_string).replace("\n", "")
  61. self.listening = False
  62. print "def_init_(self), self.listening = False"
  63. try:
  64. WebSocketClient.__init__(self, ws_url,
  65. headers=[("Authorization", "Basic %s" % base64string)])
  66. self.connect()
  67. print "self.connect()"
  68. except: print "Failed to open WebSocket."
  69. def opened(self):
  70. print "opened(self) and self.send"
  71. self.send('{"action": "start", "content-type": "audio/l16;rate=48000"}')
  72. self.stream_audio_thread = threading.Thread(target=self.stream_audio)
  73. self.stream_audio_thread.start()
  74. def received_message(self, message):
  75. global speech_received
  76. global transcript
  77. # global pwm
  78. message = json.loads(str(message))
  79. print "Received: " + str(message)
  80. if "state" in message and not speech_received:
  81. if message["state"] == "listening":
  82. self.listening = True
  83. # set_PWM(PWM_eye,100)
  84. print "Listening is now true"
  85. if "results" in message:
  86. self.listening = False
  87. speech_received = True
  88. print "Sending stop transcription message"
  89. self.send('{"action": "stop"}')
  90. results = re.search('transcript\'\: u\'(.*)\'\}\]', str(message))
  91. if results:
  92. transcript = results.group(1)
  93. print str(transcript)
  94. # set_PWM(PWM_eye,3)
  95. self.close()
  96. print "Speech_received, exiting"
  97. # self.close()
  98. # sys.exit()
  99. if "error" in message:
  100. speech_received = True
  101. self.listening = False
  102. self.send('{"action": "stop"}')
  103. print "no speech heard for 30 seconds, exiting"
  104. # set_PWM(PWM_eye,3)
  105. self.close()
  106. def stream_audio(self):
  107. print "Entering stream_audio(self)"
  108. while not self.listening:
  109. print "sleeping"
  110. time.sleep(0.1)
  111. reccmd = ["arecord", "-f", "S16_LE", "-r", "48000", "-t", "raw"]
  112. print "arecord and p=subprocess.Popen"
  113. p = subprocess.Popen(reccmd, stdout=subprocess.PIPE)
  114. while self.listening:
  115. data = p.stdout.read(1024)
  116. try:
  117. print "self.send bytearray"
  118. self.send(bytearray(data), binary=True)
  119. except ssl.SSLError: pass
  120. p.kill()
  121. print "p.kill()"
  122. def close(self):
  123. self.listening = False
  124. speech_received = True
  125. self.stream_audio_thread.join()
  126. print "close self - self.listening false - clean closure"
  127.  
  128. # K9 hotword has been detected
  129. def K9_detected():
  130. # global pwm
  131. print "K9 detected\n"
  132. # set_PWM(PWM_eye,30)
  133. global stop_now
  134. stop_now = True # get the detector to terminate
  135.  
  136. def speech_to_text():
  137. global transcript
  138. global speech_received
  139. speech_received = False # has speech been returned by Watson?
  140. transcript = "silence" # default value for speech if nothing returned
  141. print "stt_client initialisation"
  142. stt_client = SpeechToTextClient()
  143. while not speech_received:
  144. print "not hearing anything, so sleeping"
  145. time.sleep(0.1)
  146. return transcript
  147.  
  148. def stop_snowboy():
  149. global stop_now
  150. print "Waiting: " + str(stop_now)
  151. return stop_now
  152.  
  153. # Sets brightness of PWM lights from 0 to 100
  154. # def set_PWM(light, brightness):
  155. # global pwm
  156. # light = int(light)
  157. #brightness = int(float(brightness)*40.95)
  158. #if light >=0 and light <=15: # check that PWM channel exists
  159. #if brightness >= 0 and brightness <= 4095: # check that frequency is valid
  160. #pwm.setPWM(0,light,brightness)
  161.  
  162. # Initialise the eye lights at 3%
  163. # set_PWM(PWM_eye,3)
  164. print "Init Done"
  165. go = True
  166. while go:
  167. print "Calling listen_for_K9"
  168. interrupted = False
  169. stop_now = False
  170. print "Listening for K9 keyword... press Ctrl+C to exit"
  171. detector.start(detected_callback=K9_detected,
  172. interrupt_check=stop_snowboy,
  173. sleep_time=0.03)
  174. detector.terminate()
  175. time.sleep(0.03)
  176. speech_received = False
  177. transcript = "silence"
  178. print "Calling speech_to_text"
  179. speech_to_text()
  180. print "To conversation: " + transcript
  181. response = conversation.message(workspace_id=workspace_id, message_input={'text':transcript})
  182. results = re.search('\], u\'text\': \[u\'(.*)\'\]\}, u\'alt', str(response))
  183. answer = results.group(1)
  184. answer = './tts ' + answer
  185. print str(answer)
  186. subprocess.call(answer, shell=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement