在 Haystack 中使用 Whisper 转录音频: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 开源 AI 编排框架中的 Whisper 音频转写集成,覆盖本地推理组件LocalWhisperTranscriber与云端 API 组件RemoteWhisperTranscriber的安装、初始化参数、run调用、序列化与管线集成方式。读完本文,你将掌握如何把任意音频文件转写为 HaystackDocument,并将其作为索引管线的第一步,构建"音频 → 文本 → RAG"的完整链路。
背景:Whisper 集成在 Haystack 中的定位
Whisper 是 OpenAI 开源的通用语音识别模型,Haystack 通过两个音频组件将其接入组件化管线体系:
LocalWhisperTranscriber:在本机加载 Whisper 模型完成转写,音频数据不出本机;RemoteWhisperTranscriber:调用 OpenAI 兼容的 Whisper API(如 OpenAI、Groq 等)完成转写。
在版本 2.18 中,这两个组件的完整 API 参考记录于 whisper.md 与 audio_api.md,对应的用户指南位于 localwhispertranscriber.mdx 和 remotewhispertranscriber.mdx。
从 MIGRATION.md 的迁移表可以看到,这两个组件后续被迁移至独立的whisper-haystack集成包,导入路径从haystack.components.audio变为haystack_integrations.components.audio.whisper。迁移说明记录在 deprecate-whisper-components-95822a86cd87fdc0.yaml:
LocalWhisperTranscriber和RemoteWhisperTranscriber已被弃用,将在 Haystack 3.0 中移除。它们将迁移至whisper-haystack包。要继续使用,请用pip install whisper-haystack安装并更新导入语句。
因此,本指南中的示例同时给出两种导入路径:Haystack 2.18 内置组件使用haystack.components.audio,迁移后的集成包使用haystack_integrations.components.audio.whisper,二者 API 形态保持一致。
LocalWhisperTranscriber:本地 Whisper 转写
组件概览
LocalWhisperTranscriber在本地机器上使用 OpenAI 的 Whisper 模型转写音频文件。它适用于对数据隐私敏感、无网络依赖或需要离线批量处理的场景——所有转写都在执行机器上完成,音频永远不会发送给第三方服务商。
在管线中的典型位置与输入输出约定(见 localwhispertranscriber.mdx):
| 项目 | 说明 |
|---|---|
| 管线中最常见位置 | 索引管线的第一个组件 |
| 必需的 run 变量 | sources:要转写的路径或二进制流列表 |
| 输出变量 | documents:Document 列表 |
安装依赖
本地转写依赖 torch 与 Whisper 本体,按以下命令安装:
pip install 'transformers[torch]' pip install -U openai-whisper若使用迁移后的whisper-haystack包,则改为:
pip install whisper-haystack pip install -U openai-whisper初始化参数
def __init__( model: WhisperLocalModel = "large", device: ComponentDevice | None = None, whisper_params: dict[str, Any] | None = None, ) -> None- model(
WhisperLocalModel,默认"large"):要使用的模型名,可选"tiny"、"base"、"small"、"medium"、"large"。模型规模越大,识别准确率越高、速度越慢、显存占用越大,请根据机器算力权衡选择。 - device(
ComponentDevice | None,默认None):模型加载设备。为None时自动选择默认设备。 - whisper_params(
dict[str, Any] | None):透传给 Whisper 转写调用的附加参数,例如语言、时间戳等。
关于设备参数,发布说明 whisper-loc-new-devices-0665a24cd92ee4b6.yaml 记录了 Haystack 设备管理的演进:早期版本直接传字符串device="cuda:0",新版本改为框架无关的ComponentDevice:
# 旧用法 from haystack.components.audio import LocalWhisperTranscriber transcriber = LocalWhisperTranscriber(device="cuda:0") # 新用法 from haystack.utils.device import ComponentDevice, Device device = ComponentDevice.from_single(Device.gpu(id=0)) # 或 # device = ComponentDevice.from_str("cuda:0") transcriber = LocalWhisperTranscriber(device=device)方法清单
| 方法 | 签名 | 说明 |
|---|---|---|
warm_up() | warm_up() -> None | 将模型加载到内存中,首次调用前必须先执行 |
run(sources, whisper_params) | run(sources: list[str \| Path \| ByteStream], whisper_params: dict[str, Any] \| None = None) -> dict[str, Any] | 转写一组音频文件为 Document 列表 |
to_dict() | to_dict() -> dict[str, Any] | 序列化组件为字典 |
from_dict(data) | from_dict(data: dict[str, Any]) -> LocalWhisperTranscriber | 从字典反序列化组件 |
其中run的返回字典包含键documents:每个音频文件对应一个Document,Document.content为转写文本,Document.metadata携带 Whisper 模型返回的额外信息(如对齐数据 alignment data、转写所用的音频文件路径)。
值得注意,组件底层还有一个transcribe(sources, **kwargs) -> list[Document]方法,负责把输入文件逐一转为Document(见 audio_api.md),run是对它的组件化封装。
独立使用
以下示例先下载一段肯尼迪演讲 MP3,再用tiny模型在本机转写(示例源自 localwhispertranscriber.mdx):
import requests from haystack.components.audio import LocalWhisperTranscriber response = requests.get( "https://ia903102.us.archive.org/19/items/100-Best--Speeches/EK_19690725_64kb.mp3", ) with open("kennedy_speech.mp3", "wb") as file: file.write(response.content) transcriber = LocalWhisperTranscriber(model="tiny") transcriber.warm_up() transcription = transcriber.run(sources=["./kennedy_speech.mp3"]) print(transcription["documents"][0].content)关键步骤有三:构造组件 →warm_up()加载模型 →run(sources=[...])转写。使用迁移包时,把导入语句换成from haystack_integrations.components.audio.whisper import LocalWhisperTranscriber即可,其余代码不变(迁移后不再强制要求显式warm_up(),但显式调用依然安全)。
接入管线
LocalWhisperTranscriber最常见的定位是索引管线的第一个组件。下面的管线用LinkContentFetcher抓取音频 URL,再用转写器转成文本(示例源自 localwhispertranscriber.mdx):
from haystack.components.audio import LocalWhisperTranscriber from haystack.components.fetchers import LinkContentFetcher from haystack import Pipeline pipe = Pipeline() pipe.add_component("fetcher", LinkContentFetcher()) pipe.add_component("transcriber", LocalWhisperTranscriber(model="tiny")) pipe.connect("fetcher", "transcriber") result = pipe.run( data={ "fetcher": { "urls": [ "https://ia903102.us.archive.org/19/items/100-Best--Speeches/EK_19690725_64kb.mp3", ], }, }, ) print(result["transcriber"]["documents"][0].content)fetcher输出的二进制流与transcriber的sources输入天然衔接,转写结果documents可直接继续连接到后续的文档切分、向量化组件,形成完整的"音频抓取 → 转写 → 索引"管线。
RemoteWhisperTranscriber:API 转写
组件概览
RemoteWhisperTranscriber调用 OpenAI 的 Whisper API 完成转写,本机无需安装模型与 torch,只依赖网络请求。该组件兼容任何 OpenAI 兼容的客户端,不限于 OpenAI 官方服务——例如 Groq 就提供了可直接替换的 Whisper 兼容端点。它适合对延迟敏感、算力有限或希望按量付费的场景。
在管线中的约定(见 remotewhispertranscriber.mdx):
| 项目 | 说明 |
|---|---|
| 管线中最常见位置 | 索引管线的第一个组件 |
| 必需的 init 变量 | api_key:OpenAI API 密钥,可通过环境变量OPENAI_API_KEY提供 |
| 必需的 run 变量 | sources:要转写的路径或二进制流列表 |
| 输出变量 | documents:Document 列表 |
安装与密钥配置
安装迁移后的集成包:
pip install whisper-haystackRemoteWhisperTranscriber需要 OpenAI API 密钥(参考 whisper.md 中的 API 文档说明),可通过两种方式设置:
- 通过
api_key初始化参数传入,密钥由 Haystack 的 Secret API 机制解析; - 设置环境变量
OPENAI_API_KEY,组件默认从该变量读取。
from haystack_integrations.components.audio.whisper import RemoteWhisperTranscriber transcriber = RemoteWhisperTranscriber()初始化参数
def __init__( api_key: Secret = Secret.from_env_var("OPENAI_API_KEY"), model: str = "whisper-1", api_base_url: str | None = None, organization: str | None = None, http_client_kwargs: dict[str, Any] | None = None, **kwargs: Any, ) -> None各参数说明如下:
- api_key(
Secret):OpenAI API 密钥。默认从环境变量OPENAI_API_KEY解析,也可以在初始化时显式传入。 - model(
str,默认"whisper-1"):使用的模型名,目前仅接受whisper-1。 - api_base_url(
str | None):API 基地址,默认"https://api.openai.com/v1"。如果使用 OpenAI 之外的其他 Whisper 服务商(如 Groq),按该服务商文档配置此参数。 - organization(
str | None):OpenAI 组织 ID,适用于多组织账号场景。 - http_client_kwargs(
dict[str, Any] | None):用于配置自定义httpx.Client或httpx.AsyncClient的关键字参数字典,可自定义超时、代理、重试等行为。 - kwargs:其他直接透传给 OpenAI 端点的模型可选参数,主要包括:
language:输入音频的语言,使用 ISO-639-1 格式(如"zh"、"en"),提前指定可提升转写准确率并降低延迟;prompt:可选的引导文本,用于指定输出风格或衔接上一段音频,提示语言应与音频语言一致;response_format:转写输出格式,本组件仅支持json;temperature:采样温度,取值 0~1。较高值(如 0.8)使输出更随机,较低值(如 0.2)更聚焦和确定;设为 0 时模型会利用对数概率自动升温直到命中特定阈值。
版本 2.18 的RemoteWhisperTranscriber已基于 OpenAI SDK 实现(见 migrate-remote-whisper-transcriber-to-openai-sdk-980ae6f54ddfd7df.yaml),并支持通过http_client_kwargs定制底层 HTTP 客户端。
方法清单
| 方法 | 签名 | 说明 |
|---|---|---|
run(sources) | run(sources: list[str \| Path \| ByteStream]) -> dict[str, Any] | 同步转写音频文件列表为 Document 列表 |
run_async(sources) | run_async(sources: list[str \| Path \| ByteStream]) -> dict[str, Any] | run的异步版本,可在异步代码中用await调用,参数与返回值一致 |
to_dict() | to_dict() -> dict[str, Any] | 序列化组件为字典 |
from_dict(data) | from_dict(data: dict[str, Any]) -> RemoteWhisperTranscriber | 从字典反序列化组件 |
返回字典的documents键中,每个输入文件对应一个Document,其content为转写文本。RemoteWhisperTranscriber无需warm_up()——模型在服务端,本地没有加载过程。
独立使用
import requests from haystack.components.audio import RemoteWhisperTranscriber response = requests.get( "https://ia903102.us.archive.org/19/items/100-Best--Speeches/EK_19690725_64kb.mp3", ) with open("kennedy_speech.mp3", "wb") as file: file.write(response.content) transcriber = RemoteWhisperTranscriber() transcription = transcriber.run(sources=["./kennedy_speech.mp3"]) print(transcription["documents"][0].content)也可以在初始化时用Secret.from_token直接传入密钥:
from haystack.components.audio import RemoteWhisperTranscriber from haystack.utils import Secret whisper = RemoteWhisperTranscriber(api_key=Secret.from_token("<your-api-key>"), model="tiny") transcription = whisper.run(sources=["path/to/audio/file"])接入管线
与本地版本对称,远程版同样可与LinkContentFetcher串联(示例源自 remotewhispertranscriber.mdx):
from haystack.components.audio import RemoteWhisperTranscriber from haystack.components.fetchers import LinkContentFetcher from haystack import Pipeline pipe = Pipeline() pipe.add_component("fetcher", LinkContentFetcher()) pipe.add_component("transcriber", RemoteWhisperTranscriber()) pipe.connect("fetcher", "transcriber") result = pipe.run( data={ "fetcher": { "urls": [ "https://ia903102.us.archive.org/19/items/100-Best--Speeches/EK_19690725_64kb.mp3", ], }, }, ) print(result["transcriber"]["documents"][0].content)若换成 Groq 等兼容服务商,只需按厂商文档设置api_base_url与api_key,组件代码无需其他改动。
本地与远程:如何选择
| 维度 | LocalWhisperTranscriber | RemoteWhisperTranscriber |
|---|---|---|
| 运行位置 | 本机(CPU/GPU) | OpenAI 兼容 API 服务端 |
| 音频数据流向 | 不出本机 | 上传至服务端 |
| 前置依赖 | torch、openai-whisper、模型权重 | OPENAI_API_KEY(或等效密钥) |
是否需要warm_up() | 需要(首次运行前加载模型) | 不需要 |
| 适用场景 | 隐私敏感、离线批处理、无 API 预算 | 无本地算力、要求低延迟、按量付费 |
| 可选模型 | tiny / base / small / medium / large | whisper-1(OpenAI 托管) |
选择建议:数据不出域、算力充足选本地;追求省心与弹性、能接受数据上云选远程。两者输出结构一致(documents列表),因此可以在索引管线中无缝互换。
序列化与版本迁移
序列化支持
两个组件都实现了标准的 Haystack 组件序列化协议:
to_dict()将组件及其初始化参数序列化为字典,便于持久化到 YAML/JSON 或存入管线描述文件;from_dict(data)从字典还原组件实例,保证管线可完整导出与恢复。
这与其他 Haystack 组件一致,是组件可组合、可复用、可版本化管理的基础。
从 Haystack 2.18 到 whisper-haystack 的迁移
两个组件在后续版本被移入whisper-haystack独立包,迁移步骤(见 MIGRATION.md 与 deprecate-whisper-components-95822a86cd87fdc0.yaml):
- 安装新包:
pip install whisper-haystack; - 更新导入语句:
| 迁移前(Haystack 2.18) | 迁移后(whisper-haystack) |
|---|---|
from haystack.components.audio import LocalWhisperTranscriber | from haystack_integrations.components.audio.whisper import LocalWhisperTranscriber |
from haystack.components.audio import RemoteWhisperTranscriber | from haystack_integrations.components.audio.whisper import RemoteWhisperTranscriber |
迁移后组件继续以haystack_integrations命名空间提供,初始化与run调用方式保持一致。
进一步探索
- 音频组件总览:audio.mdx
- 用户指南:localwhispertranscriber.mdx、remotewhispertranscriber.mdx
- API 参考:integrations-api/whisper.md、haystack-api/audio_api.md
- 相关发布说明:deprecate-whisper-components-95822a86cd87fdc0.yaml、whisper-loc-new-devices-0665a24cd92ee4b6.yaml
- 组件迁移对照表:MIGRATION.md
基于这两个转写组件,可以进一步组合文档切分器、Embedder 与 Document Store,搭建"播客 / 会议录音 → 转写文本 → 向量索引 → 多语言 RAG"的完整生产级应用。
【免费下载链接】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),仅供参考