以编程方式使用文档

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

要使用它,您需要安装 google-cloud-speech python 包,并拥有一个启用了 语音转文本 API.

安装与设置

首先,您需要安装 google-cloud-speech python 包。

您可以在 语音转文本客户端库 page.

按照 快速入门指南 中的指引创建项目并启用该 API。

pip install -qU langchain-google-community[speech]

示例

SpeechToTextLoader 必须包含 project_idfile_path 参数。音频文件可以指定为 Google Cloud Storage URI (gs://...) 或本地文件路径。

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

from langchain_google_community import SpeechToTextLoader

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() 会阻塞直到转录完成。

转录文本可在 page_content:

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

中获取。该 metadata 包含完整的 JSON 响应及更多元信息:

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

识别配置

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

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

如果您未指定 config,则将自动选择以下选项:

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

project_id = ""
location = "global"
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,
)