Haystack 音频 API 详解:LocalWhisperTranscriber 与 RemoteWhisperTranscriber 语音转文本组件
2026/9/13 12:21:43 网站建设 项目流程

Haystack 音频 API 详解:LocalWhisperTranscriber 与 RemoteWhisperTranscriber 语音转文本组件

【免费下载链接】haystackOpen-source AI orchestration framework for building context-engineered, production-ready LLM applications. Design modular pipelines and agent workflows with explicit control over retrieval, routing, memory, and generation. Built for scalable agents, RAG, multimodal applications, semantic search, and conversational systems.项目地址: https://gitcode.com/GitHub_Trending/ha/haystack

本篇基于 Haystack 2.20 版音频 API 参考文档,系统讲解whisper_localwhisper_remote两个模块中的两个语音转文本(Speech-to-Text)组件:本地推理的LocalWhisperTranscriber与调用 OpenAI Whisper API 的RemoteWhisperTranscriber。读完后你可以掌握两个组件的完整初始化参数、run输入输出约定、序列化/反序列化方式,并结合当前仓库的迁移说明与发布记录,明确这些组件在 Haystack 3.x 中的现状与迁移路径。

音频组件总览

Haystack 的音频处理能力由haystack.components.audio包提供,按实现方式分为两个子模块:

模块组件实现方式适用场景
whisper_localLocalWhisperTranscriber在本地机器上运行 OpenAI 的 Whisper 模型数据不出本地、离线环境、大批量音频转写
whisper_remoteRemoteWhisperTranscriber调用 OpenAI 的 Whisper API无需本地算力、快速集成、按量付费

两个组件对外接口高度统一:run方法都接收sources(文件路径或ByteStream的二进制流列表),都声明相同的输出类型documents: list[Document],并且都实现了to_dict/from_dict序列化协议,因此可以在管道中互换使用、以统一的 YAML 格式落盘。

LocalWhisperTranscriber:本地 Whisper 转写组件

功能定位与用法

LocalWhisperTranscriber在本地机器上加载 OpenAI 的 Whisper 模型完成音频转写。支持的音频格式、语言列表等参数细节,以 Whisper 官方文档和官方仓库的说明为准。基本用法如下:

from haystack.components.audio import LocalWhisperTranscriber whisper = LocalWhisperTranscriber(model="small") whisper.warm_up() transcription = whisper.run(sources=["path/to/audio/file"])

初始化参数:__init__

def __init__(model: WhisperLocalModel = "large", device: Optional[ComponentDevice] = None, whisper_params: Optional[dict[str, Any]] = None)
参数类型 / 默认值说明
modelWhisperLocalModel,默认"large"要使用的 Whisper 模型名称,可取"tiny""base""small""medium""large"(默认)。各模型的规模、语言支持与精度差异,参考 Whisper 官方文档中的"可用模型与语言"章节
deviceOptional[ComponentDevice],默认None模型加载的设备;为None时自动选择默认设备
whisper_paramsOptional[dict[str, Any]],默认None透传给底层 Whisper 推理的附加参数,用于覆盖转写行为

从当前仓库的发布记录可以看到,device参数经历过一次类型升级:早期版本接受"cuda:0"这类字符串,之后改为采用框架无关的设备管理方案。迁移方式为:

from haystack.utils.device import ComponentDevice, Device from haystack.components.audio import LocalWhisperTranscriber device = ComponentDevice.from_single(Device.gpu(id=0)) # 或 # device = ComponentDevice.from_str("cuda:0") transcriber = LocalWhisperTranscriber(device=device)

该变更对应发布说明 whisper-loc-new-devices-0665a24cd92ee4b6.yaml,意味着组件的设备选择逻辑与其他 Haystack 组件保持一致,可直接复用统一的ComponentDevice配置。

warm_up:预加载模型

def warm_up() -> None

在管道启动时把模型加载进内存。由于本地 Whisper 模型(尤其是large)加载耗时较长,推荐在构建管道后显式调用warm_up(),避免首次run时产生不可预期的延迟。

run:转写入口

@component.output_types(documents=list[Document]) def run(sources: list[Union[str, Path, ByteStream]], whisper_params: Optional[dict[str, Any]] = None)

参数说明:

  • sources:待转写的音频文件路径(strPath)或二进制流(ByteStream)列表;
  • whisper_params:本次运行时的 Whisper 推理参数,支持音频格式、语言等可选项。

返回值是一个字典,唯一键为documents:列表中每个Document对应一个输入音频文件,content字段是转写文本,meta中保存 Whisper 模型返回的元数据,包括对齐(alignment)数据和所用音频文件的路径。

值得注意的是,输入参数从早期的audio_files更名为sources以统一 Haystack 各组件的输入插槽命名,同时新增了ByteStream支持——这一变更见 change-localwhispertranscriber-run-3b0a818060867720.yaml。如果你的管道中仍使用旧参数名,需要把audio_files改为sources

transcribe:底层转写方法

def transcribe(sources: list[Union[str, Path, ByteStream]], **kwargs) -> list[Document]

这是组件内部实际执行转写的方法,接收音频文件列表,返回Document列表(每个输入文件一个)。run本质上是对transcribe的管道化封装,声明了输出类型以便在Pipeline中自动连线。

依赖与安装注意事项

从仓库发布记录 simplify-whisper-installation-1e347e2527cbf913.yaml 可以看到,早期openai-whispertiktoken依赖与 Haystack 存在版本冲突,官方通过升级openai-whisper20231106版本并重新引入 audio 安装可选依赖(extra)来解决。因此使用本地组件时,建议显式安装不低于该版本的openai-whisper,并确保系统具备ffmpeg(Whisper 的音频解码前置条件)。

RemoteWhisperTranscriber:OpenAI Whisper API 转写组件

功能定位与用法

RemoteWhisperTranscriber通过 OpenAI 的 Whisper API 完成转写,需要配置 OpenAI API Key(认证方式见 OpenAI 官方文档)。基本用法如下:

from haystack.components.audio import RemoteWhisperTranscriber whisper = RemoteWhisperTranscriber(api_key=Secret.from_token("<your-api-key>"), model="tiny") transcription = whisper.run(sources=["path/to/audio/file"])

初始化参数:__init__

def __init__(api_key: Secret = Secret.from_env_var("OPENAI_API_KEY"), model: str = "whisper-1", api_base_url: Optional[str] = None, organization: Optional[str] = None, http_client_kwargs: Optional[dict[str, Any]] = None, **kwargs)

参数说明:

参数默认值说明
api_keySecret.from_env_var("OPENAI_API_KEY")OpenAI API Key。默认从环境变量OPENAI_API_KEY读取,也可在初始化时通过Secret显式传入
model"whisper-1"模型名称,目前仅接受whisper-1
api_base_urlNone可选的 API 基础地址,用于指向兼容 OpenAI 音频接口的自托管/代理端点
organizationNoneOpenAI 组织 ID,多组织账号建议设置,用法见 OpenAI 组织配置文档
http_client_kwargsNone配置底层httpx.Client/httpx.AsyncClient的参数字典,可在此设置超时、代理、TLS 等传输层选项
**kwargs其余可选参数直接透传给 OpenAI 端点

**kwargs透传参数中常用的有:

  • language:输入音频的语言,以 ISO-639-1 格式提供(如zhen)。预先声明语言可提升转写准确率并降低延迟;
  • prompt:引导模型风格或衔接上一段音频的可选文本,需与音频语言一致;
  • response_format:转写输出格式,该组件仅支持json
  • temperature:采样温度,取值 0~1。较高值(如 0.8)输出更随机,较低值(如 0.2)更聚焦、更确定;设为 0 时,模型会基于 log probability 自动逐步升高温度直到触及阈值。

从源码结构看,RemoteWhisperTranscriber的模型参数名也经历过一次统一:早期的model_name/model_name_or_path被重命名为model,见 rename-model-param--transcribers-71dbe7cfb86950e0.yaml。此外,该组件底层已迁移到 OpenAI SDK 实现,见 migrate-remote-whisper-transcriber-to-openai-sdk-980ae6f54ddfd7df.yaml。

run:转写入口

@component.output_types(documents=list[Document]) def run(sources: list[Union[str, Path, ByteStream]])
  • sources:文件路径或ByteStream对象列表,包含待转写的音频文件。

返回值同样是包含documents键的字典:每个输入文件对应一个Documentcontent为转写文本。

与本地组件相同,远端组件的输入类型也从早期的list[ByteStream]扩展为list[Union[str, Path, ByteStream]](见 remotetranscriber-input-type-aae9a255435a3507.yaml),这样它可以直接连接FileTypeRouter等按文件类型分流的路由组件,也支持先落盘再传路径的管道写法,接入方式更灵活。

序列化与反序列化:to_dict / from_dict

两个组件都实现了 Haystack 标准的组件序列化协议,这是它们能作为 YAML 管道的一部分被保存和加载的前提:

# LocalWhisperTranscriber / RemoteWhisperTranscriber 通用 def to_dict() -> dict[str, Any] # 序列化为字典 @classmethod def from_dict(cls, data: dict[str, Any]) # 从字典反序列化为组件实例
  • to_dict():把组件当前配置(模型名、设备、API 端点、透传参数等)序列化为字典;远端组件中的Secret按 Haystack 的密钥约定序列化,避免明文 API Key 泄漏到配置文件;
  • from_dict(data):类方法,接收to_dict()产出的字典并重建组件。

Pipeline层面,这两个方法由Pipeline.dumps()/Pipeline.loads()统一调度,你通常不需要手动调用;但当需要把单个组件配置嵌入外部系统(如自定义配置中心)时可以直接使用。

选型建议:本地还是远端

基于上述 API 设计,可以归纳出两者的选型要点:

  • 数据合规 / 离线 / 大批量:选LocalWhisperTranscriber。音频不出本地,且可通过model参数在tinylarge之间权衡精度与吞吐,用device指定 GPU(如ComponentDevice.from_single(Device.gpu(id=0)))加速推理;代价是需要本地算力、openai-whisper依赖和ffmpeg
  • 免运维 / 低延迟起步 / 峰值弹性:选RemoteWhisperTranscriber。无需本地模型,http_client_kwargs支持传输层定制,languagetemperatureprompt等参数直接透传 API;代价是需要 API Key 与网络访问,且受 API 计费约束。
  • 两者输出契约一致(documents: list[Document],每个音频一个 Document),因此可以在不改动下游组件(如文本预处理、写入 Document Store)的情况下互换,便于先以远端 API 验证流程、再切换本地模型降本。

重要变更:组件已迁出 Haystack 核心包

阅读本参考文档时需要注意其版本背景:该 API 文档对应 Haystack 2.20。在当前的 Haystack 3.x 中,LocalWhisperTranscriberRemoteWhisperTranscriber已从核心包移除,迁移到独立的whisper-haystack集成包中,相关发布说明见 deprecate-whisper-components-95822a86cd87fdc0.yaml 与 remove-whisper-components-30108535da20e41f.yaml。

当前仓库根目录的 MIGRATION.md 中的迁移表明确给出了新旧导入路径对照:

旧导入(haystack-ai < 3.0.0)新包新导入
from haystack.components.audio import LocalWhisperTranscriberwhisper-haystackfrom haystack_integrations.components.audio.whisper import LocalWhisperTranscriber
from haystack.components.audio import RemoteWhisperTranscriberwhisper-haystackfrom haystack_integrations.components.audio.whisper import RemoteWhisperTranscriber

实际迁移步骤为:安装新包pip install whisper-haystack,然后更新导入路径;本地组件还需要额外安装openai-whisper>=20231106ffmpeg。迁移的官方理由是把这类组件拆到独立包中,以便隔离测试、独立于 Haystack 主发布周期地修复问题,同时让核心包的开发和 CI 更轻量。

小结

Haystack 2.20 音频 API 的核心内容可归纳为三点:其一,LocalWhisperTranscriberRemoteWhisperTranscriber提供了本地推理与云端 API 两条音频转写路径,参数与输入输出契约(sources进、documents出)高度对称,便于在管道中互换;其二,两个组件均支持str/Path/ByteStream混合输入和标准to_dict/from_dict序列化,可直接接入管道并持久化为 YAML;其三,在 Haystack 3.x 中这两个组件已迁移至whisper-haystack集成包,升级项目时应按 MIGRATION.md 的对照表更新导入路径并补齐openai-whisper依赖。

【免费下载链接】haystackOpen-source AI orchestration framework for building context-engineered, production-ready LLM applications. Design modular pipelines and agent workflows with explicit control over retrieval, routing, memory, and generation. Built for scalable agents, RAG, multimodal applications, semantic search, and conversational systems.项目地址: https://gitcode.com/GitHub_Trending/ha/haystack

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询