Python调用Google Speech API返回全部历史单词而非当前转录单词的问题
Google Speech-to-Text API中
words返回历史单词的问题解析 这不是API Bug,是Google Speech-to-Text流式识别的设计行为:
- 当启用单词级时间戳或说话人分离功能时,
result.alternatives[0].words会累积存储从会话开始到当前时刻的所有识别单词,而非仅当前片段的内容。 - 而
transcript字段在流式返回的非最终结果中,会呈现当前增量片段的文本;当result.is_final=True时,transcript是当前完整话语的文本,但words依然是全局累积的。
过滤当前片段单词的方法
可以通过两种方式获取当前片段的单词:
方法1:基于历史计数增量过滤
通过记录上一次处理的单词总数,每次只提取新增的单词部分,适合处理is_final标记的完整话语:
# 在类初始化时新增变量,记录上一次处理的单词数 self.last_processed_word_count = 0 if not response.results: continue result = response.results[0] if not result.alternatives: continue transcript = result.alternatives[0].transcript confidence = result.alternatives[0].confidence words = result.alternatives[0].words if result.is_final: print("*******************") sensory_log.info(f"Final STT output: {transcript}") print(f"Confidence: {confidence:.2f}") self.process_input(transcript) # 提取当前片段的单词:仅本次新增的部分 current_segment_words = words[self.last_processed_word_count:] self.last_processed_word_count = len(words) if current_segment_words: print(current_segment_words) # 统计当前片段的说话人 speaker_ids = [] for word in current_segment_words: print(f"Word: {word.word} (speaker_tag: {word.speaker_tag})") if word.speaker_tag not in speaker_ids: speaker_ids.append(word.speaker_tag) print(f"Detected {len(speaker_ids)} speakers")
方法2:基于时间戳过滤
如果需要在非最终结果中获取当前片段的单词,可以对比当前结果的时间范围与单词的时间戳(需提前启用时间戳功能):
if not response.results: continue result = response.results[0] if not result.alternatives: continue transcript = result.alternatives[0].transcript confidence = result.alternatives[0].confidence words = result.alternatives[0].words # 获取当前结果的时间范围 current_start = result.start_time.total_seconds() current_end = result.end_time.total_seconds() # 过滤出属于当前片段的单词 current_segment_words = [ word for word in words if word.start_time.total_seconds() >= current_start and word.end_time.total_seconds() <= current_end ] # 后续处理逻辑...
注意事项
- 必须在初始化SpeechClient时,明确启用单词级时间戳和说话人分离配置,否则
words字段不会返回数据。 - 流式识别的非
is_final结果是临时增量,建议优先在is_final=True时处理完整话语的说话人信息,避免重复计算。
内容的提问来源于stack exchange,提问作者JackKalish
相关产品推荐
相关产品推荐

