azure речь к тексту остальные api python Соединение прервано. Ошибка 10054, WSAECONNRESET - PullRequest
1 голос
/ 21 января 2020

Я пытаюсь проверить azure речь, чтобы текст остальные API. Прежде всего, я использовал POSTMAN клиент, и он работал нормально. Response of 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')",))

Ответы [ 2 ]

0 голосов
/ 22 января 2020

Хорошо, я не уверен, что это правильное решение. Но я могу сказать, что решило мою проблему

Прежде всего попробовал код, приведенный в ответе Стэнли Гонга. Это не дало OSError 10054, но я получил ошибку как

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

Так что я вроде как о, что-то работает, но потом я сравнил свой код с кодом Стэнли и подумал, что вызывает ошибку? В чем разница

Затем я прокомментировал

 #'Transfer-Encoding': 'chunked',

в заголовке

Мой рабочий код (на этот раз я использую модуль запроса)

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

Спасибо Стэнли и joshvito за ответ

0 голосов
/ 22 января 2020

Попробуйте вызвать речь к текстовому 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()

Результат теста:

enter image description here

Надеюсь, это поможет.

...