在Google Cloud Run运行微软TTS遇RuntimeError及连接问题求助
问题描述
在Google Cloud Run上运行微软文本转语音(TTS)服务时出现两类异常,仅通过Cloud Build构建部署时触发,本地构建镜像直接部署则完全正常:
初始错误:平台初始化失败
报错栈:
Traceback (most recent call last): File "/code/app/./speech/backend.py", line 42, in save_text_to_speech speech_api.speech() File "/code/app/./speech/speech_api.py", line 266, in speech synthesizer = SpeechSynthesizer(speech_config=self.speech_config, audio_config=audio_config) File "/usr/local/lib/python3.9/site-packages/azure/cognitiveservices/speech/speech.py", line 1598, in __init__ self._impl = self._get_impl(impl.SpeechSynthesizer, speech_config, audio_config, File "/usr/local/lib/python3.9/site-packages/azure/cognitiveservices/speech/speech.py", line 1703, in _get_impl _impl = synth_type._from_config(speech_config._impl, None if audio_config is None else audio_config._impl) RuntimeError: Runtime error: Failed to initialize platform (azure-c-shared). Error: 2153
触发代码片段:
audio_config = AudioOutputConfig(filename=file_name) synthesizer = SpeechSynthesizer(speech_config=self.speech_config, audio_config=audio_config) synthesizer.speak_ssml(self.input_data['text'])
本地环境:
- MacOS 11.6.2
- Docker v20.10.10
已尝试操作:清除kaniko缓存、切换Cloud Build构建工具为gcr.io/cloud-builders/docker,问题未解决。
2023-07-18更新:WebSocket连接错误
更新后的Dockerfile:
FROM python:3.11 WORKDIR /app RUN apt-get update && \ apt-get install -y build-essential libssl-dev ca-certificates libasound2 wget && \ wget -O - https://www.openssl.org/source/openssl-1.1.1u.tar.gz | tar zxf - && \ cd openssl-1.1.1u && \ ./config --prefix=/usr/local && \ make -j $(nproc) && \ make install_sw install_ssldirs && \ ldconfig -v && \ export SSL_CERT_DIR=/etc/ssl/certs && \ cd ../ && \ rm -rf openssl-1.1.1u && \ pip install --no-cache-dir azure-cognitiveservices-speech==1.30.0 COPY . /app CMD ["python3", "app.py"]
测试代码(基于官方示例):
import os import azure.cognitiveservices.speech as speechsdk speech_config = speechsdk.SpeechConfig(subscription=os.environ.get('SPEECH_KEY'), region=os.environ.get('SPEECH_REGION')) audio_config = speechsdk.audio.AudioOutputConfig(use_default_speaker=True) print('key:'+os.environ.get('SPEECH_KEY')) print('region:'+os.environ.get('SPEECH_REGION')) speech_config.speech_synthesis_voice_name='en-US-JennyNeural' speech_synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config, audio_config=audio_config) text = "Hello world!" speech_synthesis_result = speech_synthesizer.speak_text_async(text).get() if speech_synthesis_result.reason == speechsdk.ResultReason.SynthesizingAudioCompleted: print("Speech synthesized for text [{}]".format(text)) elif speech_synthesis_result.reason == speechsdk.ResultReason.Canceled: cancellation_details = speech_synthesis_result.cancellation_details print("Speech synthesis canceled: {}".format(cancellation_details.reason)) if cancellation_details.reason == speechsdk.CancellationReason.Error: if cancellation_details.error_details: print("Error details: {}".format(cancellation_details.error_details)) print("Did you set the speech resource key and region values?")
新报错信息:
Speech synthesis canceled: CancellationReason.Error Error details: Connection failed (no connection to the remote host). Internal error: 1. Error details: Failed with error: WS_OPEN_ERROR_UNDERLYING_IO_OPEN_FAILED wss://southeastasia.tts.speech.microsoft.com/cognitiveservices/websocket/v1 X-ConnectionId: c4955d953f8e480c906061e6219eb8fd USP state: Sending. Received audio size: 0 bytes. Did you set the speech resource key and region values?
已确认SPEECH_KEY和SPEECH_REGION配置正确(控制台已打印验证)。
解决方案
针对平台初始化错误(Error 2153)
- 修复系统依赖缺失
Azure Speech SDK的azure-c-shared组件依赖特定系统库,Cloud Build环境可能存在依赖遗漏。修改Dockerfile,安装完整依赖并避免手动编译OpenSSL(手动编译易导致链接路径不兼容):
RUN apt-get update && apt-get install -y --no-install-recommends \ libssl-dev \ libasound2 \ ca-certificates \ && rm -rf /var/lib/apt/lists/*
- 指定库加载路径
在Dockerfile中添加环境变量,强制SDK使用系统标准库路径:
ENV LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu:$LD_LIBRARY_PATH
针对WebSocket连接错误(WS_OPEN_ERROR_UNDERLYING_IO_OPEN_FAILED)
- 强制使用REST协议
Cloud Run环境对WebSocket出站连接可能有限制,修改代码禁用WebSocket,改用REST API:
speech_config.set_property(speechsdk.PropertyId.SpeechServiceConnection_EnableWebSocket, "false")
- 适配Cloud Run无音频设备环境
Cloud Run容器没有默认音频输出设备,将音频输出改为文件:
audio_config = speechsdk.audio.AudioOutputConfig(filename="output.wav")
- 验证网络与证书
- 若使用VPC连接器,确保其允许访问微软TTS服务域名(
*.tts.speech.microsoft.com) - 在Dockerfile中添加证书更新步骤:
RUN update-ca-certificates -f
统一优化后的Dockerfile
FROM python:3.11-slim WORKDIR /app # 安装系统依赖并更新证书 RUN apt-get update && apt-get install -y --no-install-recommends \ build-essential \ libssl-dev \ libasound2 \ ca-certificates \ && update-ca-certificates -f \ && rm -rf /var/lib/apt/lists/* # 设置环境变量 ENV LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu:$LD_LIBRARY_PATH ENV SSL_CERT_DIR=/etc/ssl/certs # 安装Python依赖 RUN pip install --no-cache-dir azure-cognitiveservices-speech==1.30.0 COPY . /app CMD ["python3", "app.py"]
优化后的测试代码
import os import azure.cognitiveservices.speech as speechsdk speech_config = speechsdk.SpeechConfig(subscription=os.environ.get('SPEECH_KEY'), region=os.environ.get('SPEECH_REGION')) # 禁用WebSocket,改用REST协议 speech_config.set_property(speechsdk.PropertyId.SpeechServiceConnection_EnableWebSocket, "false") # 输出到文件(适配Cloud Run无音频设备环境) audio_config = speechsdk.audio.AudioOutputConfig(filename="output.wav") speech_config.speech_synthesis_voice_name='en-US-JennyNeural' speech_synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config, audio_config=audio_config) text = "Hello world!" speech_synthesis_result = speech_synthesizer.speak_text_async(text).get() if speech_synthesis_result.reason == speechsdk.ResultReason.SynthesizingAudioCompleted: print(f"Speech synthesized for text [{text}]") elif speech_synthesis_result.reason == speechsdk.ResultReason.Canceled: cancellation_details = speech_synthesis_result.cancellation_details print(f"Speech synthesis canceled: {cancellation_details.reason}") if cancellation_details.reason == speechsdk.CancellationReason.Error: if cancellation_details.error_details: print(f"Error details: {cancellation_details.error_details}")
内容的提问来源于stack exchange,提问作者Nori
相关产品推荐
相关产品推荐

