在Google Colab中使用Google语音转文本遇AttributeError错误
解决Google Colab中Google语音转文本服务的
universe_domain属性错误 执行语音转文本代码时触发如下错误:
if credentials: --> 505 credentials_universe = credentials.universe_domain 506 if client_universe != credentials_universe: 507 default_universe = SpeechClient._DEFAULT_UNIVERSE AttributeError: 'Credentials' object has no attribute 'universe_domain'
问题原因
该错误源于google-cloud-speech客户端库与认证凭据的版本不兼容:新版客户端库要求凭据对象包含universe_domain属性,但Colab默认加载的凭据或依赖库版本不匹配,导致属性缺失。
解决方案
1. 统一升级所有相关依赖库
在Colab单元格中执行以下命令,确保所有Google云相关库版本兼容:
!pip install --upgrade google-cloud-speech google-auth google-auth-httplib2 google-auth-oauthlib google-api-python-client
2. 显式传递凭据初始化客户端
若升级后问题仍存在,手动获取凭据并传入SpeechClient,避免自动加载的版本冲突:
修改语音识别函数:
from google.cloud import speech from google.auth import default def speech_to_text( config: speech.RecognitionConfig, audio: speech.RecognitionAudio, ) -> speech.RecognizeResponse: # 显式获取当前认证凭据 credentials, project_id = default() # 传入凭据初始化客户端 client = speech.SpeechClient(credentials=credentials) # 同步执行语音识别请求 response = client.recognize(config=config, audio=audio) return response
3. 重启Colab运行时
完成库升级后,点击菜单栏「运行时」→「重启运行时」,确保新安装的库生效。
额外处理:音频格式兼容
如果录制的音频是WebM格式(ipywebrtc默认输出格式),需转换为客户端支持的WAV/FLAC格式:
!pip install pydub ffmpeg-python import io from pydub import AudioSegment # 转换WebM到WAV audio_data = io.BytesIO(recorded_audio) audio_segment = AudioSegment.from_file(audio_data, format="webm") wav_buffer = io.BytesIO() audio_segment.export(wav_buffer, format="wav") wav_buffer.seek(0) # 创建识别用的音频对象 audio = speech.RecognitionAudio(content=wav_buffer.read())
内容的提问来源于stack exchange,提问作者Antonin
相关产品推荐
相关产品推荐

