Skip to content

Commit 40d174d

Browse files
committed
Fix chunked-transfer on Python 3.6+
1 parent 3ef9bdd commit 40d174d

File tree

2 files changed

+18
-9
lines changed

2 files changed

+18
-9
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -7,5 +7,6 @@ speech_recognition/pocketsphinx-data/fr-FR/
77
speech_recognition/pocketsphinx-data/zh-CN/
88
fr-FR.zip
99
zh-CN.zip
10+
it-IT.zip
1011
pocketsphinx-python/
1112
venv/

speech_recognition/__init__.py

+17-9
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
import io
66
import os
7+
import sys
78
import subprocess
89
import wave
910
import aifc
@@ -948,20 +949,27 @@ def recognize_bing(self, audio_data, key, language="en-US", show_all=False):
948949
convert_width=2 # audio samples should be 16-bit
949950
)
950951

951-
# chunked-transfer encoding is only supported in the standard library for Python 3.6+, so we manually format the POST data as if it was a chunked request
952-
ascii_hex_data_length = "{:X}".format(len(wav_data)).encode("utf-8")
953-
chunked_transfer_encoding_data = ascii_hex_data_length + b"\r\n" + wav_data + b"\r\n0\r\n\r\n"
954-
955952
url = "https://speech.platform.bing.com/speech/recognition/interactive/cognitiveservices/v1?{}".format(urlencode({
956953
"language": language,
957954
"locale": language,
958955
"requestid": uuid.uuid4(),
959956
}))
960-
request = Request(url, data=chunked_transfer_encoding_data, headers={
961-
"Authorization": "Bearer {}".format(access_token),
962-
"Content-type": "audio/wav; codec=\"audio/pcm\"; samplerate=16000",
963-
"Transfer-Encoding": "chunked",
964-
})
957+
958+
if sys.version_info >= (3, 6): # chunked-transfer requests are only supported in the standard library as of Python 3.6+, use it if possible
959+
request = Request(url, data=io.BytesIO(wav_data), headers={
960+
"Authorization": "Bearer {}".format(access_token),
961+
"Content-type": "audio/wav; codec=\"audio/pcm\"; samplerate=16000",
962+
"Transfer-Encoding": "chunked",
963+
})
964+
else: # fall back on manually formatting the POST body as a chunked request
965+
ascii_hex_data_length = "{:X}".format(len(wav_data)).encode("utf-8")
966+
chunked_transfer_encoding_data = ascii_hex_data_length + b"\r\n" + wav_data + b"\r\n0\r\n\r\n"
967+
request = Request(url, data=chunked_transfer_encoding_data, headers={
968+
"Authorization": "Bearer {}".format(access_token),
969+
"Content-type": "audio/wav; codec=\"audio/pcm\"; samplerate=16000",
970+
"Transfer-Encoding": "chunked",
971+
})
972+
965973
try:
966974
response = urlopen(request, timeout=self.operation_timeout)
967975
except HTTPError as e:

0 commit comments

Comments
 (0)