use std::path::Path;
use crate::error::{AudioError, AudioResult};
use super::checkpoint::WhisperDims;
pub(crate) const fn fallback_repo(n_vocab: u32) -> Option<&'static str> {
match n_vocab {
51866 => Some("openai/whisper-large-v3-turbo"),
51865 => Some("openai/whisper-large-v2"),
51864 => Some("openai/whisper-base.en"),
_ => None,
}
}
fn load_tokenizer_file(path: &Path) -> AudioResult<tokenizers::Tokenizer> {
tokenizers::Tokenizer::from_file(path).map_err(|e| AudioError::Stt {
provider: "MLX".into(),
message: format!("failed to load tokenizer {}: {e}", path.display()),
})
}
pub(crate) async fn resolve_tokenizer(
model_dir: &Path,
dims: &WhisperDims,
) -> AudioResult<tokenizers::Tokenizer> {
let local_path = model_dir.join("tokenizer.json");
if local_path.is_file() {
return load_tokenizer_file(&local_path);
}
let Some(repo) = fallback_repo(dims.n_vocab) else {
return Err(AudioError::Stt {
provider: "MLX".into(),
message: format!(
"no known Whisper tokenizer for n_vocab {}; add tokenizer.json to {}",
dims.n_vocab,
model_dir.display()
),
});
};
let api = hf_hub::api::tokio::Api::new().map_err(|e| AudioError::Stt {
provider: "MLX".into(),
message: format!("failed to initialize HuggingFace API client: {e}"),
})?;
let tokenizer_path =
api.model(repo.to_string()).get("tokenizer.json").await.map_err(|e| AudioError::Stt {
provider: "MLX".into(),
message: format!("failed to download tokenizer.json from {repo}: {e}"),
})?;
load_tokenizer_file(&tokenizer_path)
}
#[cfg(test)]
mod tests {
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use super::*;
static NEXT_ID: AtomicU64 = AtomicU64::new(0);
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(name: &str) -> Self {
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir()
.join(format!("adk-audio-mlx-tokenizer-{}-{name}-{id}", std::process::id()));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("create temp dir");
Self { path }
}
fn path(&self) -> &Path {
&self.path
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
fn dummy_dims(n_vocab: u32) -> WhisperDims {
WhisperDims {
n_mels: 80,
n_audio_ctx: 1500,
n_audio_state: 384,
n_audio_head: 6,
n_audio_layer: 4,
n_vocab,
n_text_ctx: 448,
n_text_state: 384,
n_text_head: 6,
n_text_layer: 4,
}
}
#[test]
fn fallback_repo_maps_known_vocabs() {
assert_eq!(fallback_repo(51866), Some("openai/whisper-large-v3-turbo"));
assert_eq!(fallback_repo(51865), Some("openai/whisper-large-v2"));
assert_eq!(fallback_repo(51864), Some("openai/whisper-base.en"));
assert_eq!(fallback_repo(1), None);
}
#[tokio::test]
async fn resolve_prefers_local_tokenizer() {
let dir = TempDir::new("local");
let tok_path = dir.path().join("tokenizer.json");
tokenizers::Tokenizer::new(tokenizers::models::bpe::BPE::default())
.save(&tok_path, false)
.expect("save minimal tokenizer.json");
let dims = dummy_dims(1);
let tok = resolve_tokenizer(dir.path(), &dims)
.await
.expect("should load local tokenizer.json without network");
assert_eq!(tok.get_vocab_size(true), 0);
}
#[tokio::test]
async fn resolve_unknown_vocab_errors() {
let dir = TempDir::new("unknown-vocab");
let dims = dummy_dims(1);
let err = resolve_tokenizer(dir.path(), &dims)
.await
.expect_err("unknown n_vocab without local tokenizer.json must fail");
match err {
AudioError::Stt { provider, message } => {
assert_eq!(provider, "MLX");
assert_eq!(
message,
format!(
"no known Whisper tokenizer for n_vocab 1; add tokenizer.json to {}",
dir.path().display()
)
);
}
other => panic!("unexpected error: {other}"),
}
}
}