|
4 | 4 |
|
5 | 5 | import io
|
6 | 6 | import os
|
| 7 | +import sys |
7 | 8 | import subprocess
|
8 | 9 | import wave
|
9 | 10 | import aifc
|
@@ -948,20 +949,27 @@ def recognize_bing(self, audio_data, key, language="en-US", show_all=False):
|
948 | 949 | convert_width=2 # audio samples should be 16-bit
|
949 | 950 | )
|
950 | 951 |
|
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 |
| - |
955 | 952 | url = "https://speech.platform.bing.com/speech/recognition/interactive/cognitiveservices/v1?{}".format(urlencode({
|
956 | 953 | "language": language,
|
957 | 954 | "locale": language,
|
958 | 955 | "requestid": uuid.uuid4(),
|
959 | 956 | }))
|
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 | + |
965 | 973 | try:
|
966 | 974 | response = urlopen(request, timeout=self.operation_timeout)
|
967 | 975 | except HTTPError as e:
|
|
0 commit comments