IBM Watson Speech To Text 使用 Python 请求损坏的管道

IBM Watson Speech To Text using Python Requests Broken Pipe

我正在尝试制作一个 python 脚本来访问 IBM Speech-To-Text。我试图在他们的网站上制作一个与 cURL 示例等效的命令:

curl -X POST -u <username>:<password>
--header "Content-Type: audio/flac"
--header "Transfer-Encoding: chunked"
--data-binary @<path>0001.flac 
"https://stream.watsonplatform.net/speech-to-text/api/v1/recognize?continuous=true&timestamps=true&max_alternatives=3"

我想出了以下内容:

headers = {
    'Content-Type': 'audio/flac',
    'Transfer-Encoding': 'chunked',
}
auth = (USERNAME, PASSWORD)
data = open(audio_name, 'br')
r = requests.post('https://stream.watsonplatform.net/speech-to-text/api/v1/recognize?continuous=true&timestamps=true&max_alternatives=3'
                  , headers=headers, data=data, auth=auth)

第一个命令从终端执行正常,而第二个命令给我:

requests.exceptions.ConnectionError: ('Connection aborted.', BrokenPipeError(32, 'Broken pipe'))

我该如何解决这个问题?

删除 'Transfer-Encoding': 'chunked' 并将 br 更改为 rbrequests 库将设置正确的 headers.

另一方面,我建议您使用 WDC Python SDK,这将使您的生活更轻松。

使用 pip 安装它:

pip install watson-developer-cloud

然后:

import json
from os.path import join, dirname
from watson_developer_cloud import SpeechToTextV1


speech_to_text = SpeechToTextV1(
    username='YOUR SERVICE USERNAME',
    password='YOUR SERVICE PASSWORD',
)


with open(join(dirname(__file__), './0001.flac'), 'rb') as audio_file:
    print(json.dumps(speech_to_text.recognize(
          audio_file, content_type='audio/wav', timestamps=True,
          continuous=True, timestamps=True, max_alternatives=3
         ), indent=2))