代码之家  ›  专栏  ›  技术社区  ›  ironmantis7x

未能打开WebSocket和AttributeError:“SpeechToTextClient”错误(Python上的Watson)

  •  0
  • ironmantis7x  · 技术社区  · 7 年前

    我的代码使用一个API密钥和一个url。我已经尝试了多种方法使用此打开套接字,但我得到一个web套接字错误和一个流错误,如下所示:

    Failed to open WebSocket.
    Failed to open WebSocket.
    Traceback (most recent call last): File "jasmineV3.py", line 78, in <module>
        SpeechToTextClient().close() File "jasmineV3.py", line 68, in close
        self.stream_audio_thread.join()
    AttributeError: 'SpeechToTextClient' object has no attribute 'stream_audio_thread'
    

    这是我的代码,我正在努力使工作:

    #import os
    #import time
    #import json
    import watson_developer_cloud
    import speech_recognition as sr
    from gtts import gTTS
    from time import ctime
    #from __future__ import print_function
    
    from os.path import join, dirname
    from watson_developer_cloud import SpeechToTextV1
    from watson_developer_cloud.websocket import RecognizeCallback
    from ws4py.client.threadedclient import WebSocketClient
    import base64, json, ssl, subprocess, threading, time
    
    class SpeechToTextClient(WebSocketClient):
        def __init__(self):
    
            speech_to_text = SpeechToTextV1(iam_api_key = 'xxxxxxxx', url = 'xxxxxxx')
    
            self.listening = False
    
            try:
                WebSocketClient.__init__(self, speech_to_text)
                self.connect()
            except: print "Failed to open WebSocket."
    
        def opened(self):
            self.send('{"action": "start", "content-type": "audio/l16;rate=16000"}')
            self.stream_audio_thread = threading.Thread(target=self.stream_audio)
            self.stream_audio_thread.start()
    
        def received_message(self, message):
            message = json.loads(str(message))
            if "state" in message:
                if message["state"] == "listening":
                    self.listening = True
            print "Message received: " + str(message)
    
        def stream_audio(self):
            while not self.listening:
                time.sleep(0.1)
    
            reccmd = ["arecord", "-f", "S16_LE", "-r", "16000", "-t", "raw"]
            p = subprocess.Popen(reccmd, stdout=subprocess.PIPE)
    
            while self.listening:
                data = p.stdout.read(1024)
    
                try: self.send(bytearray(data), binary=True)
                except ssl.SSLError: pass
    
            p.kill()
    
        def close(self):
            self.listening = False
            self.stream_audio_thread.join()
            WebSocketClient.close(self)
    
    try:
        stt_client = SpeechToTextClient()
        #raw_input()
        speech_to_text = SpeechToTextV1(
            iam_api_key = 'xxxxxxxxx',
            url = 'xxxxxxxx')
    finally:
        SpeechToTextClient().close()
    

    有人能帮我找出我的错误和解决方法吗?

    *******更新更新********

    因此,在对下面发布的答案进行反馈后,我得出了以下代码:

    from watson_developer_cloud import SpeechToTextV1
    from watson_developer_cloud.websocket import RecognizeCallback
    from os.path import join, dirname
    
    import watson_developer_cloud
    import speech_recognition as sr
    from gtts import gTTS
    from time import ctime
    from os.path import join, dirname
    from watson_developer_cloud import SpeechToTextV1
    from ws4py.client.threadedclient import WebSocketClient
    import base64, json, ssl, subprocess, threading, time
    import os
    import json
    
    speech_to_text = SpeechToTextV1(
        username='{username}',
        password='{password}',
        iam_api_key = 'B5AmAyElAbvr6Z6dvW-CufLPwYsmKndNtAiGp4btg6s3',
        url = 'https://gateway-wdc.watsonplatform.net/speech-to-text/api/v1/recognize')
    
    class MyRecognizeCallback(RecognizeCallback):
        def __init__(self):
            RecognizeCallback.__init__(self)
    
        def on_data(self, data):
            print(json.dumps(data, indent=2))
    
        def on_error(self, error):
            print('Error received: {}'.format(error))
    
        def on_inactivity_timeout(self, error):
            print('Inactivity timeout: {}'.format(error))
    
    myRecognizeCallback = MyRecognizeCallback()
    
    with open(join(dirname(__file__), '/home/ironmantis7x/Documents/MaverickAITech/JasmineAI', 'audio.mp3'),
                  'rb') as audio_file:
        speech_to_text.recognize_using_websocket(
            audio=audio_file,
            content_type='audio/mp3',
            model='en-US_BroadbandModel',
            recognize_callback=myRecognizeCallback,
            interim_results=False,
            keywords=['hello', 'hi', 'turn on', 'directions'],
            keywords_threshold=0.5,
            max_alternatives=3) 
    

    Traceback (most recent call last):
      File "jasmineV7.py", line 37, in <module>
        speech_to_text.recognize_using_websocket(
    AttributeError: 'SpeechToTextV1' object has no attribute 'recognize_using_websocket'
    

    我在谷歌上搜索了一下这个错误,但这并不是直接的问题,也不是如何正确地解决它。如有任何帮助,我们将不胜感激。

    2 回复  |  直到 7 年前
        1
  •  0
  •   chughts    7 年前

    你的方法 opened 没有人打电话给你,所以当你打电话的时候 close self.stream_audio_thread 不存在。

    关闭 self.stream_音频线程

    def close(self):
        self.listening = False
        if self.stream_audio_thread:
            self.stream_audio_thread.join()
        WebSocketClient.close(self)
    
        2
  •  0
  •   ironmantis7x    7 年前

    最后,我重新编写了代码,使用了不同的方法来实现我所需要的。

    解决方法如下: Trouble passing string variable to return data from python function to be used globally anywhere in a python script or program - EDITED for clarity

    谢谢。