omni-dev 0.28.0

A powerful Git commit message analysis and amendment toolkit
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
//! Model storage convention and path resolution.
//!
//! Two distinct kinds of model are tracked by this module:
//!
//! - **Whisper ASR** (`tiny.en`), loaded by the `whisper-candle` backend.
//! - **Wespeaker speaker embedding** (`resnet34_LM`), loaded by the
//!   speaker-embedding subsystem added in #805 / ADR-0034.
//!
//! Both follow the same three-tier resolution priority:
//!
//! 1. Explicit `--model <path>` (Whisper) or `--speaker-model <path>`
//!    (wespeaker) on the relevant CLI command.
//! 2. `OMNI_DEV_VOICE_WHISPER_MODEL` / `OMNI_DEV_VOICE_SPEAKER_MODEL`
//!    env var.
//! 3. Default install location under the user's home directory.
//!
//! Sharing the helper means the install command writes to exactly the
//! place the backend later reads from — bugs can't diverge between
//! download-target and load-target.

use std::path::{Path, PathBuf};

use anyhow::{anyhow, Context, Result};

use crate::voice::VoiceOpts;

// ── Whisper constants (retained for backwards compatibility) ──────────────

/// HuggingFace repository identifier for the `tiny.en` Whisper variant.
pub const MODEL_ID: &str = "openai/whisper-tiny.en";

/// Pinned HuggingFace revision. `refs/pr/15` adds the safetensors weights
/// to `openai/whisper-tiny.en`; the candle spike in #813 validated this
/// exact revision end-to-end.
pub const REVISION: &str = "refs/pr/15";

/// The three files the Whisper backend needs to load. Order matters for
/// the install command's progress messages; the backend itself loads them
/// via [`required_files_in`] independent of order.
pub const REQUIRED_FILES: &[&str] = &["config.json", "tokenizer.json", "model.safetensors"];

/// Default subdirectory name beneath `~/.omni-dev/voice/models/`.
///
/// Derived from [`MODEL_ID`] by stripping the `openai/` org prefix; keeps
/// room for future variants (`whisper-base.en`, multilingual) as sibling
/// dirs.
pub const DEFAULT_VARIANT_DIR: &str = "whisper-tiny.en";

// ── ModelSpec shape ──────────────────────────────────────────────────────

/// Where the bytes of a model come from. Each variant carries the
/// transport-specific metadata the install command needs to fetch the
/// model exactly once and verify its integrity.
#[derive(Debug, Clone, Copy)]
pub enum ModelSource {
    /// HuggingFace Hub — Whisper's distribution. The install command
    /// uses `hf_hub::api::sync::Api` to download `required_files` at a
    /// pinned revision.
    HfHub {
        /// HF repository identifier, e.g. `"openai/whisper-tiny.en"`.
        repo_id: &'static str,
        /// Pinned revision (branch, tag, or ref).
        revision: &'static str,
    },
    /// A single signed GitHub release asset — wespeaker's distribution.
    /// The install command downloads the asset, verifies SHA-256, and
    /// atomically installs into `required_files[0]`.
    HttpReleaseAsset {
        /// Direct download URL.
        url: &'static str,
        /// Expected SHA-256 of the downloaded bytes (hex).
        sha256: &'static str,
        /// Expected size in bytes; informational, for progress messages.
        bytes: u64,
    },
}

/// Fully describes a model variant's storage, install transport, and CLI
/// surface. Static lifetime: every field is `&'static str` (or
/// `&'static [&'static str]`) so `ModelSpec` is `Copy` and `'static`.
#[derive(Debug, Clone, Copy)]
pub struct ModelSpec {
    /// CLI-facing variant identifier: `"whisper-tiny.en"` or
    /// `"speaker-wespeaker-en"`. Matches the `--variant` value the user
    /// passes to `voice install-model`.
    pub variant: &'static str,
    /// Human label used in error messages: `"Whisper"` or `"Speaker"`.
    pub kind_label: &'static str,
    /// Subdirectory beneath `~/.omni-dev/voice/models/` where this
    /// model's files live.
    pub default_subdir: &'static str,
    /// Files that must exist in the install directory for the model to
    /// be considered installed.
    pub required_files: &'static [&'static str],
    /// Environment-variable override for the install directory.
    pub env_var: &'static str,
    /// Recommended `install-model` invocation, used verbatim in the
    /// `ensure_model_present` error hint.
    pub install_command: &'static str,
    /// CLI flag that overrides the model path on consumer commands,
    /// e.g. `"--model"` (Whisper) or `"--speaker-model"` (wespeaker).
    pub model_flag: &'static str,
    /// How to fetch the bytes.
    pub source: ModelSource,
}

impl ModelSpec {
    /// Default install directory: `~/.omni-dev/voice/models/<default_subdir>/`.
    ///
    /// `None` when the user's home directory cannot be located — same
    /// failure mode as `dirs::home_dir()`.
    pub fn default_dir(&self) -> Option<PathBuf> {
        dirs::home_dir().map(|home| {
            home.join(".omni-dev")
                .join("voice")
                .join("models")
                .join(self.default_subdir)
        })
    }

    /// Resolves the install directory for this spec.
    ///
    /// Priority: `override_path` → env var → default. The returned path
    /// is *not* validated for existence; pair with [`Self::ensure_present`]
    /// for fail-fast.
    pub fn resolve_dir(&self, override_path: Option<&Path>) -> Result<PathBuf> {
        if let Some(p) = override_path {
            return Ok(p.to_path_buf());
        }
        if let Ok(env) = crate::utils::settings::get_env_var(self.env_var) {
            if !env.is_empty() {
                return Ok(PathBuf::from(env));
            }
        }
        self.default_dir().ok_or_else(|| {
            anyhow!(
                "could not determine home directory; \
                 pass {} <path> or set {}",
                self.model_flag,
                self.env_var
            )
        })
    }

    /// Returns the absolute path of each required file inside `dir`.
    pub fn required_files_in(&self, dir: &Path) -> Vec<PathBuf> {
        self.required_files.iter().map(|f| dir.join(f)).collect()
    }

    /// Verifies that `dir` contains every file in `self.required_files`.
    ///
    /// On failure, returns the install hint shaped for this spec (the
    /// `install_command` / `model_flag` baked into the spec).
    pub fn ensure_present(&self, dir: &Path) -> Result<()> {
        for file in self.required_files {
            let path = dir.join(file);
            if !path.is_file() {
                return Err(anyhow!(
                    "no {} model found at {}; \
                     run `{}` or pass {} <path>",
                    self.kind_label,
                    dir.display(),
                    self.install_command,
                    self.model_flag,
                ))
                .with_context(|| format!("missing required file: {}", path.display()));
            }
        }
        Ok(())
    }
}

// ── Registered specs ──────────────────────────────────────────────────────

/// Whisper `tiny.en` — production ASR runtime per ADR-0033.
pub const WHISPER_TINY_EN: ModelSpec = ModelSpec {
    variant: "whisper-tiny.en",
    kind_label: "Whisper",
    default_subdir: DEFAULT_VARIANT_DIR,
    required_files: REQUIRED_FILES,
    env_var: "OMNI_DEV_VOICE_WHISPER_MODEL",
    install_command: "omni-dev voice install-model",
    model_flag: "--model",
    source: ModelSource::HfHub {
        repo_id: MODEL_ID,
        revision: REVISION,
    },
};

/// Wespeaker `voxceleb_resnet34_LM` — production speaker-embedding
/// runtime per ADR-0034. Not yet wired to consumers; the speaker
/// install variant lands in a follow-up commit.
pub const SPEAKER_WESPEAKER_EN: ModelSpec = ModelSpec {
    variant: "speaker-wespeaker-en",
    kind_label: "Speaker",
    default_subdir: "wespeaker-en-voxceleb-resnet34-LM",
    required_files: &["wespeaker_en_voxceleb_resnet34_LM.onnx"],
    env_var: "OMNI_DEV_VOICE_SPEAKER_MODEL",
    install_command: "omni-dev voice install-model --variant speaker-wespeaker-en",
    model_flag: "--speaker-model",
    source: ModelSource::HttpReleaseAsset {
        url: "https://github.com/k2-fsa/sherpa-onnx/releases/download/speaker-recongition-models/wespeaker_en_voxceleb_resnet34_LM.onnx",
        sha256: "e9848563da86f263117134dfd7ad63c92355b37de492b55e325400c9d9c39012",
        bytes: 26_530_550,
    },
};

// ── Backwards-compatible Whisper helpers (thin shims) ────────────────────

/// Returns the absolute path of each required model file inside `dir`.
pub fn required_files_in(dir: &Path) -> Vec<PathBuf> {
    WHISPER_TINY_EN.required_files_in(dir)
}

/// Computes the default install location: `~/.omni-dev/voice/models/whisper-tiny.en/`.
///
/// Returns `None` only when the user's home directory cannot be located
/// (i.e. `dirs::home_dir()` returns `None`) — vanishingly rare in practice.
pub fn default_whisper_model_dir() -> Option<PathBuf> {
    WHISPER_TINY_EN.default_dir()
}

/// Resolves the Whisper model directory for the current invocation.
///
/// Priority: `opts.model` → `OMNI_DEV_VOICE_WHISPER_MODEL` → default.
/// The returned path is *not* validated for existence; callers that need
/// to fail-fast on missing files should pair this with [`ensure_model_present`].
pub fn resolve_whisper_model_dir(opts: &VoiceOpts) -> Result<PathBuf> {
    WHISPER_TINY_EN.resolve_dir(opts.model.as_deref())
}

/// Verifies that `dir` contains every file in [`REQUIRED_FILES`].
///
/// On failure, returns the install hint specified by issue #802:
/// `"no Whisper model found at <path>; run `omni-dev voice install-model`
/// or pass --model <path>"`.
pub fn ensure_model_present(dir: &Path) -> Result<()> {
    WHISPER_TINY_EN.ensure_present(dir)
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use std::sync::{Mutex, MutexGuard};

    static ENV_GUARD: Mutex<()> = Mutex::new(());

    fn env_guard() -> MutexGuard<'static, ()> {
        match ENV_GUARD.lock() {
            Ok(g) => g,
            Err(poisoned) => poisoned.into_inner(),
        }
    }

    #[test]
    fn opts_model_takes_top_priority() {
        let _g = env_guard();
        std::env::set_var("OMNI_DEV_VOICE_WHISPER_MODEL", "/should/not/be/read");
        let opts = VoiceOpts {
            backend: None,
            model: Some(PathBuf::from("/explicit/path")),
        };
        let resolved = resolve_whisper_model_dir(&opts).unwrap();
        assert_eq!(resolved, PathBuf::from("/explicit/path"));
        std::env::remove_var("OMNI_DEV_VOICE_WHISPER_MODEL");
    }

    #[test]
    fn env_var_used_when_opts_absent() {
        let _g = env_guard();
        std::env::set_var("OMNI_DEV_VOICE_WHISPER_MODEL", "/from/env");
        let resolved = resolve_whisper_model_dir(&VoiceOpts::default()).unwrap();
        assert_eq!(resolved, PathBuf::from("/from/env"));
        std::env::remove_var("OMNI_DEV_VOICE_WHISPER_MODEL");
    }

    #[test]
    fn empty_env_var_falls_through_to_default() {
        let _g = env_guard();
        std::env::set_var("OMNI_DEV_VOICE_WHISPER_MODEL", "");
        let resolved = resolve_whisper_model_dir(&VoiceOpts::default()).unwrap();
        let expected = default_whisper_model_dir().unwrap();
        assert_eq!(resolved, expected);
        std::env::remove_var("OMNI_DEV_VOICE_WHISPER_MODEL");
    }

    #[test]
    fn default_path_uses_omni_dev_voice_models_subdir() {
        let dir = default_whisper_model_dir().unwrap();
        assert!(dir.ends_with(".omni-dev/voice/models/whisper-tiny.en"));
    }

    #[test]
    fn ensure_model_present_succeeds_when_all_files_exist() {
        let tmp = tempfile::TempDir::new().unwrap();
        for f in REQUIRED_FILES {
            std::fs::write(tmp.path().join(f), b"placeholder").unwrap();
        }
        ensure_model_present(tmp.path()).unwrap();
    }

    #[test]
    fn ensure_model_present_errors_with_hint_when_files_missing() {
        let tmp = tempfile::TempDir::new().unwrap();
        let err = ensure_model_present(tmp.path()).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("no Whisper model found"), "got: {msg}");
        assert!(msg.contains("voice install-model"), "got: {msg}");
        assert!(msg.contains("--model"), "got: {msg}");
    }

    #[test]
    fn ensure_model_present_errors_when_any_file_missing() {
        let tmp = tempfile::TempDir::new().unwrap();
        // Write two of three required files; tokenizer.json missing.
        std::fs::write(tmp.path().join("config.json"), b"x").unwrap();
        std::fs::write(tmp.path().join("model.safetensors"), b"x").unwrap();
        let err = ensure_model_present(tmp.path()).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("tokenizer.json"), "got: {msg}");
    }

    #[test]
    fn required_files_in_returns_three_paths() {
        let paths = required_files_in(Path::new("/x"));
        assert_eq!(paths.len(), 3);
        assert_eq!(paths[0], PathBuf::from("/x/config.json"));
        assert_eq!(paths[1], PathBuf::from("/x/tokenizer.json"));
        assert_eq!(paths[2], PathBuf::from("/x/model.safetensors"));
    }

    // ── ModelSpec-shaped API tests ──────────────────────────────────────

    #[test]
    fn speaker_spec_default_dir_ends_with_wespeaker_subdir() {
        let dir = SPEAKER_WESPEAKER_EN.default_dir().unwrap();
        assert!(dir.ends_with(".omni-dev/voice/models/wespeaker-en-voxceleb-resnet34-LM"));
    }

    #[test]
    fn speaker_spec_resolve_dir_override_takes_priority() {
        let _g = env_guard();
        std::env::set_var("OMNI_DEV_VOICE_SPEAKER_MODEL", "/should/not/be/read");
        let resolved = SPEAKER_WESPEAKER_EN
            .resolve_dir(Some(Path::new("/explicit/path")))
            .unwrap();
        assert_eq!(resolved, PathBuf::from("/explicit/path"));
        std::env::remove_var("OMNI_DEV_VOICE_SPEAKER_MODEL");
    }

    #[test]
    fn speaker_spec_resolve_dir_env_var_used_when_override_absent() {
        let _g = env_guard();
        std::env::set_var("OMNI_DEV_VOICE_SPEAKER_MODEL", "/from/env");
        let resolved = SPEAKER_WESPEAKER_EN.resolve_dir(None).unwrap();
        assert_eq!(resolved, PathBuf::from("/from/env"));
        std::env::remove_var("OMNI_DEV_VOICE_SPEAKER_MODEL");
    }

    #[test]
    fn speaker_spec_ensure_present_errors_with_install_hint() {
        let tmp = tempfile::TempDir::new().unwrap();
        let err = SPEAKER_WESPEAKER_EN.ensure_present(tmp.path()).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("no Speaker model found"), "got: {msg}");
        assert!(msg.contains("--variant speaker-wespeaker-en"), "got: {msg}");
        assert!(msg.contains("--speaker-model"), "got: {msg}");
        assert!(
            msg.contains("wespeaker_en_voxceleb_resnet34_LM.onnx"),
            "got: {msg}"
        );
    }

    #[test]
    fn speaker_spec_ensure_present_succeeds_when_file_exists() {
        let tmp = tempfile::TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("wespeaker_en_voxceleb_resnet34_LM.onnx"),
            b"placeholder",
        )
        .unwrap();
        SPEAKER_WESPEAKER_EN.ensure_present(tmp.path()).unwrap();
    }

    #[test]
    fn whisper_spec_required_files_matches_legacy_helper() {
        let dir = Path::new("/x");
        assert_eq!(
            WHISPER_TINY_EN.required_files_in(dir),
            required_files_in(dir)
        );
    }

    #[test]
    fn whisper_spec_source_carries_pinned_hf_metadata() {
        match WHISPER_TINY_EN.source {
            ModelSource::HfHub { repo_id, revision } => {
                assert_eq!(repo_id, MODEL_ID);
                assert_eq!(revision, REVISION);
            }
            ModelSource::HttpReleaseAsset { .. } => {
                panic!("WHISPER_TINY_EN should be HfHub-sourced");
            }
        }
    }

    #[test]
    fn speaker_spec_source_carries_pinned_release_metadata() {
        match SPEAKER_WESPEAKER_EN.source {
            ModelSource::HttpReleaseAsset { url, sha256, bytes } => {
                assert!(url.contains("wespeaker_en_voxceleb_resnet34_LM.onnx"));
                assert_eq!(
                    sha256,
                    "e9848563da86f263117134dfd7ad63c92355b37de492b55e325400c9d9c39012"
                );
                assert_eq!(bytes, 26_530_550);
            }
            ModelSource::HfHub { .. } => {
                panic!("SPEAKER_WESPEAKER_EN should be HttpReleaseAsset-sourced");
            }
        }
    }
}