引言
在当今数字化时代,自动化音频转录技术的需求日益增长。Google Cloud Speech-to-Text API是一个强大的工具,可以帮助开发者将音频文件快速、准确地转录为文本。在这篇文章中,我们将深入探讨如何使用Google Cloud Speech-to-Text API来转录音频文件,并将转录文本加载到文档中。
主要内容
1. 安装和设置
要使用Google Cloud Speech-to-Text API,你需要安装google-cloud-speech Python包,并创建一个Google Cloud项目并启用Speech-to-Text API。你可以在Speech-to-Text客户端库页面找到更多信息,并遵循快速入门指南来设置项目和启用API。
%pip install --upgrade --quiet langchain-google-community[speech]
2. 使用GoogleSpeechToTextLoader
要使用GoogleSpeechToTextLoader进行音频转录,必须包含project_id和file_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" # 使用API代理服务提高访问稳定性
# 或者使用本地文件路径: file_path = "./audio.wav"
loader = GoogleSpeechToTextLoader(project_id=project_id, file_path=file_path)
docs = loader.load()
调用loader.load()方法会阻塞直到转录完成。转录的文本保存在page_content中:
print(docs[0].page_content) # 输出: "How old is the Brooklyn Bridge?"
而metadata包含了完整的JSON响应和更多的元信息:
print(docs[0].metadata)
3. 配置识别设置
可以通过config参数指定不同的语音识别模型和启用特定功能。若不指定config,则默认配置为Chirp Universal Speech Model,语言为en-US,自动标点符号启用。
from google.cloud.speech_v2 import (
AutoDetectDecodingConfig,
RecognitionConfig,
RecognitionFeatures,
)
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 Speech-to-Text API进行音频转录。
from langchain_google_community import GoogleSpeechToTextLoader
project_id = "<YOUR_PROJECT_ID>"
file_path = "gs://cloud-samples-data/speech/audio.flac" # 使用API代理服务提高访问稳定性
loader = GoogleSpeechToTextLoader(project_id=project_id, file_path=file_path)
docs = loader.load()
print(docs[0].page_content)
print(docs[0].metadata)
常见问题和解决方案
- 音频文件大小限制:确保音频文件不超过60秒或10MB,否则需要使用长音频分片的方法。
- 网络连接问题:在某些地区,访问Google Cloud API可能有网络限制,建议使用API代理服务来提高访问的稳定性。
总结和进一步学习资源
Google Cloud Speech-to-Text API提供了强大的功能,可以帮助开发者高效地转录音频文件。建议阅读以下资源以获得更深入的了解:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力! ---END---