使用 WhisperKit 开发时避免与 HuggingFace 的网络连接

分类
技术
标签
工具推荐

在使用 WhisperKit 进行开发的时候,我们发现它默认会与 HuggingFace 的服务器进行连接。这对于一些网络环境不佳或者对网络流量有限制的场景下,可能会导致无法使用等问题。
为此我依靠 https://github.com/argmaxinc/WhisperKit/issues/81 提供的相关信息进行探索,并最终实现了该需求。

设置

WhisperKit 在加载模型时需要加载两个东西:一是模型本身,如openai_whisper-large-v3-v20240930_547MB,二是模型对应的tokenizer。为了实现本地加载,我们需要同时提供这两个文件。参考加载函数如下
1func setupWhisper() async { 2 do { 3 await MainActor.run { 4 loadingState = .loading 5 } 6 guard let modelPath = Bundle.main.url(forResource: "openai_whisper-large-v3-v20240930_547MB", withExtension: nil), 7 let tokenizerPath = Bundle.main.url(forResource: "tokenizerFolder", withExtension: nil) else { 8 print("无法找到模型或分词器文件") 9 await MainActor.run { 10 loadingState = .notLoaded 11 } 12 return 13 } 14 15 whisperKit = try await WhisperKit(modelFolder: modelPath.path, tokenizerFolder: tokenizerPath) 16 try await whisperKit?.loadModels(prewarmMode: true) 17 18 await MainActor.run { 19 loadingState = .loaded 20 if let variant = whisperKit?.modelVariant { 21 currentModel = variant.description 22 } 23 } 24 print("Whisper 模型加载成功: \(currentModel)") 25 } catch { 26 print("Whisper 初始化失败: \(error)") 27 await MainActor.run { 28 loadingState = .notLoaded 29 } 30 } 31 }
需要关注的是,你需要在 Build PhasesCopy Bundle Resources 中将模型文件和分词器文件添加到 bundle 中。
Ball TriangleAnimated representation of three balls
notion image

附件

为了方便下载和管理模型,编写了如下 ci 脚本
1#!/bin/sh 2# ci_scripts/ci_pre_xcodebuild.sh 3echo "setup whisperkit" 4export WHISPER_VARIANT=large-v3-v20240930_547MB 5export TOKENIZER_VARIANT=openai/whisper-large-v3 6git clone https://github.com/argmaxinc/whisperkit.git 7cd whisperkit 8make setup 9make download-model MODEL=$WHISPER_VARIANT 10mkdir -p tokenizerFolder/models/$TOKENIZER_VARIANT 11GIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/$TOKENIZER_VARIANT tokenizerFolder/models/$TOKENIZER_VARIANT 12echo "whisperkit setup done"
其中 WHISPER_VARIANT 可以在 WhisperKit 提供的 HuggingFace 中的仓库找到,即 https://huggingface.co/argmaxinc/whisperkit-coreml
TOKENIZER_VARIANT 需要参考 https://github.com/argmaxinc/WhisperKit/blob/0af71463b035bd9915c9b989ae670275ddad0928/Sources/WhisperKit/Core/Utils.swift#L366 里的case来确认具体值;其具体tokenizer根据不同模型其variant来决定。不同模型的variant你可以在加载之后通过whisperKit?.modelVariant来获悉。
值得注意的是,当你挂载 tokenizerFolder 的时候必须将 tokenizerFolder 直接挂载进去并保留 tokenizerFolder/models/openai/whisper-large-v3 的文件结构。