通过 python 对文本 api 调用进行 Azure 语音时出错

Error while making azure speech to text api call via python

我正在尝试使用 Azure 语音通过 python 发送文本 api。下面是代码。

import http.client, urllib.request, urllib.parse, urllib.error, base64

headers = {
    # Request headers
    'Content-Type': 'application/json',
    'Ocp-Apim-Subscription-Key': '<my_subscription_key>',
}

params = urllib.parse.urlencode({
  "contentUrls": [
      "<URI_TO_MY_AUDIO_FILE>",
  ],
  "properties": {
  },
  "locale": "en-US",
  "displayName": "Transcription"
})

try:
    conn = http.client.HTTPSConnection('eastus.api.cognitive.microsoft.com')
    conn.request("POST", "/speechtotext/v3.0/transcriptions?%s" % params, "{body}", headers)
    response = conn.getresponse()
    data = response.read()
    print(data)
    conn.close()
except Exception as e:
    print("[Errno {0}] {1}".format(e.errno, e.strerror))

我得到的错误是:

b'{\r\n  "code": "InvalidPayload",\r\n  "message": "Invalid JavaScript property identifier character: }. Path \'\', line 1, position 5."\r\n}'

我认为我的参数设置有误。找不到问题所在。

Python 版本 3.7

奇怪的是,同样的 HTTP 请求在通过 https://eastus.dev.cognitive.microsoft.com/docs/services/speech-to-text-api-v3-0/operations/CreateTranscription

完成时会成功

我建议改用 Python API 而不是 REST API; https://docs.microsoft.com/en-us/azure/cognitive-services/speech-service/get-started-speech-to-text?tabs=windowsinstall&pivots=programming-language-python

这看起来像是一个奇怪的错误,甚至可能是由您的音频文件中的某些内容引起的,因此切换到 Python API 可能会给您提供更有用的错误消息。

您的 POST 请求正文未以正确的格式提供。
请参阅下面更正后的代码:

import http.client
import json

headers = {
    # Request headers
    'Content-Type': 'application/json',
    'Ocp-Apim-Subscription-Key': '<my_subscription_key>',
}

body = {
  "contentUrls": [
      "<URI_TO_MY_AUDIO_FILE>",
  ],
  "properties": {
  },
  "locale": "en-US",
  "displayName": "Transcription"
}

try:
    conn = http.client.HTTPSConnection('eastus.api.cognitive.microsoft.com')
    conn.request("POST", "/speechtotext/v3.0/transcriptions", body=json.dumps(body), headers=headers)
    response = conn.getresponse()
    data = response.read()
    print(data)
    conn.close()
except Exception as e:
    print("[Errno {0}] {1}".format(e.errno, e.strerror))

谢谢,