Skip to main content
Open In ColabOpen on GitHub

Google 语音转文字音频转录稿

The SpeechToTextLoader 允许使用 Google Cloud Speech-to-Text API 转录音频文件,并将转录的文本加载到文档中。

要使用它,您应该已经安装了google-cloud-speech python 包,并且有一个启用了语音转文本 API的 Google 云项目。

安装与设置

首先,你需要安装LangChain Python 包。

您可以在语音转文本客户端库页面上找到更多信息。

按照Google Cloud 文档中的快速入门指南 创建一个项目并启用API。

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

示例

The SpeechToTextLoader 必须包括 project_idfile_path 参数。音频文件可以指定为 Google 云存储 URI (gs://...) 或本地文件路径。

仅支持同步请求,加载器对每个音频文件有60秒或10MB的限制

from langchain_google_community import SpeechToTextLoader

project_id = "<PROJECT_ID>"
file_path = "gs://cloud-samples-data/speech/audio.flac"
# or a local file path: file_path = "./audio.wav"

loader = SpeechToTextLoader(project_id=project_id, file_path=file_path)

docs = loader.load()

注释:调用loader.load()会阻塞直到转录完成。

The transcribed text is available in the page_content:

docs[0].page_content
"How old is the Brooklyn Bridge?"

The metadata 包含完整的 JSON 响应并带有更多元数据信息:

docs[0].metadata
{
'language_code': 'en-US',
'result_end_offset': datetime.timedelta(seconds=1)
}

Recognition Config

您可以指定config参数以使用不同的语音识别模型并启用特定功能。

参阅语音识别文档RecognizeRequest API 参考,了解如何设置自定义配置。

如果没有指定config,将会自动选择以下选项:

from google.cloud.speech_v2 import (
AutoDetectDecodingConfig,
RecognitionConfig,
RecognitionFeatures,
)
from langchain_google_community import SpeechToTextLoader

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 = SpeechToTextLoader(
project_id=project_id,
location=location,
recognizer_id=recognizer_id,
file_path=file_path,
config=config,
)