无法打开WebSocket和AttributeError:'SpeechToTextClient'错误(在Python上为Watson)

时间:2018-08-13 20:43:13

标签: python websocket ibm-cloud ibm-watson

我正在尝试打开网络套接字连接以使用Python v2.7在Watson上进行语音到文本的识别

我的代码使用API​​密钥和网址。我已经尝试了几种使用此方法打开套接字的方法,但是出现了如下所示的带有流错误的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'

我尝试使用Google搜索该错误,但并不能直接判断问题是什么,也无法正确解决该问题。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:0)

尚未调用您的方法opened,因此在调用closeself.stream_audio_thread不存在。

所有可能是因为您的Web套接字创建失败。通过在内部运行方法之前检查close的存在来确保您的self.stream_audio_thread方法安全,并确定套接字创建失败的原因。

def close(self):
    self.listening = False
    if self.stream_audio_thread:
        self.stream_audio_thread.join()
    WebSocketClient.close(self)

答案 1 :(得分:0)

我最终重做了采用不同方法来实现我所需要的代码。

该解决方案在这里: Trouble passing string variable to return data from python function to be used globally anywhere in a python script or program - EDITED for clarity

谢谢。