use std::pin::Pin;
use async_trait::async_trait;
use futures::Stream;
use crate::error::{AudioError, AudioResult};
use crate::frame::AudioFrame;
use crate::registry::LocalModelRegistry;
use crate::traits::{SttOptions, SttProvider, Transcript};
use super::checkpoint::{self, Checkpoint, WhisperDims};
use super::config::MlxSttConfig;
use super::tokenizer;
pub struct MlxSttProvider {
config: MlxSttConfig,
checkpoint: Checkpoint,
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
worker: Option<super::whisper::worker::WhisperWorker>,
}
#[cold]
#[cfg_attr(all(target_os = "macos", target_arch = "aarch64"), allow(dead_code))]
pub(crate) fn unsupported_platform() -> AudioError {
AudioError::Stt {
provider: "MLX".into(),
message: "MLX inference requires Apple Silicon (aarch64-apple-darwin); use whisper-onnx \
or a cloud STT provider"
.into(),
}
}
#[cfg_attr(not(all(target_os = "macos", target_arch = "aarch64")), allow(dead_code))] fn whisper_language(bcp47: Option<&str>) -> Option<Box<str>> {
let primary = bcp47?.split(['-', '_']).next()?;
(!primary.is_empty()).then(|| primary.to_ascii_lowercase().into_boxed_str())
}
impl MlxSttProvider {
#[doc(hidden)]
pub fn with_dummy() -> Self {
Self {
config: MlxSttConfig::default(),
checkpoint: Checkpoint {
dims: WhisperDims {
n_mels: 80,
n_audio_ctx: 1500,
n_audio_state: 384,
n_audio_head: 6,
n_audio_layer: 4,
n_vocab: 51865,
n_text_ctx: 448,
n_text_state: 384,
n_text_head: 6,
n_text_layer: 4,
},
weights: std::path::PathBuf::from("/tmp/model/weights.safetensors"),
},
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
worker: None,
}
}
pub async fn new(config: MlxSttConfig, registry: &LocalModelRegistry) -> AudioResult<Self> {
let model_path = registry.get_or_download(&config.model_id).await?;
let checkpoint = checkpoint::inspect(&model_path)?;
let tokenizer = tokenizer::resolve_tokenizer(&model_path, &checkpoint.dims).await?;
#[cfg(not(all(target_os = "macos", target_arch = "aarch64")))]
drop(tokenizer);
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
let worker = {
use super::whisper::model::Whisper;
use super::whisper::worker::WhisperWorker;
let ck = checkpoint.clone();
let max_duration_secs = config.max_duration_secs;
let spawn = move || {
WhisperWorker::spawn(
move || Ok((Whisper::load(&ck)?, tokenizer)),
max_duration_secs,
)
};
let worker =
tokio::task::spawn_blocking(spawn).await.map_err(|e| AudioError::Stt {
provider: "MLX".into(),
message: format!("MLX model load task failed: {e}"),
})??;
Some(worker)
};
Ok(Self {
config,
checkpoint,
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
worker,
})
}
pub async fn default_whisper() -> AudioResult<Self> {
let registry = LocalModelRegistry::default();
Self::new(MlxSttConfig::default(), ®istry).await
}
}
impl std::fmt::Debug for MlxSttProvider {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut s = f.debug_struct("MlxSttProvider");
s.field("model_id", &self.config.model_id)
.field("weights", &self.checkpoint.weights)
.field("dims", &self.checkpoint.dims);
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
s.field("loaded", &self.worker.is_some());
s.finish_non_exhaustive()
}
}
#[async_trait]
impl SttProvider for MlxSttProvider {
async fn transcribe(&self, audio: &AudioFrame, opts: &SttOptions) -> AudioResult<Transcript> {
if audio.data.len() < 2 {
return Err(AudioError::Stt {
provider: "MLX".into(),
message: "empty audio input".into(),
});
}
#[cfg(not(all(target_os = "macos", target_arch = "aarch64")))]
{
let _ = opts;
Err(unsupported_platform())
}
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
{
let Some(worker) = &self.worker else {
return Err(AudioError::Stt {
provider: "MLX".into(),
message: "no model loaded: this instance comes from \
`MlxSttProvider::with_dummy`; use `MlxSttProvider::new`"
.into(),
});
};
let language = whisper_language(opts.language.as_deref());
worker.transcribe(audio.data.clone(), audio.sample_rate, audio.channels, language).await
}
}
async fn transcribe_stream(
&self,
_audio: Pin<Box<dyn Stream<Item = AudioFrame> + Send>>,
_opts: &SttOptions,
) -> AudioResult<crate::TranscriptStream> {
Err(AudioError::Stt {
provider: "MLX".into(),
message: "streaming transcription not yet implemented; call `transcribe` with the \
buffered audio"
.into(),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unsupported_platform_message() {
let msg = unsupported_platform().to_string();
assert!(msg.contains("requires Apple Silicon (aarch64-apple-darwin)"), "msg: {msg}");
assert!(msg.contains("whisper-onnx"), "msg: {msg}");
assert_eq!(
msg,
"STT error (MLX): MLX inference requires Apple Silicon (aarch64-apple-darwin); use \
whisper-onnx or a cloud STT provider"
);
}
#[tokio::test]
async fn transcribe_stream_returns_explicit_unimplemented_error() {
let provider = MlxSttProvider::with_dummy();
let result = provider
.transcribe_stream(Box::pin(futures::stream::empty()), &SttOptions::default())
.await;
match result {
Err(AudioError::Stt { provider, message }) => {
assert_eq!(provider, "MLX");
assert!(message.contains("not yet implemented"));
}
Err(err) => panic!("unexpected audio error: {err}"),
Ok(_) => panic!("expected explicit STT error"),
}
}
struct TempCache {
cache_dir: std::path::PathBuf,
}
impl TempCache {
fn new(name: &str) -> Self {
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT_ID: AtomicU64 = AtomicU64::new(0);
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
let cache_dir = std::env::temp_dir()
.join(format!("adk-audio-mlx-stt-{}-{name}-{id}", std::process::id()));
let _ = std::fs::remove_dir_all(&cache_dir);
std::fs::create_dir_all(&cache_dir).unwrap();
Self { cache_dir }
}
fn model_dir(&self, slug: &str) -> std::path::PathBuf {
let cfg = r#"{"n_mels":80,"n_audio_ctx":1500,"n_audio_state":384,"n_audio_head":6,"n_audio_layer":4,"n_vocab":51865,"n_text_ctx":448,"n_text_state":384,"n_text_head":6,"n_text_layer":4}"#;
self.model_dir_with(slug, cfg)
}
fn model_dir_with(&self, slug: &str, config_json: &str) -> std::path::PathBuf {
let dir = self.cache_dir.join(slug);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("config.json"), config_json).unwrap();
dir
}
}
impl Drop for TempCache {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.cache_dir);
}
}
#[test]
fn provider_is_send_sync() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<MlxSttProvider>();
}
#[test]
fn whisper_language_takes_primary_subtag() {
assert_eq!(whisper_language(None), None);
assert_eq!(whisper_language(Some("")), None);
assert_eq!(whisper_language(Some("en")).as_deref(), Some("en"));
assert_eq!(whisper_language(Some("en-US")).as_deref(), Some("en"));
assert_eq!(whisper_language(Some("PT_br")).as_deref(), Some("pt"));
}
fn assert_stt_error(result: AudioResult<Transcript>, expected: &str) {
match result {
Err(AudioError::Stt { provider, message }) => {
assert_eq!(provider, "MLX");
assert!(message.contains(expected), "{message:?} lacks {expected:?}");
}
Err(e) => panic!("unexpected error {e}"),
Ok(t) => panic!("expected error, got {t:?}"),
}
}
#[tokio::test]
async fn transcribe_empty_audio_errors() {
let provider = MlxSttProvider::with_dummy();
let empty = AudioFrame::new(bytes::Bytes::new(), 16_000, 1);
assert_stt_error(provider.transcribe(&empty, &SttOptions::default()).await, "empty audio");
}
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
#[tokio::test]
async fn dummy_transcribe_errors() {
let provider = MlxSttProvider::with_dummy();
let audio = AudioFrame::new(vec![0u8; 3200], 16_000, 1);
assert_stt_error(
provider.transcribe(&audio, &SttOptions::default()).await,
"no model loaded",
);
}
#[cfg(not(all(target_os = "macos", target_arch = "aarch64")))]
#[tokio::test]
async fn transcribe_reports_unsupported_platform() {
let provider = MlxSttProvider::with_dummy();
let audio = AudioFrame::new(vec![0u8; 3200], 16_000, 1);
let result = provider.transcribe(&audio, &SttOptions::default()).await;
assert_eq!(result.unwrap_err().to_string(), unsupported_platform().to_string());
}
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn new_loads_checkpoint_and_transcribes() {
use crate::mlx::whisper::model::tests::save_random;
use crate::mlx::whisper::worker::tests::{test_dims, test_tokenizer};
let cache = TempCache::new("ok");
let d = test_dims();
let cfg = format!(
r#"{{"n_mels":{},"n_audio_ctx":{},"n_audio_state":{},"n_audio_head":{},"n_audio_layer":{},"n_vocab":{},"n_text_ctx":{},"n_text_state":{},"n_text_head":{},"n_text_layer":{}}}"#,
d.n_mels,
d.n_audio_ctx,
d.n_audio_state,
d.n_audio_head,
d.n_audio_layer,
d.n_vocab,
d.n_text_ctx,
d.n_text_state,
d.n_text_head,
d.n_text_layer
);
let model_dir = cache.model_dir_with("test-org--whisper-tiny", &cfg);
save_random(d, 3, &model_dir.join("weights.safetensors"));
test_tokenizer().save(model_dir.join("tokenizer.json"), false).unwrap();
let registry = LocalModelRegistry::new(&cache.cache_dir);
let config = MlxSttConfig {
model_id: "test-org/whisper-tiny".into(),
max_duration_secs: 1,
..Default::default()
};
let provider = MlxSttProvider::new(config, ®istry).await.expect("new should succeed");
assert_eq!(provider.checkpoint.dims, d);
assert!(provider.checkpoint.weights.ends_with("weights.safetensors"));
let clip = AudioFrame::new(vec![0x10u8; 6400], 16_000, 1);
let opts = SttOptions::default().with_language("en-US");
let transcript = provider.transcribe(&clip, &opts).await.expect("transcribe");
assert_eq!(transcript.language_detected.as_deref(), Some("en"));
let long = AudioFrame::new(vec![0u8; 48_000], 16_000, 1);
assert_stt_error(
provider.transcribe(&long, &SttOptions::default()).await,
"audio is 1.5 s, over the 1 s limit",
);
}
#[cfg(not(all(target_os = "macos", target_arch = "aarch64")))]
#[tokio::test]
async fn new_loads_local_checkpoint_and_tokenizer() {
let cache = TempCache::new("ok");
let model_dir = cache.model_dir("test-org--whisper-tiny");
let header =
br#"{"encoder.conv1.weight":{"dtype":"F16","shape":[1],"data_offsets":[0,2]}}"#;
let mut weights = Vec::with_capacity(8 + header.len() + 2);
weights.extend_from_slice(&(header.len() as u64).to_le_bytes());
weights.extend_from_slice(header);
weights.extend_from_slice(&[0u8, 0u8]);
std::fs::write(model_dir.join("weights.safetensors"), weights).unwrap();
tokenizers::Tokenizer::new(tokenizers::models::bpe::BPE::default())
.save(model_dir.join("tokenizer.json"), false)
.unwrap();
let registry = LocalModelRegistry::new(&cache.cache_dir);
let config =
MlxSttConfig { model_id: "test-org/whisper-tiny".into(), ..Default::default() };
let provider = MlxSttProvider::new(config, ®istry).await.expect("new should succeed");
assert_eq!(provider.checkpoint.dims.n_vocab, 51865);
assert!(provider.checkpoint.weights.ends_with("weights.safetensors"));
}
#[tokio::test]
async fn new_rejects_npz_checkpoint() {
let cache = TempCache::new("npz");
let model_dir = cache.model_dir("test-org--whisper-npz");
std::fs::write(model_dir.join("weights.npz"), b"PK\x03\x04").unwrap();
let registry = LocalModelRegistry::new(&cache.cache_dir);
let config = MlxSttConfig { model_id: "test-org/whisper-npz".into(), ..Default::default() };
let err = match MlxSttProvider::new(config, ®istry).await {
Err(err) => err,
Ok(_) => panic!("npz must fail"),
};
assert!(err.to_string().contains("weights.npz"), "err: {err}");
}
}