ACQUIRING IMAGE…

LOG ENTRYCAT / 技术

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

介绍如何在 WhisperKit 开发中配置本地模型加载,避免与 HuggingFace 服务器的网络连接。

工具推荐

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

设置

WhisperKit 在加载模型时需要加载两个东西:一是模型本身,如openai_whisper-large-v3-v20240930_547MB,二是模型对应的tokenizer。为了实现本地加载,我们需要同时提供这两个文件。参考加载函数如下
func setupWhisper() async {
        do {
            await MainActor.run {
                loadingState = .loading
            }
            guard let modelPath = Bundle.main.url(forResource: "openai_whisper-large-v3-v20240930_547MB", withExtension: nil),
                  let tokenizerPath = Bundle.main.url(forResource: "tokenizerFolder", withExtension: nil) else {
                print("无法找到模型或分词器文件")
                await MainActor.run {
                    loadingState = .notLoaded
                }
                return
            }

            whisperKit = try await WhisperKit(modelFolder: modelPath.path, tokenizerFolder: tokenizerPath)
            try await whisperKit?.loadModels(prewarmMode: true)

            await MainActor.run {
                loadingState = .loaded
                if let variant = whisperKit?.modelVariant {
                    currentModel = variant.description
                }
            }
            print("Whisper 模型加载成功: \(currentModel)")
        } catch {
            print("Whisper 初始化失败: \(error)")
            await MainActor.run {
                loadingState = .notLoaded
            }
        }
    }
需要关注的是,你需要在 Build PhasesCopy Bundle Resources 中将模型文件和分词器文件添加到 bundle 中。
ACQUIRING IMAGE…

附件

为了方便下载和管理模型,编写了如下 ci 脚本
#!/bin/sh
# ci_scripts/ci_pre_xcodebuild.sh
echo "setup whisperkit"
export WHISPER_VARIANT=large-v3-v20240930_547MB
export TOKENIZER_VARIANT=openai/whisper-large-v3
git clone https://github.com/argmaxinc/whisperkit.git
cd whisperkit
make setup
make download-model MODEL=$WHISPER_VARIANT
mkdir -p tokenizerFolder/models/$TOKENIZER_VARIANT
GIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/$TOKENIZER_VARIANT tokenizerFolder/models/$TOKENIZER_VARIANT
echo "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 的文件结构。