将Typhoon Whisper Turbo集成到你的应用:API封装、微服务与Web端3种泰语ASR实战方案

原创2026-11-10 18:10:082,250 阅读

将Typhoon Whisper Turbo集成到你的应用:API封装、微服务与Web端3种泰语ASR实战方案

Typhoon Whisper Turbo 是一款基于 OpenAI Whisper Large v3 Turbo 架构微调的**泰语语音识别(Thai ASR)**模型,专为离线转写设计,兼具高精度与低延迟。本文用 3 种由浅入深的集成方案——API 封装、FastAPI 微服务、Web 端接入,带你把它快速落地到真实应用中。

一、为什么选 Typhoon Whisper Turbo?

它是 SCB 10X 团队基于 Whisper Large v3 Turbo 在约 11,000 小时泰语音频上微调的专用模型(Gigaspeech2、CommonVoice 及内部公开媒体数据),核心优势一眼可见:

特性 说明
🏗️ 架构 Whisper Large v3 Turbo:4 层解码器(标准 Large v3 为 32 层)
🚀 速度 推理吞吐量显著高于标准 Whisper,显存占用更低
🎙️ 语言 专注泰语(th),数字、重复标记等本地化细节统一归一化
📄 许可 MIT License,可自由用于商业与开源项目
⏱️ 定位 离线转写(offline transcription),支持时间戳输出

💡 模型细节可在 config.json 中验证:"decoder_layers": 4、"d_model": 1280、"torch_dtype": "bfloat16"。

二、环境准备:一键安装与模型获取

只需三个核心依赖:

pip install transformers torch accelerate

模型权重可克隆仓库到本地使用(离线部署推荐):

git clone https://gitcode.com/hf_mirrors/typhoon-ai/typhoon-whisper-turbo

仓库内关键文件速览,方便你按需取用:

文件 作用
model.safetensors 模型权重(safetensors 格式)
config.json 模型结构与超参数配置
preprocessor_config.json 音频特征提取配置:16kHz 采样率、128 mel bins、30 秒分块
generation_config.json 生成参数与多语言 token 映射
tokenizer.json / vocab.json / merges.txt 分词器词表与合并规则
special_tokens_map.json / added_tokens.json 特殊 token 与时间戳 token 定义
README.md 官方模型卡片与示例代码

📌 音频预处理按 preprocessor_config.json 执行:"sampling_rate": 16000、"chunk_length": 30。也就是说,输入建议统一为 16kHz 单声道,超过 30 秒的音频会被自动切块。

三、方案一:API 封装——最小化本地转写脚本

适合脚本、数据标注流水线等"拿到音频文件就出文本"的场景。用 transformers 的 pipeline 三行核心代码即可完成转写:

import torch
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline

device = "cuda:0" if torch.cuda.is_available() else "cpu"
dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float32

model_id = "scb10x/typhoon-whisper-turbo"
model = AutoModelForSpeechSeq2Seq.from_pretrained(
    model_id, torch_dtype=dtype, low_cpu_mem_usage=True, use_safetensors=True
).to(device)
processor = AutoProcessor.from_pretrained(model_id)

pipe = pipeline(
    "automatic-speech-recognition",
    model=model, tokenizer=processor.tokenizer,
    feature_extractor=processor.feature_extractor,
    max_new_tokens=448, chunk_length_s=30,
    batch_size=16, return_timestamps=True,
    torch_dtype=dtype, device=device,
)

result = pipe("thai_audio.wav", generate_kwargs={"language": "thai"})
print(result["text"])

封装成函数即可作为内部 API 使用:

def transcribe(audio_path: str) -> str:
    return pipe(audio_path, generate_kwargs={"language": "thai"})["text"]

几个参数值得记住(均对应仓库配置文件):

  • chunk_length_s=30:与 preprocessor_config.json 的 chunk_length 一致,长音频自动按 30 秒分块推理;
  • max_new_tokens=448:与 config.json 的 max_target_positions 一致;
  • return_timestamps=True:输出带时间戳的片段,方便做字幕对齐,时间戳 token 定义见 added_tokens.json;
  • batch_size=16:批量推理吞吐关键,显存紧张时可降到 4~8。

四、方案二:微服务化——FastAPI 异步转写服务

当多个客户端并发调用时,建议把模型装进一个独立微服务。核心思路:模型只加载一次 + 长任务丢进后台队列,避免每个请求重复推理阻塞。

import asyncio, uuid
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import JSONResponse
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline

app = FastAPI(title="Thai ASR Service")
pipe = None
results = {}  # task_id -> 结果(生产环境建议换成 Redis)

@app.on_event("startup")
def load_model():
    global pipe
    model = AutoModelForSpeechSeq2Seq.from_pretrained(
        "scb10x/typhoon-whisper-turbo", torch_dtype="auto",
        low_cpu_mem_usage=True, use_safetensors=True)
    proc = AutoProcessor.from_pretrained("scb10x/typhoon-whisper-turbo")
    pipe = pipeline("automatic-speech-recognition", model=model,
                    tokenizer=proc.tokenizer,
                    feature_extractor=proc.feature_extractor,
                    max_new_tokens=448, chunk_length_s=30, batch_size=16)

@app.post("/transcribe")
async def transcribe(file: UploadFile = File(...)):
    task_id = str(uuid.uuid4())
    asyncio.get_event_loop().run_in_executor(
        None, worker, task_id, file.file.read())
    return {"task_id": task_id}

def worker(task_id, audio_bytes):
    result = pipe({"raw": audio_bytes}, generate_kwargs={"language": "thai"})
    results[task_id] = result

@app.get("/result/{task_id}")
def get_result(task_id: str):
    if task_id not in results:
        return JSONResponse({"status": "pending"}, status_code=202)
    return results[task_id]

微服务落地的 3 个要点:

  1. 启动时预热模型:权重加载放进 startup 钩子,避免首个请求等待 30 秒以上;
  2. 任务化 + 轮询:转写是耗时操作,返回 task_id 让客户端轮询 /result/{task_id},天然支持大文件;
  3. 有状态隔离:示例用内存字典存结果,生产环境请换成 Redis 或对象存储,方便横向扩容多实例。

五、方案三:Web 端集成——前端上传音频获取泰语文本

有了微服务,Web 端只需"上传 → 拿 task_id → 轮询 → 渲染文本"。前端核心逻辑非常轻:

async function transcribe(file) {
  const form = new FormData();
  form.append("file", file);
  const { task_id } = await fetch("/transcribe", { method: "POST", body: form })
    .then(r => r.json());

  // 轮询直到完成
  while (true) {
    const res = await fetch(`/result/${task_id}`);
    if (res.status === 200) return res.json();
    await new Promise(r => setTimeout(r, 2000));
  }
}

返回结构可直接渲染,开启 return_timestamps 时还带分段时间轴,适合做字幕播放器、会议记录、语音客服质检等 UI:

{
  "text": "สวัสดีครับ วันนี้เราจะมาเรียนรู้เรื่องการติดตั้งโมเดล",
  "chunks": [{"timestamp": [0.0, 2.4], "text": "สวัสดีครับ"}]
}

🎧 前端采集音频时,浏览器 MediaRecorder 默认输出可能不是 16kHz,建议上传后用 ffmpeg 或 pydub 重采样为 16kHz 单声道,与 preprocessor_config.json 保持一致,可显著减少预处理抖动。

六、性能调优与避坑清单

场景 建议
GPU 推理 优先 bfloat16(模型默认精度,见 config.json 的 torch_dtype),速度接近翻倍
吞吐不够 调大 batch_size;多路请求时让微服务内部攒批
长音频 放心上传,30 秒自动分块;超大文件优先走方案二的任务队列
需要字幕对齐 return_timestamps=True,输出 chunks 时间轴
CPU 环境 可用但速度慢,建议 batch_size=1~2,dtype 用 float32

已知边界(来自 README.md 的 Limitations 说明):

  • 模型针对泰语优化,其他语言不建议使用;
  • 训练数据覆盖不到的方言/口音效果可能波动;
  • 定位是离线转写,流式实时场景请配合分块策略自行平滑延迟。

七、上手路线小结

  1. 验证效果 → 方案一脚本跑通,产出第一句泰语文本;
  2. 团队共享 → 方案二封成 FastAPI 微服务,任务化 + 队列;
  3. 产品化 → 方案三 Web 前端接入,配合时间戳做字幕/高亮展示。

模型基于 MIT License 发布(继承自 OpenAI Whisper),可放心商用;使用时请遵循 OpenTyphoon 的服务条款。更多背景与论文信息见 README.md。

登录后查看全文
typhoon-whisper-turbo