azure speech to text rest api python 连接中止。操作系统错误 10054,WSAECONNRESET
azure speech to text rest api python Connection aborted. OSError 10054, WSAECONNRESET
我正在尝试测试 azure speech 以向其余部分发送短信 API。首先,我使用了 POSTMAN 客户端,它运行良好。
现在我正在使用 python 尝试同样的事情,但出现错误。
我正在按照 https://docs.microsoft.com/en-us/azure/cognitive-services/speech-service/rest-speech-to-text#
给出的说明进行操作
这是代码
file = open(test.wav','rb')
data = file.read()
import requests
url = "https://centralindia.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US"
payload = data
headers = {
'Ocp-Apim-Subscription-Key': {key},
'Connection': 'keep-alive',
'Content-Type': 'audio/wav; codecs=audio/pcm; samplerate=16000',
'Accept': 'application/json',
'Transfer-Encoding': 'chunked',
'Expect' : '100-continue'
}
response = requests.request("POST", url, headers=headers, data = payload)
print(response.text.encode('utf8'))
错误如下
SysCallError Traceback (most recent call last)
~\Anaconda3\lib\site-packages\urllib3\contrib\pyopenssl.py in _send_until_done(self, data)
319 try:
--> 320 return self.connection.send(data)
321 except OpenSSL.SSL.WantWriteError:
~\Anaconda3\lib\site-packages\OpenSSL\SSL.py in send(self, buf, flags)
1736 result = _lib.SSL_write(self._ssl, buf, len(buf))
-> 1737 self._raise_ssl_error(self._ssl, result)
1738 return result
~\Anaconda3\lib\site-packages\OpenSSL\SSL.py in _raise_ssl_error(self, ssl, result)
1638 if errno != 0:
-> 1639 raise SysCallError(errno, errorcode.get(errno))
1640 raise SysCallError(-1, "Unexpected EOF")
SysCallError: (10054, 'WSAECONNRESET')
During handling of the above exception, another exception occurred:
OSError Traceback (most recent call last)
~\Anaconda3\lib\site-packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
599 body=body, headers=headers,
--> 600 chunked=chunked)
601
~\Anaconda3\lib\site-packages\urllib3\connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
353 else:
--> 354 conn.request(method, url, **httplib_request_kw)
355
~\Anaconda3\lib\http\client.py in request(self, method, url, body, headers, encode_chunked)
1238 """Send a complete request to the server."""
-> 1239 self._send_request(method, url, body, headers, encode_chunked)
1240
~\Anaconda3\lib\http\client.py in _send_request(self, method, url, body, headers, encode_chunked)
1284 body = _encode(body, 'body')
-> 1285 self.endheaders(body, encode_chunked=encode_chunked)
1286
~\Anaconda3\lib\http\client.py in endheaders(self, message_body, encode_chunked)
1233 raise CannotSendHeader()
-> 1234 self._send_output(message_body, encode_chunked=encode_chunked)
1235
~\Anaconda3\lib\http\client.py in _send_output(self, message_body, encode_chunked)
1064 + b'\r\n'
-> 1065 self.send(chunk)
1066
~\Anaconda3\lib\http\client.py in send(self, data)
985 try:
--> 986 self.sock.sendall(data)
987 except TypeError:
~\Anaconda3\lib\site-packages\urllib3\contrib\pyopenssl.py in sendall(self, data)
330 while total_sent < len(data):
--> 331 sent = self._send_until_done(data[total_sent:total_sent + SSL_WRITE_BLOCKSIZE])
332 total_sent += sent
~\Anaconda3\lib\site-packages\urllib3\contrib\pyopenssl.py in _send_until_done(self, data)
325 except OpenSSL.SSL.SysCallError as e:
--> 326 raise SocketError(str(e))
327
OSError: (10054, 'WSAECONNRESET')
During handling of the above exception, another exception occurred:
ProtocolError Traceback (most recent call last)
~\Anaconda3\lib\site-packages\requests\adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
448 retries=self.max_retries,
--> 449 timeout=timeout
450 )
~\Anaconda3\lib\site-packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
637 retries = retries.increment(method, url, error=e, _pool=self,
--> 638 _stacktrace=sys.exc_info()[2])
639 retries.sleep()
~\Anaconda3\lib\site-packages\urllib3\util\retry.py in increment(self, method, url, response, error, _pool, _stacktrace)
367 if read is False or not self._is_method_retryable(method):
--> 368 raise six.reraise(type(error), error, _stacktrace)
369 elif read is not None:
~\Anaconda3\lib\site-packages\urllib3\packages\six.py in reraise(tp, value, tb)
684 if value.__traceback__ is not tb:
--> 685 raise value.with_traceback(tb)
686 raise value
~\Anaconda3\lib\site-packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
599 body=body, headers=headers,
--> 600 chunked=chunked)
601
~\Anaconda3\lib\site-packages\urllib3\connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
353 else:
--> 354 conn.request(method, url, **httplib_request_kw)
355
~\Anaconda3\lib\http\client.py in request(self, method, url, body, headers, encode_chunked)
1238 """Send a complete request to the server."""
-> 1239 self._send_request(method, url, body, headers, encode_chunked)
1240
~\Anaconda3\lib\http\client.py in _send_request(self, method, url, body, headers, encode_chunked)
1284 body = _encode(body, 'body')
-> 1285 self.endheaders(body, encode_chunked=encode_chunked)
1286
~\Anaconda3\lib\http\client.py in endheaders(self, message_body, encode_chunked)
1233 raise CannotSendHeader()
-> 1234 self._send_output(message_body, encode_chunked=encode_chunked)
1235
~\Anaconda3\lib\http\client.py in _send_output(self, message_body, encode_chunked)
1064 + b'\r\n'
-> 1065 self.send(chunk)
1066
~\Anaconda3\lib\http\client.py in send(self, data)
985 try:
--> 986 self.sock.sendall(data)
987 except TypeError:
~\Anaconda3\lib\site-packages\urllib3\contrib\pyopenssl.py in sendall(self, data)
330 while total_sent < len(data):
--> 331 sent = self._send_until_done(data[total_sent:total_sent + SSL_WRITE_BLOCKSIZE])
332 total_sent += sent
~\Anaconda3\lib\site-packages\urllib3\contrib\pyopenssl.py in _send_until_done(self, data)
325 except OpenSSL.SSL.SysCallError as e:
--> 326 raise SocketError(str(e))
327
ProtocolError: ('Connection aborted.', OSError("(10054, 'WSAECONNRESET')",))
During handling of the above exception, another exception occurred:
ConnectionError Traceback (most recent call last)
<ipython-input-75-405437dcff4f> in <module>
14 }
15
---> 16 response = requests.request("POST", url, headers=headers, data = payload)
17
18 print(response.text.encode('utf8'))
~\Anaconda3\lib\site-packages\requests\api.py in request(method, url, **kwargs)
58 # cases, and look like a memory leak in others.
59 with sessions.Session() as session:
---> 60 return session.request(method=method, url=url, **kwargs)
61
62
~\Anaconda3\lib\site-packages\requests\sessions.py in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
531 }
532 send_kwargs.update(settings)
--> 533 resp = self.send(prep, **send_kwargs)
534
535 return resp
~\Anaconda3\lib\site-packages\requests\sessions.py in send(self, request, **kwargs)
644
645 # Send the request
--> 646 r = adapter.send(request, **kwargs)
647
648 # Total elapsed time of the request (approximately)
~\Anaconda3\lib\site-packages\requests\adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
496
497 except (ProtocolError, socket.error) as err:
--> 498 raise ConnectionError(err, request=request)
499
500 except MaxRetryError as e:
ConnectionError: ('Connection aborted.', OSError("(10054, 'WSAECONNRESET')",))
尝试将语音转换为文本 API:
import json,http.client, urllib.request, urllib.parse, urllib.error, base64
host = '<your speech to text host>'
key = '<your subscription key>'
filePath ='<path of your audio file>'
headers = {
# Request headers
'Content-Type': 'udio/wav; codecs=audio/pcm; samplerate=16000',
'Ocp-Apim-Subscription-Key': key
}
requestURL= "/speech/recognition/conversation/cognitiveservices/v1?language=en-US&format=detailed"
audioData = open(filePath, 'rb').read()
conn = http.client.HTTPSConnection(host)
conn.request("POST", requestURL , audioData, headers)
response = conn.getresponse()
data = response.read()
print(data)
print(response.getcode())
conn.close()
测试结果:
希望对您有所帮助。
好的,我不确定这是否是正确的解决方案。但我可以说是什么解决了我的问题
首先尝试了Stanley Gong的答案中给出的代码。它没有给出 OSError 10054 但我收到错误
b'{"error":{"code":"404","message": "Resource not found"}}'
404
所以我想哦,有些东西在工作,但后来我将我的代码与 Stanley 的代码进行了比较,并思考是什么导致了错误?有什么区别
然后我注释掉了
#'Transfer-Encoding': 'chunked',
在header
我的工作代码(这次我使用的是请求模块)
file = open(r'test.wav','rb')
data = file.read()
import requests
url = "https://centralindia.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US"
payload = data
headers = {
'Ocp-Apim-Subscription-Key': {key},
'Connection': 'keep-alive',
'Content-Type': 'audio/wav; codecs=audio/pcm; samplerate=16000',
'Accept': 'application/json',
#'Transfer-Encoding': 'chunked',
'Expect' : '100-continue'
}
response = requests.request("POST", url, headers=headers, data = payload)
print(response.text.encode('utf8'))
感谢 Stanley 和 joshvito 的回复
我正在尝试测试 azure speech 以向其余部分发送短信 API。首先,我使用了 POSTMAN 客户端,它运行良好。
这是代码
file = open(test.wav','rb')
data = file.read()
import requests
url = "https://centralindia.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US"
payload = data
headers = {
'Ocp-Apim-Subscription-Key': {key},
'Connection': 'keep-alive',
'Content-Type': 'audio/wav; codecs=audio/pcm; samplerate=16000',
'Accept': 'application/json',
'Transfer-Encoding': 'chunked',
'Expect' : '100-continue'
}
response = requests.request("POST", url, headers=headers, data = payload)
print(response.text.encode('utf8'))
错误如下
SysCallError Traceback (most recent call last)
~\Anaconda3\lib\site-packages\urllib3\contrib\pyopenssl.py in _send_until_done(self, data)
319 try:
--> 320 return self.connection.send(data)
321 except OpenSSL.SSL.WantWriteError:
~\Anaconda3\lib\site-packages\OpenSSL\SSL.py in send(self, buf, flags)
1736 result = _lib.SSL_write(self._ssl, buf, len(buf))
-> 1737 self._raise_ssl_error(self._ssl, result)
1738 return result
~\Anaconda3\lib\site-packages\OpenSSL\SSL.py in _raise_ssl_error(self, ssl, result)
1638 if errno != 0:
-> 1639 raise SysCallError(errno, errorcode.get(errno))
1640 raise SysCallError(-1, "Unexpected EOF")
SysCallError: (10054, 'WSAECONNRESET')
During handling of the above exception, another exception occurred:
OSError Traceback (most recent call last)
~\Anaconda3\lib\site-packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
599 body=body, headers=headers,
--> 600 chunked=chunked)
601
~\Anaconda3\lib\site-packages\urllib3\connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
353 else:
--> 354 conn.request(method, url, **httplib_request_kw)
355
~\Anaconda3\lib\http\client.py in request(self, method, url, body, headers, encode_chunked)
1238 """Send a complete request to the server."""
-> 1239 self._send_request(method, url, body, headers, encode_chunked)
1240
~\Anaconda3\lib\http\client.py in _send_request(self, method, url, body, headers, encode_chunked)
1284 body = _encode(body, 'body')
-> 1285 self.endheaders(body, encode_chunked=encode_chunked)
1286
~\Anaconda3\lib\http\client.py in endheaders(self, message_body, encode_chunked)
1233 raise CannotSendHeader()
-> 1234 self._send_output(message_body, encode_chunked=encode_chunked)
1235
~\Anaconda3\lib\http\client.py in _send_output(self, message_body, encode_chunked)
1064 + b'\r\n'
-> 1065 self.send(chunk)
1066
~\Anaconda3\lib\http\client.py in send(self, data)
985 try:
--> 986 self.sock.sendall(data)
987 except TypeError:
~\Anaconda3\lib\site-packages\urllib3\contrib\pyopenssl.py in sendall(self, data)
330 while total_sent < len(data):
--> 331 sent = self._send_until_done(data[total_sent:total_sent + SSL_WRITE_BLOCKSIZE])
332 total_sent += sent
~\Anaconda3\lib\site-packages\urllib3\contrib\pyopenssl.py in _send_until_done(self, data)
325 except OpenSSL.SSL.SysCallError as e:
--> 326 raise SocketError(str(e))
327
OSError: (10054, 'WSAECONNRESET')
During handling of the above exception, another exception occurred:
ProtocolError Traceback (most recent call last)
~\Anaconda3\lib\site-packages\requests\adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
448 retries=self.max_retries,
--> 449 timeout=timeout
450 )
~\Anaconda3\lib\site-packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
637 retries = retries.increment(method, url, error=e, _pool=self,
--> 638 _stacktrace=sys.exc_info()[2])
639 retries.sleep()
~\Anaconda3\lib\site-packages\urllib3\util\retry.py in increment(self, method, url, response, error, _pool, _stacktrace)
367 if read is False or not self._is_method_retryable(method):
--> 368 raise six.reraise(type(error), error, _stacktrace)
369 elif read is not None:
~\Anaconda3\lib\site-packages\urllib3\packages\six.py in reraise(tp, value, tb)
684 if value.__traceback__ is not tb:
--> 685 raise value.with_traceback(tb)
686 raise value
~\Anaconda3\lib\site-packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
599 body=body, headers=headers,
--> 600 chunked=chunked)
601
~\Anaconda3\lib\site-packages\urllib3\connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
353 else:
--> 354 conn.request(method, url, **httplib_request_kw)
355
~\Anaconda3\lib\http\client.py in request(self, method, url, body, headers, encode_chunked)
1238 """Send a complete request to the server."""
-> 1239 self._send_request(method, url, body, headers, encode_chunked)
1240
~\Anaconda3\lib\http\client.py in _send_request(self, method, url, body, headers, encode_chunked)
1284 body = _encode(body, 'body')
-> 1285 self.endheaders(body, encode_chunked=encode_chunked)
1286
~\Anaconda3\lib\http\client.py in endheaders(self, message_body, encode_chunked)
1233 raise CannotSendHeader()
-> 1234 self._send_output(message_body, encode_chunked=encode_chunked)
1235
~\Anaconda3\lib\http\client.py in _send_output(self, message_body, encode_chunked)
1064 + b'\r\n'
-> 1065 self.send(chunk)
1066
~\Anaconda3\lib\http\client.py in send(self, data)
985 try:
--> 986 self.sock.sendall(data)
987 except TypeError:
~\Anaconda3\lib\site-packages\urllib3\contrib\pyopenssl.py in sendall(self, data)
330 while total_sent < len(data):
--> 331 sent = self._send_until_done(data[total_sent:total_sent + SSL_WRITE_BLOCKSIZE])
332 total_sent += sent
~\Anaconda3\lib\site-packages\urllib3\contrib\pyopenssl.py in _send_until_done(self, data)
325 except OpenSSL.SSL.SysCallError as e:
--> 326 raise SocketError(str(e))
327
ProtocolError: ('Connection aborted.', OSError("(10054, 'WSAECONNRESET')",))
During handling of the above exception, another exception occurred:
ConnectionError Traceback (most recent call last)
<ipython-input-75-405437dcff4f> in <module>
14 }
15
---> 16 response = requests.request("POST", url, headers=headers, data = payload)
17
18 print(response.text.encode('utf8'))
~\Anaconda3\lib\site-packages\requests\api.py in request(method, url, **kwargs)
58 # cases, and look like a memory leak in others.
59 with sessions.Session() as session:
---> 60 return session.request(method=method, url=url, **kwargs)
61
62
~\Anaconda3\lib\site-packages\requests\sessions.py in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
531 }
532 send_kwargs.update(settings)
--> 533 resp = self.send(prep, **send_kwargs)
534
535 return resp
~\Anaconda3\lib\site-packages\requests\sessions.py in send(self, request, **kwargs)
644
645 # Send the request
--> 646 r = adapter.send(request, **kwargs)
647
648 # Total elapsed time of the request (approximately)
~\Anaconda3\lib\site-packages\requests\adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
496
497 except (ProtocolError, socket.error) as err:
--> 498 raise ConnectionError(err, request=request)
499
500 except MaxRetryError as e:
ConnectionError: ('Connection aborted.', OSError("(10054, 'WSAECONNRESET')",))
尝试将语音转换为文本 API:
import json,http.client, urllib.request, urllib.parse, urllib.error, base64
host = '<your speech to text host>'
key = '<your subscription key>'
filePath ='<path of your audio file>'
headers = {
# Request headers
'Content-Type': 'udio/wav; codecs=audio/pcm; samplerate=16000',
'Ocp-Apim-Subscription-Key': key
}
requestURL= "/speech/recognition/conversation/cognitiveservices/v1?language=en-US&format=detailed"
audioData = open(filePath, 'rb').read()
conn = http.client.HTTPSConnection(host)
conn.request("POST", requestURL , audioData, headers)
response = conn.getresponse()
data = response.read()
print(data)
print(response.getcode())
conn.close()
测试结果:
希望对您有所帮助。
好的,我不确定这是否是正确的解决方案。但我可以说是什么解决了我的问题
首先尝试了Stanley Gong的答案中给出的代码。它没有给出 OSError 10054 但我收到错误
b'{"error":{"code":"404","message": "Resource not found"}}'
404
所以我想哦,有些东西在工作,但后来我将我的代码与 Stanley 的代码进行了比较,并思考是什么导致了错误?有什么区别
然后我注释掉了
#'Transfer-Encoding': 'chunked',
在header
我的工作代码(这次我使用的是请求模块)
file = open(r'test.wav','rb')
data = file.read()
import requests
url = "https://centralindia.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US"
payload = data
headers = {
'Ocp-Apim-Subscription-Key': {key},
'Connection': 'keep-alive',
'Content-Type': 'audio/wav; codecs=audio/pcm; samplerate=16000',
'Accept': 'application/json',
#'Transfer-Encoding': 'chunked',
'Expect' : '100-continue'
}
response = requests.request("POST", url, headers=headers, data = payload)
print(response.text.encode('utf8'))
感谢 Stanley 和 joshvito 的回复