Search code examples
python-requestsazure-api-managementazure-cognitive-servicesazure-rest-apiazure-speech

azure speech to text rest api python Connection aborted. OSError 10054, WSAECONNRESET


I am trying to test azure speech to text the rest API. First of all I used POSTMAN client and it worked fine. Response of POSTMAN Now I am trying the same thing using python but getting an error. I am following instructions given as per the https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/rest-speech-to-text#

This is the code

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'))

Below is the error

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')",))

Solution

  • Ok i am not sure if this is correct solution. But i can tell what resolved my problem

    First of all tried the code given in the answer by Stanley Gong. It didnt give OSError 10054 but i got error as

    b'{"error":{"code":"404","message": "Resource not found"}}'
    404
    

    So i was like oh something is working but then i compared my code with that of Stanley and thought what is causing the error?what is the difference

    Then i commented out

     #'Transfer-Encoding': 'chunked',
    

    in header

    My working code (this time I am using request module)

    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'))
    

    Thanks to Stanley and joshvito for responding