adk-audio 3.0.0

Audio intelligence and pipeline orchestration for ADK-Rust agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! MLX STT provider for Apple Silicon.

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;

/// MLX-based Whisper STT provider using Metal GPU on Apple Silicon.
///
/// On Apple Silicon (`aarch64-apple-darwin`), runs Whisper models locally via
/// `mlx-rs` on Metal GPU with unified memory on a dedicated inference thread
/// so the async runtime never blocks; requests are served one at a time in
/// arrival order, and callers beyond the queue wait asynchronously for a slot.
/// On non-Apple-Silicon targets, `--features mlx` compiles (load-only) and
/// `transcribe` returns [`AudioError::Stt`] stating Apple Silicon is required.
///
/// Building `--features mlx` (or `--features all`) on Apple Silicon requires
/// `cmake` and Xcode's Metal toolchain.
///
/// # Audio, language, and decoding
///
/// Any sample rate and channel count is accepted: audio is downmixed to mono,
/// resampled to 16 kHz, and processed in 30-second windows up to
/// [`MlxSttConfig::max_duration_secs`] (600 s by default). Multilingual
/// checkpoints default to `"en"` when [`SttOptions::language`] is `None` (no
/// language detection); English-only (`.en`, `n_vocab < 51865`) checkpoints
/// ignore `SttOptions::language` and prompt with `[sot, notimestamps]`.
///
/// Decoding is greedy and suppresses only the special tokens (start of
/// transcript, language, task, no-speech) and timestamps; Whisper's
/// non-speech symbol list and blank suppression are not applied.
/// [`SttProvider::transcribe_stream`] is not implemented and returns
/// [`AudioError::Stt`].
///
/// # Checkpoints and tokenizers
///
/// Supports unquantized safetensors checkpoints (`weights.safetensors` or
/// `model.safetensors`), defaulting to `mlx-community/whisper-large-v3-turbo`
/// and supporting `mlx-community/whisper-*-fp16`. `.npz`-only and quantized
/// (`-4bit`/`-8bit`) checkpoints return [`AudioError::Stt`].
///
/// Uses `tokenizer.json` in the model directory when present; otherwise
/// downloads only `tokenizer.json` from the matching `openai/whisper-*`
/// repository based on `config.json` `n_vocab`.
///
/// # Recovery
///
/// If the inference thread dies (a panic inside MLX), the provider stays
/// unusable: every later `transcribe` returns `MLX worker stopped`. Create a
/// new provider to recover.
pub struct MlxSttProvider {
    config: MlxSttConfig,
    checkpoint: Checkpoint,
    /// Inference thread; `None` for `with_dummy` instances.
    #[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(),
    }
}

/// Whisper language code for a BCP-47 tag: its lowercased primary subtag
/// (`en-US` → `en`). Empty tags mean "not given".
#[cfg_attr(not(all(target_os = "macos", target_arch = "aarch64")), allow(dead_code))] // tests only
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 {
    /// Create a test instance without downloading a model.
    ///
    /// It has no model: on Apple Silicon `transcribe` returns an error.
    #[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,
        }
    }

    /// Load model from HuggingFace Hub or local cache.
    ///
    /// On Apple Silicon this also uploads the weights to the GPU and starts the
    /// dedicated inference thread, so it takes a few seconds for large models.
    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,
        })
    }

    /// Convenience: load default Whisper large-v3-turbo with default registry.
    pub async fn default_whisper() -> AudioResult<Self> {
        let registry = LocalModelRegistry::default();
        Self::new(MlxSttConfig::default(), &registry).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(),
                });
            };
            // `Bytes` clone is a refcount bump, not a copy of the PCM.
            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, &registry).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, &registry).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, &registry).await {
            Err(err) => err,
            Ok(_) => panic!("npz must fail"),
        };
        assert!(err.to_string().contains("weights.npz"), "err: {err}");
    }
}