Python3调用Google Speech API启用自动标点报错,求解决方案
解决Google Speech API
enableAutomaticPunctuation 字段不存在的错误 这个问题我之前也碰到过,核心原因是客户端库版本不匹配或者字段命名不符合Python客户端的规范,下面给你一步步解决的方案:
1. 先更新Google Cloud Speech客户端库到最新版本
旧版本的google-cloud-speech可能没有包含自动标点相关的字段,执行以下命令升级:
pip install --upgrade google-cloud-speech
2. 使用v1p1beta1版本的API客户端
自动标点功能属于Speech-to-Text的beta特性,需要使用v1p1beta1版本的客户端,而不是默认的v1版本。在代码里导入对应版本的库:
from google.cloud import speech_v1p1beta1 as speech
3. 修正字段命名(下划线替代驼峰)
Python客户端库使用下划线分隔的命名规范,而不是API文档里的驼峰命名。把代码里的enableAutomaticPunctuation改成enable_automatic_punctuation。
完整的修正后代码片段
def transcribe_file_with_auto_punctuation(path): # 导入beta版本的Speech客户端 from google.cloud import speech_v1p1beta1 as speech client = speech.SpeechClient() # 读取音频文件 with open(path, "rb") as audio_file: content = audio_file.read() audio = speech.RecognitionAudio(content=content) config = speech.RecognitionConfig( encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16, sample_rate_hertz=16000, language_code="en-US", # 正确的字段名:下划线分隔 enable_automatic_punctuation=True, ) # 发送识别请求 response = client.recognize(config=config, audio=audio) # 输出转录结果 for result in response.results: print("带标点的转录文本: {}".format(result.alternatives[0].transcript))
额外注意事项
- 确保你的Google Cloud账号已经启用了Speech-to-Text API,并且配置了正确的服务账号密钥(通过环境变量
GOOGLE_APPLICATION_CREDENTIALS指定)。 - 如果使用的是其他语言代码(比如中文
zh-CN),确认该语言支持自动标点功能(大部分主流语言都支持)。
内容的提问来源于stack exchange,提问作者isuru gayashan
相关产品推荐
相关产品推荐

