#grpc #google-text-to-speech #gtts
#grpc #google-преобразование текста в речь #gtts
Вопрос:
Как вы можете видеть в приведенном ниже коде, я инициализировал клиент TTS и использую этот клиент для синтеза выходных данных для всех запросов. Это выдает ошибки. Но, если я инициализирую клиент для каждого запроса, помещая код client = texttospeech.TextToSpeechClient()
внутри функции генератора, он работает нормально.
from flask import Flask, request
from google.cloud import texttospeech
app = Flask(__name__)
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = '/path/to/json'
# Initialize client
client = texttospeech.TextToSpeechClient()
voice = texttospeech.VoiceSelectionParams(
language_code="en-US", ssml_gender=texttospeech.SsmlVoiceGender.NEUTRAL
)
audio_config = texttospeech.AudioConfig(
audio_encoding=texttospeech.AudioEncoding.LINEAR16
)
@app.route('/generate', methods=['GET'])
def generator():
text = request.args.get('text')
# Google TTS
synthesis_input = texttospeech.SynthesisInput(text=text)
response = client.synthesize_speech(input=synthesis_input, voice=voice, audio_config=audio_config)
return 'some variable'
if __name__ == '__main__':
app.run(debug=True, host = '0.0.0.0', port='8000', threaded=False)
Теперь, когда я отправляю несколько таких запросов —
for i in range(100):
requests.get('ip:port/generate', {'text': 'some large text. ' * 200})
Первоначальные 3-4 запроса работают хорошо. После этого некоторые запросы начинают получать внутреннюю ошибку (500). Это полная обратная трассировка —
Traceback (most recent call last):
File "/some/path/lib/python3.8/site-packages/google/api_core/grpc_helpers.py", line 73, in error_remapped_callable
return callable_(*args, **kwargs)
File "/some/path/lib/python3.8/site-packages/grpc/_channel.py", line 923, in __call__
return _end_unary_response_blocking(state, call, False, None)
File "/some/path/lib/python3.8/site-packages/grpc/_channel.py", line 826, in _end_unary_response_blocking
raise _InactiveRpcError(state)
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
status = StatusCode.UNKNOWN
details = "Stream removed"
debug_error_string = "{"created":"@1614073936.608639390","description":"Error received from peer ipv4:74.125.142.95:443","file":"src/core/lib/surface/call.cc","file_line":1067,"grpc_message":"Stream removed","grpc_status":2}"
>
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/some/path/lib/python3.8/site-packages/flask/app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "/some/path/lib/python3.8/site-packages/flask/app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "/some/path/lib/python3.8/site-packages/flask/app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "/some/path/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/some/path/lib/python3.8/site-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/some/path/lib/python3.8/site-packages/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/some/path/lib/python3.8/site-packages/flask/app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/some/path/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/some/path/lib/python3.8/site-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/some/path/lib/python3.8/site-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/current/app/path/deploy.py", line 37, in video_generator
response = client.synthesize_speech(input=synthesis_input, voice=voice, audio_config=audio_config)
File "/some/path/lib/python3.8/site-packages/google/cloud/texttospeech_v1/services/text_to_speech/client.py", line 374, in synthesize_speech
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
File "/some/path/lib/python3.8/site-packages/google/api_core/gapic_v1/method.py", line 145, in __call__
return wrapped_func(*args, **kwargs)
File "/some/path/lib/python3.8/site-packages/google/api_core/grpc_helpers.py", line 75, in error_remapped_callable
six.raise_from(exceptions.from_grpc_error(exc), exc)
File "<string>", line 3, in raise_from
# Permission is hereby granted, free of charge, to any person obtaining a copy
google.api_core.exceptions.Unknown: None Stream removed